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