contrib / mw-to-git / git-remote-mediawikion commit Merge branch 'fg/submodule-git-file-git-dir' (efc5fb6)
   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
  36use strict;
  37use MediaWiki::API;
  38use DateTime::Format::ISO8601;
  39use encoding 'utf8';
  40
  41# use encoding 'utf8' doesn't change STDERROR
  42# but we're going to output UTF-8 filenames to STDERR
  43binmode STDERR, ":utf8";
  44
  45use URI::Escape;
  46use warnings;
  47
  48# Mediawiki filenames can contain forward slashes. This variable decides by which pattern they should be replaced
  49use constant SLASH_REPLACEMENT => "%2F";
  50
  51# It's not always possible to delete pages (may require some
  52# priviledges). Deleted pages are replaced with this content.
  53use constant DELETED_CONTENT => "[[Category:Deleted]]\n";
  54
  55# It's not possible to create empty pages. New empty files in Git are
  56# sent with this content instead.
  57use constant EMPTY_CONTENT => "<!-- empty page -->\n";
  58
  59# used to reflect file creation or deletion in diff.
  60use constant NULL_SHA1 => "0000000000000000000000000000000000000000";
  61
  62my $remotename = $ARGV[0];
  63my $url = $ARGV[1];
  64
  65# Accept both space-separated and multiple keys in config file.
  66# Spaces should be written as _ anyway because we'll use chomp.
  67my @tracked_pages = split(/[ \n]/, run_git("config --get-all remote.". $remotename .".pages"));
  68chomp(@tracked_pages);
  69
  70# Just like @tracked_pages, but for MediaWiki categories.
  71my @tracked_categories = split(/[ \n]/, run_git("config --get-all remote.". $remotename .".categories"));
  72chomp(@tracked_categories);
  73
  74my $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.
  78my $wiki_passwd = run_git("config --get remote.". $remotename .".mwPassword");
  79my $wiki_domain = run_git("config --get remote.". $remotename .".mwDomain");
  80chomp($wiki_login);
  81chomp($wiki_passwd);
  82chomp($wiki_domain);
  83
  84# Import only last revisions (both for clone and fetch)
  85my $shallow_import = run_git("config --get --bool remote.". $remotename .".shallow");
  86chomp($shallow_import);
  87$shallow_import = ($shallow_import eq "true");
  88
  89# Dumb push: don't update notes and mediawiki ref to reflect the last push.
  90#
  91# Configurable with mediawiki.dumbPush, or per-remote with
  92# remote.<remotename>.dumbPush.
  93#
  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.
 103my $dumb_push = run_git("config --get --bool remote.$remotename.dumbPush");
 104unless ($dumb_push) {
 105        $dumb_push = run_git("config --get --bool mediawiki.dumbPush");
 106}
 107chomp($dumb_push);
 108$dumb_push = ($dumb_push eq "true");
 109
 110my $wiki_name = $url;
 111$wiki_name =~ s/[^\/]*:\/\///;
 112
 113# Commands parser
 114my $entry;
 115my @cmd;
 116while (<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;
 138                }
 139        } else {
 140                # blank line: we should terminate
 141                last;
 142        }
 143
 144        BEGIN { $| = 1 } # flush STDOUT, to make sure the previous
 145                         # command is fully processed.
 146}
 147
 148########################## Functions ##############################
 149
 150# MediaWiki API instance, created lazily.
 151my $mediawiki;
 152
 153sub mw_connect_maybe {
 154        if ($mediawiki) {
 155            return;
 156        }
 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";
 172                }
 173        }
 174}
 175
 176sub get_mw_first_pages {
 177        my $some_pages = shift;
 178        my @some_pages = @{$some_pages};
 179
 180        my $pages = shift;
 181
 182        # pattern 'page1|page2|...' required by the API
 183        my $titles = join('|', @some_pages);
 184
 185        my $mw_pages = $mediawiki->api({
 186                action => 'query',
 187                titles => $titles,
 188        });
 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;
 194        }
 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;
 200                }
 201        }
 202}
 203
 204sub get_mw_pages {
 205        mw_connect_maybe();
 206
 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.
 213
 214                my @some_pages = @tracked_pages;
 215                while (@some_pages) {
 216                        my $last = 50;
 217                        if ($#some_pages < $last) {
 218                                $last = $#some_pages;
 219                        }
 220                        my @slice = @some_pages[0..$last];
 221                        get_mw_first_pages(\@slice, \%pages);
 222                        @some_pages = @some_pages[51..$#some_pages];
 223                }
 224        }
 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;
 233                        }
 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;
 242                        }
 243                }
 244        }
 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,
 252                });
 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;
 258                }
 259                foreach my $page (@{$mw_pages}) {
 260                        $pages{$page->{title}} = $page;
 261                }
 262        }
 263        return values(%pages);
 264}
 265
 266sub run_git {
 267        open(my $git, "-|:encoding(UTF-8)", "git " . $_[0]);
 268        my $res = do { local $/; <$git> };
 269        close($git);
 270
 271        return $res;
 272}
 273
 274
 275sub 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);
 279
 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";
 289        }
 290        return $lastrevision_number;
 291}
 292
 293# Remember the timestamp corresponding to a revision id.
 294my %basetimestamps;
 295
 296sub get_last_remote_revision {
 297        mw_connect_maybe();
 298
 299        my @pages = get_mw_pages();
 300
 301        my $max_rev_num = 0;
 302
 303        foreach my $page (@pages) {
 304                my $id = $page->{pageid};
 305
 306                my $query = {
 307                        action => 'query',
 308                        prop => 'revisions',
 309                        rvprop => 'ids|timestamp',
 310                        pageids => $id,
 311                };
 312
 313                my $result = $mediawiki->api($query);
 314
 315                my $lastrev = pop(@{$result->{query}->{pages}->{$id}->{revisions}});
 316
 317                $basetimestamps{$lastrev->{revid}} = $lastrev->{timestamp};
 318
 319                $max_rev_num = ($lastrev->{revid} > $max_rev_num ? $lastrev->{revid} : $max_rev_num);
 320        }
 321
 322        print STDERR "Last remote revision found is $max_rev_num.\n";
 323        return $max_rev_num;
 324}
 325
 326# Clean content before sending it to MediaWiki
 327sub 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;
 336        }
 337        return $string."\n";
 338}
 339
 340# Filter applied on MediaWiki data before adding them to Git
 341sub mediawiki_smudge {
 342        my $string = shift;
 343        if ($string eq EMPTY_CONTENT) {
 344                $string = "";
 345        }
 346        # This \n is important. This is due to mediawiki's way to handle end of files.
 347        return $string."\n";
 348}
 349
 350sub 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
 360
 361        return $filename;
 362}
 363
 364sub 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;
 371}
 372
 373sub literal_data {
 374        my ($content) = @_;
 375        print STDOUT "data ", bytes::length($content), "\n", $content;
 376}
 377
 378sub 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";
 387}
 388
 389sub 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";
 395}
 396
 397sub mw_option {
 398        print STDERR "remote-helper command 'option $_[0]' not yet implemented\n";
 399        print STDOUT "unsupported\n";
 400}
 401
 402sub 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,
 415        };
 416
 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);
 421
 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++;
 429                }
 430                last unless $result->{'query-continue'};
 431                $query->{rvstartid} = $result->{'query-continue'}->{revisions}->{rvstartid};
 432        }
 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];
 437        }
 438        print STDERR "  Found ", $revnum, " revision(s).\n";
 439        return @page_revs;
 440}
 441
 442sub fetch_mw_revisions {
 443        my $pages = shift; my @pages = @{$pages};
 444        my $fetch_from = shift;
 445
 446        my @revisions = ();
 447        my $n = 1;
 448        foreach my $page (@pages) {
 449                my $id = $page->{pageid};
 450
 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);
 455        }
 456
 457        return ($n, @revisions);
 458}
 459
 460sub import_file_revision {
 461        my $commit = shift;
 462        my %commit = %{$commit};
 463        my $full_import = shift;
 464        my $n = shift;
 465
 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};
 471
 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);
 476
 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";
 480        }
 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";
 487        }
 488
 489        # mediawiki revision number in the git note
 490        if ($full_import && $n == 1) {
 491                print STDOUT "reset refs/notes/$remotename/mediawiki\n";
 492        }
 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";
 498        }
 499        print STDOUT "N inline :$n\n";
 500        literal_data("mediawiki_revision: " . $commit{mw_revision});
 501        print STDOUT "\n\n";
 502}
 503
 504# parse a sequence of
 505# <cmd> <arg1>
 506# <cmd> <arg2>
 507# \n
 508# (like batch sequence of import and sequence of push statements)
 509sub 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: ". $_);
 520                }
 521        }
 522}
 523
 524sub 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);
 529        }
 530        print STDOUT "done\n";
 531}
 532
 533sub 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;
 542        }
 543
 544        mw_connect_maybe();
 545
 546        my @pages = get_mw_pages();
 547
 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";
 555        }
 556        my ($n, @revisions) = fetch_mw_revisions(\@pages, $fetch_from);
 557
 558        # Creation of the fast-import stream
 559        print STDERR "Fetching & writing export data...\n";
 560
 561        $n = 0;
 562        my $last_timestamp = 0; # Placeholer in case $rev->timestamp is undefined
 563
 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},
 571                };
 572
 573                my $result = $mediawiki->api($query);
 574
 575                my $rev = pop(@{$result->{query}->{pages}->{$pagerevid->{pageid}}->{revisions}});
 576
 577                $n++;
 578
 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}
 584                    );
 585                $commit{mw_revision} = $pagerevid->{revid};
 586                $commit{content} = mediawiki_smudge($rev->{'*'});
 587
 588                if (!defined($rev->{timestamp})) {
 589                        $last_timestamp++;
 590                } else {
 591                        $last_timestamp = $rev->{timestamp};
 592                }
 593                $commit{date} = DateTime::Format::ISO8601->parse_datetime($last_timestamp);
 594
 595                print STDERR "$n/", scalar(@revisions), ": Revision #$pagerevid->{revid} of $commit{title}\n";
 596
 597                import_file_revision(\%commit, ($fetch_from == 1), $n);
 598        }
 599
 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.
 605        }
 606}
 607
 608sub 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";
 618        }
 619        print STDOUT "error $_[0] \"non-fast-forward\"\n";
 620        return 0;
 621}
 622
 623sub 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);
 628
 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;
 636
 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);
 642
 643        if (substr($complete_file_name,-3) eq ".mw") {
 644                my $title = substr($complete_file_name,0,-3);
 645
 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");
 655                }
 656
 657                mw_connect_maybe();
 658
 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
 667                                  });
 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};
 681                        }
 682                }
 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"
 687        }
 688        return ($newrevid, "ok");
 689}
 690
 691sub 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";
 700                }
 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;
 705                }
 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;
 710                }
 711                if (mw_push_revision($local, $remote)) {
 712                        $pushed = 1;
 713                }
 714        }
 715
 716        # Notify Git that the push is done
 717        print STDOUT "\n";
 718
 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";
 726        }
 727}
 728
 729sub 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;
 736
 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);
 742
 743        if ($last_local_revid > 0 &&
 744            $last_local_revid < $last_remote_revid) {
 745                return error_non_fast_forward($remote);
 746        }
 747
 748        if ($HEAD_sha1 eq $remoteorigin_sha1) {
 749                # nothing to push
 750                return 0;
 751        }
 752
 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);
 763                        }
 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];
 769                }
 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);
 780                }
 781        }
 782
 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);
 810                        }
 811                        if ($status ne "ok") {
 812                                die("Unknown error from mw_push_file()");
 813                        }
 814                }
 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");
 818                }
 819        }
 820
 821        print STDOUT "ok $remote\n";
 822        return 1;
 823}