git-remote-mediawiki: allow a domain to be set for authentication
[git.git] / contrib / mw-to-git / git-remote-mediawiki
blob0b32d18eaa963492bfb7fb1bb4437763db7b70c3
1 #! /usr/bin/perl
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
11 # Gateway between Git and MediaWiki.
12 # https://github.com/Bibzball/Git-Mediawiki/wiki
14 # Known limitations:
16 # - Only wiki pages are managed, no support for [[File:...]]
17 # attachments.
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.
26 # - Git renames could be turned into MediaWiki renames (see TODO
27 # below)
29 # - login/password support requires the user to write the password
30 # cleartext in a file (see TODO below).
32 # - No way to import "one page, and all pages included in it"
34 # - Multiple remote MediaWikis have not been very well tested.
36 use strict;
37 use MediaWiki::API;
38 use DateTime::Format::ISO8601;
39 use encoding 'utf8';
41 # use encoding 'utf8' doesn't change STDERROR
42 # but we're going to output UTF-8 filenames to STDERR
43 binmode STDERR, ":utf8";
45 use URI::Escape;
46 use warnings;
48 # Mediawiki filenames can contain forward slashes. This variable decides by which pattern they should be replaced
49 use constant SLASH_REPLACEMENT => "%2F";
51 # It's not always possible to delete pages (may require some
52 # priviledges). Deleted pages are replaced with this content.
53 use constant DELETED_CONTENT => "[[Category:Deleted]]\n";
55 # It's not possible to create empty pages. New empty files in Git are
56 # sent with this content instead.
57 use constant EMPTY_CONTENT => "<!-- empty page -->\n";
59 # used to reflect file creation or deletion in diff.
60 use constant NULL_SHA1 => "0000000000000000000000000000000000000000";
62 my $remotename = $ARGV[0];
63 my $url = $ARGV[1];
65 # Accept both space-separated and multiple keys in config file.
66 # Spaces should be written as _ anyway because we'll use chomp.
67 my @tracked_pages = split(/[ \n]/, run_git("config --get-all remote.". $remotename .".pages"));
68 chomp(@tracked_pages);
70 # Just like @tracked_pages, but for MediaWiki categories.
71 my @tracked_categories = split(/[ \n]/, run_git("config --get-all remote.". $remotename .".categories"));
72 chomp(@tracked_categories);
74 my $wiki_login = run_git("config --get remote.". $remotename .".mwLogin");
75 # TODO: ideally, this should be able to read from keyboard, but we're
76 # inside a remote helper, so our stdin is connect to git, not to a
77 # terminal.
78 my $wiki_passwd = run_git("config --get remote.". $remotename .".mwPassword");
79 my $wiki_domain = run_git("config --get remote.". $remotename .".mwDomain");
80 chomp($wiki_login);
81 chomp($wiki_passwd);
82 chomp($wiki_domain);
84 # Import only last revisions (both for clone and fetch)
85 my $shallow_import = run_git("config --get --bool remote.". $remotename .".shallow");
86 chomp($shallow_import);
87 $shallow_import = ($shallow_import eq "true");
89 # Dumb push: don't update notes and mediawiki ref to reflect the last push.
91 # Configurable with mediawiki.dumbPush, or per-remote with
92 # remote.<remotename>.dumbPush.
94 # This means the user will have to re-import the just-pushed
95 # revisions. On the other hand, this means that the Git revisions
96 # corresponding to MediaWiki revisions are all imported from the wiki,
97 # regardless of whether they were initially created in Git or from the
98 # web interface, hence all users will get the same history (i.e. if
99 # the push from Git to MediaWiki loses some information, everybody
100 # will get the history with information lost). If the import is
101 # deterministic, this means everybody gets the same sha1 for each
102 # MediaWiki revision.
103 my $dumb_push = run_git("config --get --bool remote.$remotename.dumbPush");
104 unless ($dumb_push) {
105 $dumb_push = run_git("config --get --bool mediawiki.dumbPush");
107 chomp($dumb_push);
108 $dumb_push = ($dumb_push eq "true");
110 my $wiki_name = $url;
111 $wiki_name =~ s/[^\/]*:\/\///;
113 # Commands parser
114 my $entry;
115 my @cmd;
116 while (<STDIN>) {
117 chomp;
118 @cmd = split(/ /);
119 if (defined($cmd[0])) {
120 # Line not blank
121 if ($cmd[0] eq "capabilities") {
122 die("Too many arguments for capabilities") unless (!defined($cmd[1]));
123 mw_capabilities();
124 } elsif ($cmd[0] eq "list") {
125 die("Too many arguments for list") unless (!defined($cmd[2]));
126 mw_list($cmd[1]);
127 } elsif ($cmd[0] eq "import") {
128 die("Invalid arguments for import") unless ($cmd[1] ne "" && !defined($cmd[2]));
129 mw_import($cmd[1]);
130 } elsif ($cmd[0] eq "option") {
131 die("Too many arguments for option") unless ($cmd[1] ne "" && $cmd[2] ne "" && !defined($cmd[3]));
132 mw_option($cmd[1],$cmd[2]);
133 } elsif ($cmd[0] eq "push") {
134 mw_push($cmd[1]);
135 } else {
136 print STDERR "Unknown command. Aborting...\n";
137 last;
139 } else {
140 # blank line: we should terminate
141 last;
144 BEGIN { $| = 1 } # flush STDOUT, to make sure the previous
145 # command is fully processed.
148 ########################## Functions ##############################
150 # MediaWiki API instance, created lazily.
151 my $mediawiki;
153 sub mw_connect_maybe {
154 if ($mediawiki) {
155 return;
157 $mediawiki = MediaWiki::API->new;
158 $mediawiki->{config}->{api_url} = "$url/api.php";
159 if ($wiki_login) {
160 if (!$mediawiki->login({
161 lgname => $wiki_login,
162 lgpassword => $wiki_passwd,
163 lgdomain => $wiki_domain,
164 })) {
165 print STDERR "Failed to log in mediawiki user \"$wiki_login\" on $url\n";
166 print STDERR "(error " .
167 $mediawiki->{error}->{code} . ': ' .
168 $mediawiki->{error}->{details} . ")\n";
169 exit 1;
170 } else {
171 print STDERR "Logged in with user \"$wiki_login\".\n";
176 sub get_mw_first_pages {
177 my $some_pages = shift;
178 my @some_pages = @{$some_pages};
180 my $pages = shift;
182 # pattern 'page1|page2|...' required by the API
183 my $titles = join('|', @some_pages);
185 my $mw_pages = $mediawiki->api({
186 action => 'query',
187 titles => $titles,
189 if (!defined($mw_pages)) {
190 print STDERR "fatal: could not query the list of wiki pages.\n";
191 print STDERR "fatal: '$url' does not appear to be a mediawiki\n";
192 print STDERR "fatal: make sure '$url/api.php' is a valid page.\n";
193 exit 1;
195 while (my ($id, $page) = each(%{$mw_pages->{query}->{pages}})) {
196 if ($id < 0) {
197 print STDERR "Warning: page $page->{title} not found on wiki\n";
198 } else {
199 $pages->{$page->{title}} = $page;
204 sub get_mw_pages {
205 mw_connect_maybe();
207 my %pages; # hash on page titles to avoid duplicates
208 my $user_defined;
209 if (@tracked_pages) {
210 $user_defined = 1;
211 # The user provided a list of pages titles, but we
212 # still need to query the API to get the page IDs.
214 my @some_pages = @tracked_pages;
215 while (@some_pages) {
216 my $last = 50;
217 if ($#some_pages < $last) {
218 $last = $#some_pages;
220 my @slice = @some_pages[0..$last];
221 get_mw_first_pages(\@slice, \%pages);
222 @some_pages = @some_pages[51..$#some_pages];
225 if (@tracked_categories) {
226 $user_defined = 1;
227 foreach my $category (@tracked_categories) {
228 if (index($category, ':') < 0) {
229 # Mediawiki requires the Category
230 # prefix, but let's not force the user
231 # to specify it.
232 $category = "Category:" . $category;
234 my $mw_pages = $mediawiki->list( {
235 action => 'query',
236 list => 'categorymembers',
237 cmtitle => $category,
238 cmlimit => 'max' } )
239 || die $mediawiki->{error}->{code} . ': ' . $mediawiki->{error}->{details};
240 foreach my $page (@{$mw_pages}) {
241 $pages{$page->{title}} = $page;
245 if (!$user_defined) {
246 # No user-provided list, get the list of pages from
247 # the API.
248 my $mw_pages = $mediawiki->list({
249 action => 'query',
250 list => 'allpages',
251 aplimit => 500,
253 if (!defined($mw_pages)) {
254 print STDERR "fatal: could not get the list of wiki pages.\n";
255 print STDERR "fatal: '$url' does not appear to be a mediawiki\n";
256 print STDERR "fatal: make sure '$url/api.php' is a valid page.\n";
257 exit 1;
259 foreach my $page (@{$mw_pages}) {
260 $pages{$page->{title}} = $page;
263 return values(%pages);
266 sub run_git {
267 open(my $git, "-|:encoding(UTF-8)", "git " . $_[0]);
268 my $res = do { local $/; <$git> };
269 close($git);
271 return $res;
275 sub get_last_local_revision {
276 # Get note regarding last mediawiki revision
277 my $note = run_git("notes --ref=$remotename/mediawiki show refs/mediawiki/$remotename/master 2>/dev/null");
278 my @note_info = split(/ /, $note);
280 my $lastrevision_number;
281 if (!(defined($note_info[0]) && $note_info[0] eq "mediawiki_revision:")) {
282 print STDERR "No previous mediawiki revision found";
283 $lastrevision_number = 0;
284 } else {
285 # Notes are formatted : mediawiki_revision: #number
286 $lastrevision_number = $note_info[1];
287 chomp($lastrevision_number);
288 print STDERR "Last local mediawiki revision found is $lastrevision_number";
290 return $lastrevision_number;
293 # Remember the timestamp corresponding to a revision id.
294 my %basetimestamps;
296 sub get_last_remote_revision {
297 mw_connect_maybe();
299 my @pages = get_mw_pages();
301 my $max_rev_num = 0;
303 foreach my $page (@pages) {
304 my $id = $page->{pageid};
306 my $query = {
307 action => 'query',
308 prop => 'revisions',
309 rvprop => 'ids|timestamp',
310 pageids => $id,
313 my $result = $mediawiki->api($query);
315 my $lastrev = pop(@{$result->{query}->{pages}->{$id}->{revisions}});
317 $basetimestamps{$lastrev->{revid}} = $lastrev->{timestamp};
319 $max_rev_num = ($lastrev->{revid} > $max_rev_num ? $lastrev->{revid} : $max_rev_num);
322 print STDERR "Last remote revision found is $max_rev_num.\n";
323 return $max_rev_num;
326 # Clean content before sending it to MediaWiki
327 sub mediawiki_clean {
328 my $string = shift;
329 my $page_created = shift;
330 # Mediawiki does not allow blank space at the end of a page and ends with a single \n.
331 # This function right trims a string and adds a \n at the end to follow this rule
332 $string =~ s/\s+$//;
333 if ($string eq "" && $page_created) {
334 # Creating empty pages is forbidden.
335 $string = EMPTY_CONTENT;
337 return $string."\n";
340 # Filter applied on MediaWiki data before adding them to Git
341 sub mediawiki_smudge {
342 my $string = shift;
343 if ($string eq EMPTY_CONTENT) {
344 $string = "";
346 # This \n is important. This is due to mediawiki's way to handle end of files.
347 return $string."\n";
350 sub mediawiki_clean_filename {
351 my $filename = shift;
352 $filename =~ s/@{[SLASH_REPLACEMENT]}/\//g;
353 # [, ], |, {, and } are forbidden by MediaWiki, even URL-encoded.
354 # Do a variant of URL-encoding, i.e. looks like URL-encoding,
355 # but with _ added to prevent MediaWiki from thinking this is
356 # an actual special character.
357 $filename =~ s/[\[\]\{\}\|]/sprintf("_%%_%x", ord($&))/ge;
358 # If we use the uri escape before
359 # we should unescape here, before anything
361 return $filename;
364 sub mediawiki_smudge_filename {
365 my $filename = shift;
366 $filename =~ s/\//@{[SLASH_REPLACEMENT]}/g;
367 $filename =~ s/ /_/g;
368 # Decode forbidden characters encoded in mediawiki_clean_filename
369 $filename =~ s/_%_([0-9a-fA-F][0-9a-fA-F])/sprintf("%c", hex($1))/ge;
370 return $filename;
373 sub literal_data {
374 my ($content) = @_;
375 print STDOUT "data ", bytes::length($content), "\n", $content;
378 sub mw_capabilities {
379 # Revisions are imported to the private namespace
380 # refs/mediawiki/$remotename/ by the helper and fetched into
381 # refs/remotes/$remotename later by fetch.
382 print STDOUT "refspec refs/heads/*:refs/mediawiki/$remotename/*\n";
383 print STDOUT "import\n";
384 print STDOUT "list\n";
385 print STDOUT "push\n";
386 print STDOUT "\n";
389 sub mw_list {
390 # MediaWiki do not have branches, we consider one branch arbitrarily
391 # called master, and HEAD pointing to it.
392 print STDOUT "? refs/heads/master\n";
393 print STDOUT "\@refs/heads/master HEAD\n";
394 print STDOUT "\n";
397 sub mw_option {
398 print STDERR "remote-helper command 'option $_[0]' not yet implemented\n";
399 print STDOUT "unsupported\n";
402 sub fetch_mw_revisions_for_page {
403 my $page = shift;
404 my $id = shift;
405 my $fetch_from = shift;
406 my @page_revs = ();
407 my $query = {
408 action => 'query',
409 prop => 'revisions',
410 rvprop => 'ids',
411 rvdir => 'newer',
412 rvstartid => $fetch_from,
413 rvlimit => 500,
414 pageids => $id,
417 my $revnum = 0;
418 # Get 500 revisions at a time due to the mediawiki api limit
419 while (1) {
420 my $result = $mediawiki->api($query);
422 # Parse each of those 500 revisions
423 foreach my $revision (@{$result->{query}->{pages}->{$id}->{revisions}}) {
424 my $page_rev_ids;
425 $page_rev_ids->{pageid} = $page->{pageid};
426 $page_rev_ids->{revid} = $revision->{revid};
427 push(@page_revs, $page_rev_ids);
428 $revnum++;
430 last unless $result->{'query-continue'};
431 $query->{rvstartid} = $result->{'query-continue'}->{revisions}->{rvstartid};
433 if ($shallow_import && @page_revs) {
434 print STDERR " Found 1 revision (shallow import).\n";
435 @page_revs = sort {$b->{revid} <=> $a->{revid}} (@page_revs);
436 return $page_revs[0];
438 print STDERR " Found ", $revnum, " revision(s).\n";
439 return @page_revs;
442 sub fetch_mw_revisions {
443 my $pages = shift; my @pages = @{$pages};
444 my $fetch_from = shift;
446 my @revisions = ();
447 my $n = 1;
448 foreach my $page (@pages) {
449 my $id = $page->{pageid};
451 print STDERR "page $n/", scalar(@pages), ": ". $page->{title} ."\n";
452 $n++;
453 my @page_revs = fetch_mw_revisions_for_page($page, $id, $fetch_from);
454 @revisions = (@page_revs, @revisions);
457 return ($n, @revisions);
460 sub import_file_revision {
461 my $commit = shift;
462 my %commit = %{$commit};
463 my $full_import = shift;
464 my $n = shift;
466 my $title = $commit{title};
467 my $comment = $commit{comment};
468 my $content = $commit{content};
469 my $author = $commit{author};
470 my $date = $commit{date};
472 print STDOUT "commit refs/mediawiki/$remotename/master\n";
473 print STDOUT "mark :$n\n";
474 print STDOUT "committer $author <$author\@$wiki_name> ", $date->epoch, " +0000\n";
475 literal_data($comment);
477 # If it's not a clone, we need to know where to start from
478 if (!$full_import && $n == 1) {
479 print STDOUT "from refs/mediawiki/$remotename/master^0\n";
481 if ($content ne DELETED_CONTENT) {
482 print STDOUT "M 644 inline $title.mw\n";
483 literal_data($content);
484 print STDOUT "\n\n";
485 } else {
486 print STDOUT "D $title.mw\n";
489 # mediawiki revision number in the git note
490 if ($full_import && $n == 1) {
491 print STDOUT "reset refs/notes/$remotename/mediawiki\n";
493 print STDOUT "commit refs/notes/$remotename/mediawiki\n";
494 print STDOUT "committer $author <$author\@$wiki_name> ", $date->epoch, " +0000\n";
495 literal_data("Note added by git-mediawiki during import");
496 if (!$full_import && $n == 1) {
497 print STDOUT "from refs/notes/$remotename/mediawiki^0\n";
499 print STDOUT "N inline :$n\n";
500 literal_data("mediawiki_revision: " . $commit{mw_revision});
501 print STDOUT "\n\n";
504 # parse a sequence of
505 # <cmd> <arg1>
506 # <cmd> <arg2>
507 # \n
508 # (like batch sequence of import and sequence of push statements)
509 sub get_more_refs {
510 my $cmd = shift;
511 my @refs;
512 while (1) {
513 my $line = <STDIN>;
514 if ($line =~ m/^$cmd (.*)$/) {
515 push(@refs, $1);
516 } elsif ($line eq "\n") {
517 return @refs;
518 } else {
519 die("Invalid command in a '$cmd' batch: ". $_);
524 sub mw_import {
525 # multiple import commands can follow each other.
526 my @refs = (shift, get_more_refs("import"));
527 foreach my $ref (@refs) {
528 mw_import_ref($ref);
530 print STDOUT "done\n";
533 sub mw_import_ref {
534 my $ref = shift;
535 # The remote helper will call "import HEAD" and
536 # "import refs/heads/master".
537 # Since HEAD is a symbolic ref to master (by convention,
538 # followed by the output of the command "list" that we gave),
539 # we don't need to do anything in this case.
540 if ($ref eq "HEAD") {
541 return;
544 mw_connect_maybe();
546 my @pages = get_mw_pages();
548 print STDERR "Searching revisions...\n";
549 my $last_local = get_last_local_revision();
550 my $fetch_from = $last_local + 1;
551 if ($fetch_from == 1) {
552 print STDERR ", fetching from beginning.\n";
553 } else {
554 print STDERR ", fetching from here.\n";
556 my ($n, @revisions) = fetch_mw_revisions(\@pages, $fetch_from);
558 # Creation of the fast-import stream
559 print STDERR "Fetching & writing export data...\n";
561 $n = 0;
562 my $last_timestamp = 0; # Placeholer in case $rev->timestamp is undefined
564 foreach my $pagerevid (sort {$a->{revid} <=> $b->{revid}} @revisions) {
565 # fetch the content of the pages
566 my $query = {
567 action => 'query',
568 prop => 'revisions',
569 rvprop => 'content|timestamp|comment|user|ids',
570 revids => $pagerevid->{revid},
573 my $result = $mediawiki->api($query);
575 my $rev = pop(@{$result->{query}->{pages}->{$pagerevid->{pageid}}->{revisions}});
577 $n++;
579 my %commit;
580 $commit{author} = $rev->{user} || 'Anonymous';
581 $commit{comment} = $rev->{comment} || '*Empty MediaWiki Message*';
582 $commit{title} = mediawiki_smudge_filename(
583 $result->{query}->{pages}->{$pagerevid->{pageid}}->{title}
585 $commit{mw_revision} = $pagerevid->{revid};
586 $commit{content} = mediawiki_smudge($rev->{'*'});
588 if (!defined($rev->{timestamp})) {
589 $last_timestamp++;
590 } else {
591 $last_timestamp = $rev->{timestamp};
593 $commit{date} = DateTime::Format::ISO8601->parse_datetime($last_timestamp);
595 print STDERR "$n/", scalar(@revisions), ": Revision #$pagerevid->{revid} of $commit{title}\n";
597 import_file_revision(\%commit, ($fetch_from == 1), $n);
600 if ($fetch_from == 1 && $n == 0) {
601 print STDERR "You appear to have cloned an empty MediaWiki.\n";
602 # Something has to be done remote-helper side. If nothing is done, an error is
603 # thrown saying that HEAD is refering to unknown object 0000000000000000000
604 # and the clone fails.
608 sub error_non_fast_forward {
609 my $advice = run_git("config --bool advice.pushNonFastForward");
610 chomp($advice);
611 if ($advice ne "false") {
612 # Native git-push would show this after the summary.
613 # We can't ask it to display it cleanly, so print it
614 # ourselves before.
615 print STDERR "To prevent you from losing history, non-fast-forward updates were rejected\n";
616 print STDERR "Merge the remote changes (e.g. 'git pull') before pushing again. See the\n";
617 print STDERR "'Note about fast-forwards' section of 'git push --help' for details.\n";
619 print STDOUT "error $_[0] \"non-fast-forward\"\n";
620 return 0;
623 sub mw_push_file {
624 my $diff_info = shift;
625 # $diff_info contains a string in this format:
626 # 100644 100644 <sha1_of_blob_before_commit> <sha1_of_blob_now> <status>
627 my @diff_info_split = split(/[ \t]/, $diff_info);
629 # Filename, including .mw extension
630 my $complete_file_name = shift;
631 # Commit message
632 my $summary = shift;
633 # MediaWiki revision number. Keep the previous one by default,
634 # in case there's no edit to perform.
635 my $newrevid = shift;
637 my $new_sha1 = $diff_info_split[3];
638 my $old_sha1 = $diff_info_split[2];
639 my $page_created = ($old_sha1 eq NULL_SHA1);
640 my $page_deleted = ($new_sha1 eq NULL_SHA1);
641 $complete_file_name = mediawiki_clean_filename($complete_file_name);
643 if (substr($complete_file_name,-3) eq ".mw") {
644 my $title = substr($complete_file_name,0,-3);
646 my $file_content;
647 if ($page_deleted) {
648 # Deleting a page usually requires
649 # special priviledges. A common
650 # convention is to replace the page
651 # with this content instead:
652 $file_content = DELETED_CONTENT;
653 } else {
654 $file_content = run_git("cat-file blob $new_sha1");
657 mw_connect_maybe();
659 my $result = $mediawiki->edit( {
660 action => 'edit',
661 summary => $summary,
662 title => $title,
663 basetimestamp => $basetimestamps{$newrevid},
664 text => mediawiki_clean($file_content, $page_created),
665 }, {
666 skip_encoding => 1 # Helps with names with accentuated characters
668 if (!$result) {
669 if ($mediawiki->{error}->{code} == 3) {
670 # edit conflicts, considered as non-fast-forward
671 print STDERR 'Warning: Error ' .
672 $mediawiki->{error}->{code} .
673 ' from mediwiki: ' . $mediawiki->{error}->{details} .
674 ".\n";
675 return ($newrevid, "non-fast-forward");
676 } else {
677 # Other errors. Shouldn't happen => just die()
678 die 'Fatal: Error ' .
679 $mediawiki->{error}->{code} .
680 ' from mediwiki: ' . $mediawiki->{error}->{details};
683 $newrevid = $result->{edit}->{newrevid};
684 print STDERR "Pushed file: $new_sha1 - $title\n";
685 } else {
686 print STDERR "$complete_file_name not a mediawiki file (Not pushable on this version of git-remote-mediawiki).\n"
688 return ($newrevid, "ok");
691 sub mw_push {
692 # multiple push statements can follow each other
693 my @refsspecs = (shift, get_more_refs("push"));
694 my $pushed;
695 for my $refspec (@refsspecs) {
696 my ($force, $local, $remote) = $refspec =~ /^(\+)?([^:]*):([^:]*)$/
697 or die("Invalid refspec for push. Expected <src>:<dst> or +<src>:<dst>");
698 if ($force) {
699 print STDERR "Warning: forced push not allowed on a MediaWiki.\n";
701 if ($local eq "") {
702 print STDERR "Cannot delete remote branch on a MediaWiki\n";
703 print STDOUT "error $remote cannot delete\n";
704 next;
706 if ($remote ne "refs/heads/master") {
707 print STDERR "Only push to the branch 'master' is supported on a MediaWiki\n";
708 print STDOUT "error $remote only master allowed\n";
709 next;
711 if (mw_push_revision($local, $remote)) {
712 $pushed = 1;
716 # Notify Git that the push is done
717 print STDOUT "\n";
719 if ($pushed && $dumb_push) {
720 print STDERR "Just pushed some revisions to MediaWiki.\n";
721 print STDERR "The pushed revisions now have to be re-imported, and your current branch\n";
722 print STDERR "needs to be updated with these re-imported commits. You can do this with\n";
723 print STDERR "\n";
724 print STDERR " git pull --rebase\n";
725 print STDERR "\n";
729 sub mw_push_revision {
730 my $local = shift;
731 my $remote = shift; # actually, this has to be "refs/heads/master" at this point.
732 my $last_local_revid = get_last_local_revision();
733 print STDERR ".\n"; # Finish sentence started by get_last_local_revision()
734 my $last_remote_revid = get_last_remote_revision();
735 my $mw_revision = $last_remote_revid;
737 # Get sha1 of commit pointed by local HEAD
738 my $HEAD_sha1 = run_git("rev-parse $local 2>/dev/null"); chomp($HEAD_sha1);
739 # Get sha1 of commit pointed by remotes/$remotename/master
740 my $remoteorigin_sha1 = run_git("rev-parse refs/remotes/$remotename/master 2>/dev/null");
741 chomp($remoteorigin_sha1);
743 if ($last_local_revid > 0 &&
744 $last_local_revid < $last_remote_revid) {
745 return error_non_fast_forward($remote);
748 if ($HEAD_sha1 eq $remoteorigin_sha1) {
749 # nothing to push
750 return 0;
753 # Get every commit in between HEAD and refs/remotes/origin/master,
754 # including HEAD and refs/remotes/origin/master
755 my @commit_pairs = ();
756 if ($last_local_revid > 0) {
757 my $parsed_sha1 = $remoteorigin_sha1;
758 # Find a path from last MediaWiki commit to pushed commit
759 while ($parsed_sha1 ne $HEAD_sha1) {
760 my @commit_info = grep(/^$parsed_sha1/, split(/\n/, run_git("rev-list --children $local")));
761 if (!@commit_info) {
762 return error_non_fast_forward($remote);
764 my @commit_info_split = split(/ |\n/, $commit_info[0]);
765 # $commit_info_split[1] is the sha1 of the commit to export
766 # $commit_info_split[0] is the sha1 of its direct child
767 push(@commit_pairs, \@commit_info_split);
768 $parsed_sha1 = $commit_info_split[1];
770 } else {
771 # No remote mediawiki revision. Export the whole
772 # history (linearized with --first-parent)
773 print STDERR "Warning: no common ancestor, pushing complete history\n";
774 my $history = run_git("rev-list --first-parent --children $local");
775 my @history = split('\n', $history);
776 @history = @history[1..$#history];
777 foreach my $line (reverse @history) {
778 my @commit_info_split = split(/ |\n/, $line);
779 push(@commit_pairs, \@commit_info_split);
783 foreach my $commit_info_split (@commit_pairs) {
784 my $sha1_child = @{$commit_info_split}[0];
785 my $sha1_commit = @{$commit_info_split}[1];
786 my $diff_infos = run_git("diff-tree -r --raw -z $sha1_child $sha1_commit");
787 # TODO: we could detect rename, and encode them with a #redirect on the wiki.
788 # TODO: for now, it's just a delete+add
789 my @diff_info_list = split(/\0/, $diff_infos);
790 # Keep the first line of the commit message as mediawiki comment for the revision
791 my $commit_msg = (split(/\n/, run_git("show --pretty=format:\"%s\" $sha1_commit")))[0];
792 chomp($commit_msg);
793 # Push every blob
794 while (@diff_info_list) {
795 my $status;
796 # git diff-tree -z gives an output like
797 # <metadata>\0<filename1>\0
798 # <metadata>\0<filename2>\0
799 # and we've split on \0.
800 my $info = shift(@diff_info_list);
801 my $file = shift(@diff_info_list);
802 ($mw_revision, $status) = mw_push_file($info, $file, $commit_msg, $mw_revision);
803 if ($status eq "non-fast-forward") {
804 # we may already have sent part of the
805 # commit to MediaWiki, but it's too
806 # late to cancel it. Stop the push in
807 # the middle, but still give an
808 # accurate error message.
809 return error_non_fast_forward($remote);
811 if ($status ne "ok") {
812 die("Unknown error from mw_push_file()");
815 unless ($dumb_push) {
816 run_git("notes --ref=$remotename/mediawiki add -m \"mediawiki_revision: $mw_revision\" $sha1_commit");
817 run_git("update-ref -m \"Git-MediaWiki push\" refs/mediawiki/$remotename/master $sha1_commit $sha1_child");
821 print STDOUT "ok $remote\n";
822 return 1;