git-remote-mediawiki: don't "use encoding 'utf8';"
[git.git] / contrib / mw-to-git / git-remote-mediawiki
1 #! /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.
12 #   https://github.com/Bibzball/Git-Mediawiki/wiki
13 #
14 # Known limitations:
15 #
16 # - Only wiki pages are managed, no support for [[File:...]]
17 #   attachments.
18 #
19 # - Poor performance in the best case: it takes forever to check
20 #   whether we're up-to-date (on fetch or push) or to fetch a few
21 #   revisions from a large wiki, because we use exclusively a
22 #   page-based synchronization. We could switch to a wiki-wide
23 #   synchronization when the synchronization involves few revisions
24 #   but the wiki is large.
25 #
26 # - Git renames could be turned into MediaWiki renames (see TODO
27 #   below)
28 #
29 # - login/password support requires the user to write the password
30 #   cleartext in a file (see TODO below).
31 #
32 # - No way to import "one page, and all pages included in it"
33 #
34 # - Multiple remote MediaWikis have not been very well tested.
35
36 use strict;
37 use MediaWiki::API;
38 use DateTime::Format::ISO8601;
39
40 # By default, use UTF-8 to communicate with Git and the user
41 binmode STDERR, ":utf8";
42 binmode STDOUT, ":utf8";
43
44 use URI::Escape;
45 use IPC::Open2;
46
47 use warnings;
48
49 # Mediawiki filenames can contain forward slashes. This variable decides by which pattern they should be replaced
50 use constant SLASH_REPLACEMENT => "%2F";
51
52 # It's not always possible to delete pages (may require some
53 # priviledges). Deleted pages are replaced with this content.
54 use constant DELETED_CONTENT => "[[Category:Deleted]]\n";
55
56 # It's not possible to create empty pages. New empty files in Git are
57 # sent with this content instead.
58 use constant EMPTY_CONTENT => "<!-- empty page -->\n";
59
60 # used to reflect file creation or deletion in diff.
61 use constant NULL_SHA1 => "0000000000000000000000000000000000000000";
62
63 my $remotename = $ARGV[0];
64 my $url = $ARGV[1];
65
66 # Accept both space-separated and multiple keys in config file.
67 # Spaces should be written as _ anyway because we'll use chomp.
68 my @tracked_pages = split(/[ \n]/, run_git("config --get-all remote.". $remotename .".pages"));
69 chomp(@tracked_pages);
70
71 # Just like @tracked_pages, but for MediaWiki categories.
72 my @tracked_categories = split(/[ \n]/, run_git("config --get-all remote.". $remotename .".categories"));
73 chomp(@tracked_categories);
74
75 my $wiki_login = run_git("config --get remote.". $remotename .".mwLogin");
76 # TODO: ideally, this should be able to read from keyboard, but we're
77 # inside a remote helper, so our stdin is connect to git, not to a
78 # terminal.
79 my $wiki_passwd = run_git("config --get remote.". $remotename .".mwPassword");
80 my $wiki_domain = run_git("config --get remote.". $remotename .".mwDomain");
81 chomp($wiki_login);
82 chomp($wiki_passwd);
83 chomp($wiki_domain);
84
85 # Import only last revisions (both for clone and fetch)
86 my $shallow_import = run_git("config --get --bool remote.". $remotename .".shallow");
87 chomp($shallow_import);
88 $shallow_import = ($shallow_import eq "true");
89
90 # Dumb push: don't update notes and mediawiki ref to reflect the last push.
91 #
92 # Configurable with mediawiki.dumbPush, or per-remote with
93 # remote.<remotename>.dumbPush.
94 #
95 # This means the user will have to re-import the just-pushed
96 # revisions. On the other hand, this means that the Git revisions
97 # corresponding to MediaWiki revisions are all imported from the wiki,
98 # regardless of whether they were initially created in Git or from the
99 # web interface, hence all users will get the same history (i.e. if
100 # the push from Git to MediaWiki loses some information, everybody
101 # will get the history with information lost). If the import is
102 # deterministic, this means everybody gets the same sha1 for each
103 # MediaWiki revision.
104 my $dumb_push = run_git("config --get --bool remote.$remotename.dumbPush");
105 unless ($dumb_push) {
106         $dumb_push = run_git("config --get --bool mediawiki.dumbPush");
107 }
108 chomp($dumb_push);
109 $dumb_push = ($dumb_push eq "true");
110
111 my $wiki_name = $url;
112 $wiki_name =~ s/[^\/]*:\/\///;
113 # If URL is like http://user:password@example.com/, we clearly don't
114 # want the password in $wiki_name. While we're there, also remove user
115 # and '@' sign, to avoid author like MWUser@HTTPUser@host.com
116 $wiki_name =~ s/^.*@//;
117
118 # Commands parser
119 my $entry;
120 my @cmd;
121 while (<STDIN>) {
122         chomp;
123         @cmd = split(/ /);
124         if (defined($cmd[0])) {
125                 # Line not blank
126                 if ($cmd[0] eq "capabilities") {
127                         die("Too many arguments for capabilities") unless (!defined($cmd[1]));
128                         mw_capabilities();
129                 } elsif ($cmd[0] eq "list") {
130                         die("Too many arguments for list") unless (!defined($cmd[2]));
131                         mw_list($cmd[1]);
132                 } elsif ($cmd[0] eq "import") {
133                         die("Invalid arguments for import") unless ($cmd[1] ne "" && !defined($cmd[2]));
134                         mw_import($cmd[1]);
135                 } elsif ($cmd[0] eq "option") {
136                         die("Too many arguments for option") unless ($cmd[1] ne "" && $cmd[2] ne "" && !defined($cmd[3]));
137                         mw_option($cmd[1],$cmd[2]);
138                 } elsif ($cmd[0] eq "push") {
139                         mw_push($cmd[1]);
140                 } else {
141                         print STDERR "Unknown command. Aborting...\n";
142                         last;
143                 }
144         } else {
145                 # blank line: we should terminate
146                 last;
147         }
148
149         BEGIN { $| = 1 } # flush STDOUT, to make sure the previous
150                          # command is fully processed.
151 }
152
153 ########################## Functions ##############################
154
155 ## credential API management (generic functions)
156
157 sub credential_from_url {
158         my $url = shift;
159         my $parsed = URI->new($url);
160         my %credential;
161
162         if ($parsed->scheme) {
163                 $credential{protocol} = $parsed->scheme;
164         }
165         if ($parsed->host) {
166                 $credential{host} = $parsed->host;
167         }
168         if ($parsed->path) {
169                 $credential{path} = $parsed->path;
170         }
171         if ($parsed->userinfo) {
172                 if ($parsed->userinfo =~ /([^:]*):(.*)/) {
173                         $credential{username} = $1;
174                         $credential{password} = $2;
175                 } else {
176                         $credential{username} = $parsed->userinfo;
177                 }
178         }
179
180         return %credential;
181 }
182
183 sub credential_read {
184         my %credential;
185         my $reader = shift;
186         my $op = shift;
187         while (<$reader>) {
188                 my ($key, $value) = /([^=]*)=(.*)/;
189                 if (not defined $key) {
190                         die "ERROR receiving response from git credential $op:\n$_\n";
191                 }
192                 $credential{$key} = $value;
193         }
194         return %credential;
195 }
196
197 sub credential_write {
198         my $credential = shift;
199         my $writer = shift;
200         while (my ($key, $value) = each(%$credential) ) {
201                 if ($value) {
202                         print $writer "$key=$value\n";
203                 }
204         }
205 }
206
207 sub credential_run {
208         my $op = shift;
209         my $credential = shift;
210         my $pid = open2(my $reader, my $writer, "git credential $op");
211         credential_write($credential, $writer);
212         print $writer "\n";
213         close($writer);
214
215         if ($op eq "fill") {
216                 %$credential = credential_read($reader, $op);
217         } else {
218                 if (<$reader>) {
219                         die "ERROR while running git credential $op:\n$_";
220                 }
221         }
222         close($reader);
223         waitpid($pid, 0);
224         my $child_exit_status = $? >> 8;
225         if ($child_exit_status != 0) {
226                 die "'git credential $op' failed with code $child_exit_status.";
227         }
228 }
229
230 # MediaWiki API instance, created lazily.
231 my $mediawiki;
232
233 sub mw_connect_maybe {
234         if ($mediawiki) {
235                 return;
236         }
237         $mediawiki = MediaWiki::API->new;
238         $mediawiki->{config}->{api_url} = "$url/api.php";
239         if ($wiki_login) {
240                 my %credential = credential_from_url($url);
241                 $credential{username} = $wiki_login;
242                 $credential{password} = $wiki_passwd;
243                 credential_run("fill", \%credential);
244                 my $request = {lgname => $credential{username},
245                                lgpassword => $credential{password},
246                                lgdomain => $wiki_domain};
247                 if ($mediawiki->login($request)) {
248                         credential_run("approve", \%credential);
249                         print STDERR "Logged in mediawiki user \"$credential{username}\".\n";
250                 } else {
251                         print STDERR "Failed to log in mediawiki user \"$credential{username}\" on $url\n";
252                         print STDERR "  (error " .
253                                 $mediawiki->{error}->{code} . ': ' .
254                                 $mediawiki->{error}->{details} . ")\n";
255                         credential_run("reject", \%credential);
256                         exit 1;
257                 }
258         }
259 }
260
261 sub get_mw_first_pages {
262         my $some_pages = shift;
263         my @some_pages = @{$some_pages};
264
265         my $pages = shift;
266
267         # pattern 'page1|page2|...' required by the API
268         my $titles = join('|', @some_pages);
269
270         my $mw_pages = $mediawiki->api({
271                 action => 'query',
272                 titles => $titles,
273         });
274         if (!defined($mw_pages)) {
275                 print STDERR "fatal: could not query the list of wiki pages.\n";
276                 print STDERR "fatal: '$url' does not appear to be a mediawiki\n";
277                 print STDERR "fatal: make sure '$url/api.php' is a valid page.\n";
278                 exit 1;
279         }
280         while (my ($id, $page) = each(%{$mw_pages->{query}->{pages}})) {
281                 if ($id < 0) {
282                         print STDERR "Warning: page $page->{title} not found on wiki\n";
283                 } else {
284                         $pages->{$page->{title}} = $page;
285                 }
286         }
287 }
288
289 sub get_mw_pages {
290         mw_connect_maybe();
291
292         my %pages; # hash on page titles to avoid duplicates
293         my $user_defined;
294         if (@tracked_pages) {
295                 $user_defined = 1;
296                 # The user provided a list of pages titles, but we
297                 # still need to query the API to get the page IDs.
298
299                 my @some_pages = @tracked_pages;
300                 while (@some_pages) {
301                         my $last = 50;
302                         if ($#some_pages < $last) {
303                                 $last = $#some_pages;
304                         }
305                         my @slice = @some_pages[0..$last];
306                         get_mw_first_pages(\@slice, \%pages);
307                         @some_pages = @some_pages[51..$#some_pages];
308                 }
309         }
310         if (@tracked_categories) {
311                 $user_defined = 1;
312                 foreach my $category (@tracked_categories) {
313                         if (index($category, ':') < 0) {
314                                 # Mediawiki requires the Category
315                                 # prefix, but let's not force the user
316                                 # to specify it.
317                                 $category = "Category:" . $category;
318                         }
319                         my $mw_pages = $mediawiki->list( {
320                                 action => 'query',
321                                 list => 'categorymembers',
322                                 cmtitle => $category,
323                                 cmlimit => 'max' } )
324                             || die $mediawiki->{error}->{code} . ': ' . $mediawiki->{error}->{details};
325                         foreach my $page (@{$mw_pages}) {
326                                 $pages{$page->{title}} = $page;
327                         }
328                 }
329         }
330         if (!$user_defined) {
331                 # No user-provided list, get the list of pages from
332                 # the API.
333                 my $mw_pages = $mediawiki->list({
334                         action => 'query',
335                         list => 'allpages',
336                         aplimit => 500,
337                 });
338                 if (!defined($mw_pages)) {
339                         print STDERR "fatal: could not get the list of wiki pages.\n";
340                         print STDERR "fatal: '$url' does not appear to be a mediawiki\n";
341                         print STDERR "fatal: make sure '$url/api.php' is a valid page.\n";
342                         exit 1;
343                 }
344                 foreach my $page (@{$mw_pages}) {
345                         $pages{$page->{title}} = $page;
346                 }
347         }
348         return values(%pages);
349 }
350
351 sub run_git {
352         open(my $git, "-|:encoding(UTF-8)", "git " . $_[0]);
353         my $res = do { local $/; <$git> };
354         close($git);
355
356         return $res;
357 }
358
359
360 sub get_last_local_revision {
361         # Get note regarding last mediawiki revision
362         my $note = run_git("notes --ref=$remotename/mediawiki show refs/mediawiki/$remotename/master 2>/dev/null");
363         my @note_info = split(/ /, $note);
364
365         my $lastrevision_number;
366         if (!(defined($note_info[0]) && $note_info[0] eq "mediawiki_revision:")) {
367                 print STDERR "No previous mediawiki revision found";
368                 $lastrevision_number = 0;
369         } else {
370                 # Notes are formatted : mediawiki_revision: #number
371                 $lastrevision_number = $note_info[1];
372                 chomp($lastrevision_number);
373                 print STDERR "Last local mediawiki revision found is $lastrevision_number";
374         }
375         return $lastrevision_number;
376 }
377
378 # Remember the timestamp corresponding to a revision id.
379 my %basetimestamps;
380
381 sub get_last_remote_revision {
382         mw_connect_maybe();
383
384         my @pages = get_mw_pages();
385
386         my $max_rev_num = 0;
387
388         foreach my $page (@pages) {
389                 my $id = $page->{pageid};
390
391                 my $query = {
392                         action => 'query',
393                         prop => 'revisions',
394                         rvprop => 'ids|timestamp',
395                         pageids => $id,
396                 };
397
398                 my $result = $mediawiki->api($query);
399
400                 my $lastrev = pop(@{$result->{query}->{pages}->{$id}->{revisions}});
401
402                 $basetimestamps{$lastrev->{revid}} = $lastrev->{timestamp};
403
404                 $max_rev_num = ($lastrev->{revid} > $max_rev_num ? $lastrev->{revid} : $max_rev_num);
405         }
406
407         print STDERR "Last remote revision found is $max_rev_num.\n";
408         return $max_rev_num;
409 }
410
411 # Clean content before sending it to MediaWiki
412 sub mediawiki_clean {
413         my $string = shift;
414         my $page_created = shift;
415         # Mediawiki does not allow blank space at the end of a page and ends with a single \n.
416         # This function right trims a string and adds a \n at the end to follow this rule
417         $string =~ s/\s+$//;
418         if ($string eq "" && $page_created) {
419                 # Creating empty pages is forbidden.
420                 $string = EMPTY_CONTENT;
421         }
422         return $string."\n";
423 }
424
425 # Filter applied on MediaWiki data before adding them to Git
426 sub mediawiki_smudge {
427         my $string = shift;
428         if ($string eq EMPTY_CONTENT) {
429                 $string = "";
430         }
431         # This \n is important. This is due to mediawiki's way to handle end of files.
432         return $string."\n";
433 }
434
435 sub mediawiki_clean_filename {
436         my $filename = shift;
437         $filename =~ s/@{[SLASH_REPLACEMENT]}/\//g;
438         # [, ], |, {, and } are forbidden by MediaWiki, even URL-encoded.
439         # Do a variant of URL-encoding, i.e. looks like URL-encoding,
440         # but with _ added to prevent MediaWiki from thinking this is
441         # an actual special character.
442         $filename =~ s/[\[\]\{\}\|]/sprintf("_%%_%x", ord($&))/ge;
443         # If we use the uri escape before
444         # we should unescape here, before anything
445
446         return $filename;
447 }
448
449 sub mediawiki_smudge_filename {
450         my $filename = shift;
451         $filename =~ s/\//@{[SLASH_REPLACEMENT]}/g;
452         $filename =~ s/ /_/g;
453         # Decode forbidden characters encoded in mediawiki_clean_filename
454         $filename =~ s/_%_([0-9a-fA-F][0-9a-fA-F])/sprintf("%c", hex($1))/ge;
455         return $filename;
456 }
457
458 sub literal_data {
459         my ($content) = @_;
460         print STDOUT "data ", bytes::length($content), "\n", $content;
461 }
462
463 sub mw_capabilities {
464         # Revisions are imported to the private namespace
465         # refs/mediawiki/$remotename/ by the helper and fetched into
466         # refs/remotes/$remotename later by fetch.
467         print STDOUT "refspec refs/heads/*:refs/mediawiki/$remotename/*\n";
468         print STDOUT "import\n";
469         print STDOUT "list\n";
470         print STDOUT "push\n";
471         print STDOUT "\n";
472 }
473
474 sub mw_list {
475         # MediaWiki do not have branches, we consider one branch arbitrarily
476         # called master, and HEAD pointing to it.
477         print STDOUT "? refs/heads/master\n";
478         print STDOUT "\@refs/heads/master HEAD\n";
479         print STDOUT "\n";
480 }
481
482 sub mw_option {
483         print STDERR "remote-helper command 'option $_[0]' not yet implemented\n";
484         print STDOUT "unsupported\n";
485 }
486
487 sub fetch_mw_revisions_for_page {
488         my $page = shift;
489         my $id = shift;
490         my $fetch_from = shift;
491         my @page_revs = ();
492         my $query = {
493                 action => 'query',
494                 prop => 'revisions',
495                 rvprop => 'ids',
496                 rvdir => 'newer',
497                 rvstartid => $fetch_from,
498                 rvlimit => 500,
499                 pageids => $id,
500         };
501
502         my $revnum = 0;
503         # Get 500 revisions at a time due to the mediawiki api limit
504         while (1) {
505                 my $result = $mediawiki->api($query);
506
507                 # Parse each of those 500 revisions
508                 foreach my $revision (@{$result->{query}->{pages}->{$id}->{revisions}}) {
509                         my $page_rev_ids;
510                         $page_rev_ids->{pageid} = $page->{pageid};
511                         $page_rev_ids->{revid} = $revision->{revid};
512                         push(@page_revs, $page_rev_ids);
513                         $revnum++;
514                 }
515                 last unless $result->{'query-continue'};
516                 $query->{rvstartid} = $result->{'query-continue'}->{revisions}->{rvstartid};
517         }
518         if ($shallow_import && @page_revs) {
519                 print STDERR "  Found 1 revision (shallow import).\n";
520                 @page_revs = sort {$b->{revid} <=> $a->{revid}} (@page_revs);
521                 return $page_revs[0];
522         }
523         print STDERR "  Found ", $revnum, " revision(s).\n";
524         return @page_revs;
525 }
526
527 sub fetch_mw_revisions {
528         my $pages = shift; my @pages = @{$pages};
529         my $fetch_from = shift;
530
531         my @revisions = ();
532         my $n = 1;
533         foreach my $page (@pages) {
534                 my $id = $page->{pageid};
535
536                 print STDERR "page $n/", scalar(@pages), ": ". $page->{title} ."\n";
537                 $n++;
538                 my @page_revs = fetch_mw_revisions_for_page($page, $id, $fetch_from);
539                 @revisions = (@page_revs, @revisions);
540         }
541
542         return ($n, @revisions);
543 }
544
545 sub import_file_revision {
546         my $commit = shift;
547         my %commit = %{$commit};
548         my $full_import = shift;
549         my $n = shift;
550
551         my $title = $commit{title};
552         my $comment = $commit{comment};
553         my $content = $commit{content};
554         my $author = $commit{author};
555         my $date = $commit{date};
556
557         print STDOUT "commit refs/mediawiki/$remotename/master\n";
558         print STDOUT "mark :$n\n";
559         print STDOUT "committer $author <$author\@$wiki_name> ", $date->epoch, " +0000\n";
560         literal_data($comment);
561
562         # If it's not a clone, we need to know where to start from
563         if (!$full_import && $n == 1) {
564                 print STDOUT "from refs/mediawiki/$remotename/master^0\n";
565         }
566         if ($content ne DELETED_CONTENT) {
567                 print STDOUT "M 644 inline $title.mw\n";
568                 literal_data($content);
569                 print STDOUT "\n\n";
570         } else {
571                 print STDOUT "D $title.mw\n";
572         }
573
574         # mediawiki revision number in the git note
575         if ($full_import && $n == 1) {
576                 print STDOUT "reset refs/notes/$remotename/mediawiki\n";
577         }
578         print STDOUT "commit refs/notes/$remotename/mediawiki\n";
579         print STDOUT "committer $author <$author\@$wiki_name> ", $date->epoch, " +0000\n";
580         literal_data("Note added by git-mediawiki during import");
581         if (!$full_import && $n == 1) {
582                 print STDOUT "from refs/notes/$remotename/mediawiki^0\n";
583         }
584         print STDOUT "N inline :$n\n";
585         literal_data("mediawiki_revision: " . $commit{mw_revision});
586         print STDOUT "\n\n";
587 }
588
589 # parse a sequence of
590 # <cmd> <arg1>
591 # <cmd> <arg2>
592 # \n
593 # (like batch sequence of import and sequence of push statements)
594 sub get_more_refs {
595         my $cmd = shift;
596         my @refs;
597         while (1) {
598                 my $line = <STDIN>;
599                 if ($line =~ m/^$cmd (.*)$/) {
600                         push(@refs, $1);
601                 } elsif ($line eq "\n") {
602                         return @refs;
603                 } else {
604                         die("Invalid command in a '$cmd' batch: ". $_);
605                 }
606         }
607 }
608
609 sub mw_import {
610         # multiple import commands can follow each other.
611         my @refs = (shift, get_more_refs("import"));
612         foreach my $ref (@refs) {
613                 mw_import_ref($ref);
614         }
615         print STDOUT "done\n";
616 }
617
618 sub mw_import_ref {
619         my $ref = shift;
620         # The remote helper will call "import HEAD" and
621         # "import refs/heads/master".
622         # Since HEAD is a symbolic ref to master (by convention,
623         # followed by the output of the command "list" that we gave),
624         # we don't need to do anything in this case.
625         if ($ref eq "HEAD") {
626                 return;
627         }
628
629         mw_connect_maybe();
630
631         my @pages = get_mw_pages();
632
633         print STDERR "Searching revisions...\n";
634         my $last_local = get_last_local_revision();
635         my $fetch_from = $last_local + 1;
636         if ($fetch_from == 1) {
637                 print STDERR ", fetching from beginning.\n";
638         } else {
639                 print STDERR ", fetching from here.\n";
640         }
641         my ($n, @revisions) = fetch_mw_revisions(\@pages, $fetch_from);
642
643         # Creation of the fast-import stream
644         print STDERR "Fetching & writing export data...\n";
645
646         $n = 0;
647         my $last_timestamp = 0; # Placeholer in case $rev->timestamp is undefined
648
649         foreach my $pagerevid (sort {$a->{revid} <=> $b->{revid}} @revisions) {
650                 # fetch the content of the pages
651                 my $query = {
652                         action => 'query',
653                         prop => 'revisions',
654                         rvprop => 'content|timestamp|comment|user|ids',
655                         revids => $pagerevid->{revid},
656                 };
657
658                 my $result = $mediawiki->api($query);
659
660                 my $rev = pop(@{$result->{query}->{pages}->{$pagerevid->{pageid}}->{revisions}});
661
662                 $n++;
663
664                 my %commit;
665                 $commit{author} = $rev->{user} || 'Anonymous';
666                 $commit{comment} = $rev->{comment} || '*Empty MediaWiki Message*';
667                 $commit{title} = mediawiki_smudge_filename(
668                         $result->{query}->{pages}->{$pagerevid->{pageid}}->{title}
669                     );
670                 $commit{mw_revision} = $pagerevid->{revid};
671                 $commit{content} = mediawiki_smudge($rev->{'*'});
672
673                 if (!defined($rev->{timestamp})) {
674                         $last_timestamp++;
675                 } else {
676                         $last_timestamp = $rev->{timestamp};
677                 }
678                 $commit{date} = DateTime::Format::ISO8601->parse_datetime($last_timestamp);
679
680                 print STDERR "$n/", scalar(@revisions), ": Revision #$pagerevid->{revid} of $commit{title}\n";
681
682                 import_file_revision(\%commit, ($fetch_from == 1), $n);
683         }
684
685         if ($fetch_from == 1 && $n == 0) {
686                 print STDERR "You appear to have cloned an empty MediaWiki.\n";
687                 # Something has to be done remote-helper side. If nothing is done, an error is
688                 # thrown saying that HEAD is refering to unknown object 0000000000000000000
689                 # and the clone fails.
690         }
691 }
692
693 sub error_non_fast_forward {
694         my $advice = run_git("config --bool advice.pushNonFastForward");
695         chomp($advice);
696         if ($advice ne "false") {
697                 # Native git-push would show this after the summary.
698                 # We can't ask it to display it cleanly, so print it
699                 # ourselves before.
700                 print STDERR "To prevent you from losing history, non-fast-forward updates were rejected\n";
701                 print STDERR "Merge the remote changes (e.g. 'git pull') before pushing again. See the\n";
702                 print STDERR "'Note about fast-forwards' section of 'git push --help' for details.\n";
703         }
704         print STDOUT "error $_[0] \"non-fast-forward\"\n";
705         return 0;
706 }
707
708 sub mw_push_file {
709         my $diff_info = shift;
710         # $diff_info contains a string in this format:
711         # 100644 100644 <sha1_of_blob_before_commit> <sha1_of_blob_now> <status>
712         my @diff_info_split = split(/[ \t]/, $diff_info);
713
714         # Filename, including .mw extension
715         my $complete_file_name = shift;
716         # Commit message
717         my $summary = shift;
718         # MediaWiki revision number. Keep the previous one by default,
719         # in case there's no edit to perform.
720         my $newrevid = shift;
721
722         my $new_sha1 = $diff_info_split[3];
723         my $old_sha1 = $diff_info_split[2];
724         my $page_created = ($old_sha1 eq NULL_SHA1);
725         my $page_deleted = ($new_sha1 eq NULL_SHA1);
726         $complete_file_name = mediawiki_clean_filename($complete_file_name);
727
728         if (substr($complete_file_name,-3) eq ".mw") {
729                 my $title = substr($complete_file_name,0,-3);
730
731                 my $file_content;
732                 if ($page_deleted) {
733                         # Deleting a page usually requires
734                         # special priviledges. A common
735                         # convention is to replace the page
736                         # with this content instead:
737                         $file_content = DELETED_CONTENT;
738                 } else {
739                         $file_content = run_git("cat-file blob $new_sha1");
740                 }
741
742                 mw_connect_maybe();
743
744                 my $result = $mediawiki->edit( {
745                         action => 'edit',
746                         summary => $summary,
747                         title => $title,
748                         basetimestamp => $basetimestamps{$newrevid},
749                         text => mediawiki_clean($file_content, $page_created),
750                                   }, {
751                                           skip_encoding => 1 # Helps with names with accentuated characters
752                                   });
753                 if (!$result) {
754                         if ($mediawiki->{error}->{code} == 3) {
755                                 # edit conflicts, considered as non-fast-forward
756                                 print STDERR 'Warning: Error ' .
757                                     $mediawiki->{error}->{code} .
758                                     ' from mediwiki: ' . $mediawiki->{error}->{details} .
759                                     ".\n";
760                                 return ($newrevid, "non-fast-forward");
761                         } else {
762                                 # Other errors. Shouldn't happen => just die()
763                                 die 'Fatal: Error ' .
764                                     $mediawiki->{error}->{code} .
765                                     ' from mediwiki: ' . $mediawiki->{error}->{details};
766                         }
767                 }
768                 $newrevid = $result->{edit}->{newrevid};
769                 print STDERR "Pushed file: $new_sha1 - $title\n";
770         } else {
771                 print STDERR "$complete_file_name not a mediawiki file (Not pushable on this version of git-remote-mediawiki).\n"
772         }
773         return ($newrevid, "ok");
774 }
775
776 sub mw_push {
777         # multiple push statements can follow each other
778         my @refsspecs = (shift, get_more_refs("push"));
779         my $pushed;
780         for my $refspec (@refsspecs) {
781                 my ($force, $local, $remote) = $refspec =~ /^(\+)?([^:]*):([^:]*)$/
782                     or die("Invalid refspec for push. Expected <src>:<dst> or +<src>:<dst>");
783                 if ($force) {
784                         print STDERR "Warning: forced push not allowed on a MediaWiki.\n";
785                 }
786                 if ($local eq "") {
787                         print STDERR "Cannot delete remote branch on a MediaWiki\n";
788                         print STDOUT "error $remote cannot delete\n";
789                         next;
790                 }
791                 if ($remote ne "refs/heads/master") {
792                         print STDERR "Only push to the branch 'master' is supported on a MediaWiki\n";
793                         print STDOUT "error $remote only master allowed\n";
794                         next;
795                 }
796                 if (mw_push_revision($local, $remote)) {
797                         $pushed = 1;
798                 }
799         }
800
801         # Notify Git that the push is done
802         print STDOUT "\n";
803
804         if ($pushed && $dumb_push) {
805                 print STDERR "Just pushed some revisions to MediaWiki.\n";
806                 print STDERR "The pushed revisions now have to be re-imported, and your current branch\n";
807                 print STDERR "needs to be updated with these re-imported commits. You can do this with\n";
808                 print STDERR "\n";
809                 print STDERR "  git pull --rebase\n";
810                 print STDERR "\n";
811         }
812 }
813
814 sub mw_push_revision {
815         my $local = shift;
816         my $remote = shift; # actually, this has to be "refs/heads/master" at this point.
817         my $last_local_revid = get_last_local_revision();
818         print STDERR ".\n"; # Finish sentence started by get_last_local_revision()
819         my $last_remote_revid = get_last_remote_revision();
820         my $mw_revision = $last_remote_revid;
821
822         # Get sha1 of commit pointed by local HEAD
823         my $HEAD_sha1 = run_git("rev-parse $local 2>/dev/null"); chomp($HEAD_sha1);
824         # Get sha1 of commit pointed by remotes/$remotename/master
825         my $remoteorigin_sha1 = run_git("rev-parse refs/remotes/$remotename/master 2>/dev/null");
826         chomp($remoteorigin_sha1);
827
828         if ($last_local_revid > 0 &&
829             $last_local_revid < $last_remote_revid) {
830                 return error_non_fast_forward($remote);
831         }
832
833         if ($HEAD_sha1 eq $remoteorigin_sha1) {
834                 # nothing to push
835                 return 0;
836         }
837
838         # Get every commit in between HEAD and refs/remotes/origin/master,
839         # including HEAD and refs/remotes/origin/master
840         my @commit_pairs = ();
841         if ($last_local_revid > 0) {
842                 my $parsed_sha1 = $remoteorigin_sha1;
843                 # Find a path from last MediaWiki commit to pushed commit
844                 while ($parsed_sha1 ne $HEAD_sha1) {
845                         my @commit_info =  grep(/^$parsed_sha1/, split(/\n/, run_git("rev-list --children $local")));
846                         if (!@commit_info) {
847                                 return error_non_fast_forward($remote);
848                         }
849                         my @commit_info_split = split(/ |\n/, $commit_info[0]);
850                         # $commit_info_split[1] is the sha1 of the commit to export
851                         # $commit_info_split[0] is the sha1 of its direct child
852                         push(@commit_pairs, \@commit_info_split);
853                         $parsed_sha1 = $commit_info_split[1];
854                 }
855         } else {
856                 # No remote mediawiki revision. Export the whole
857                 # history (linearized with --first-parent)
858                 print STDERR "Warning: no common ancestor, pushing complete history\n";
859                 my $history = run_git("rev-list --first-parent --children $local");
860                 my @history = split('\n', $history);
861                 @history = @history[1..$#history];
862                 foreach my $line (reverse @history) {
863                         my @commit_info_split = split(/ |\n/, $line);
864                         push(@commit_pairs, \@commit_info_split);
865                 }
866         }
867
868         foreach my $commit_info_split (@commit_pairs) {
869                 my $sha1_child = @{$commit_info_split}[0];
870                 my $sha1_commit = @{$commit_info_split}[1];
871                 my $diff_infos = run_git("diff-tree -r --raw -z $sha1_child $sha1_commit");
872                 # TODO: we could detect rename, and encode them with a #redirect on the wiki.
873                 # TODO: for now, it's just a delete+add
874                 my @diff_info_list = split(/\0/, $diff_infos);
875                 # Keep the subject line of the commit message as mediawiki comment for the revision
876                 my $commit_msg = run_git("log --no-walk --format=\"%s\" $sha1_commit");
877                 chomp($commit_msg);
878                 # Push every blob
879                 while (@diff_info_list) {
880                         my $status;
881                         # git diff-tree -z gives an output like
882                         # <metadata>\0<filename1>\0
883                         # <metadata>\0<filename2>\0
884                         # and we've split on \0.
885                         my $info = shift(@diff_info_list);
886                         my $file = shift(@diff_info_list);
887                         ($mw_revision, $status) = mw_push_file($info, $file, $commit_msg, $mw_revision);
888                         if ($status eq "non-fast-forward") {
889                                 # we may already have sent part of the
890                                 # commit to MediaWiki, but it's too
891                                 # late to cancel it. Stop the push in
892                                 # the middle, but still give an
893                                 # accurate error message.
894                                 return error_non_fast_forward($remote);
895                         }
896                         if ($status ne "ok") {
897                                 die("Unknown error from mw_push_file()");
898                         }
899                 }
900                 unless ($dumb_push) {
901                         run_git("notes --ref=$remotename/mediawiki add -m \"mediawiki_revision: $mw_revision\" $sha1_commit");
902                         run_git("update-ref -m \"Git-MediaWiki push\" refs/mediawiki/$remotename/master $sha1_commit $sha1_child");
903                 }
904         }
905
906         print STDOUT "ok $remote\n";
907         return 1;
908 }