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