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 113# Commands parser 114my$entry; 115my@cmd; 116while(<STDIN>) { 117chomp; 118@cmd=split(/ /); 119if(defined($cmd[0])) { 120# Line not blank 121if($cmd[0]eq"capabilities") { 122die("Too many arguments for capabilities")unless(!defined($cmd[1])); 123 mw_capabilities(); 124}elsif($cmd[0]eq"list") { 125die("Too many arguments for list")unless(!defined($cmd[2])); 126 mw_list($cmd[1]); 127}elsif($cmd[0]eq"import") { 128die("Invalid arguments for import")unless($cmd[1]ne""&& !defined($cmd[2])); 129 mw_import($cmd[1]); 130}elsif($cmd[0]eq"option") { 131die("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{ 136print STDERR "Unknown command. Aborting...\n"; 137last; 138} 139}else{ 140# blank line: we should terminate 141last; 142} 143 144BEGIN{ $| =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 { 154if($mediawiki) { 155return; 156} 157$mediawiki= MediaWiki::API->new; 158$mediawiki->{config}->{api_url} ="$url/api.php"; 159if($wiki_login) { 160if(!$mediawiki->login({ 161 lgname =>$wiki_login, 162 lgpassword =>$wiki_passwd, 163 lgdomain =>$wiki_domain, 164})) { 165print STDERR "Failed to log in mediawiki user\"$wiki_login\"on$url\n"; 166print STDERR "(error ". 167$mediawiki->{error}->{code} .': '. 168$mediawiki->{error}->{details} .")\n"; 169exit1; 170}else{ 171print STDERR "Logged in with user\"$wiki_login\".\n"; 172} 173} 174} 175 176sub get_mw_first_pages { 177my$some_pages=shift; 178my@some_pages= @{$some_pages}; 179 180my$pages=shift; 181 182# pattern 'page1|page2|...' required by the API 183my$titles=join('|',@some_pages); 184 185my$mw_pages=$mediawiki->api({ 186 action =>'query', 187 titles =>$titles, 188}); 189if(!defined($mw_pages)) { 190print STDERR "fatal: could not query the list of wiki pages.\n"; 191print STDERR "fatal: '$url' does not appear to be a mediawiki\n"; 192print STDERR "fatal: make sure '$url/api.php' is a valid page.\n"; 193exit1; 194} 195while(my($id,$page) =each(%{$mw_pages->{query}->{pages}})) { 196if($id<0) { 197print 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 207my%pages;# hash on page titles to avoid duplicates 208my$user_defined; 209if(@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 214my@some_pages=@tracked_pages; 215while(@some_pages) { 216my$last=50; 217if($#some_pages<$last) { 218$last=$#some_pages; 219} 220my@slice=@some_pages[0..$last]; 221 get_mw_first_pages(\@slice, \%pages); 222@some_pages=@some_pages[51..$#some_pages]; 223} 224} 225if(@tracked_categories) { 226$user_defined=1; 227foreachmy$category(@tracked_categories) { 228if(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} 234my$mw_pages=$mediawiki->list( { 235 action =>'query', 236 list =>'categorymembers', 237 cmtitle =>$category, 238 cmlimit =>'max'} ) 239||die$mediawiki->{error}->{code} .': '.$mediawiki->{error}->{details}; 240foreachmy$page(@{$mw_pages}) { 241$pages{$page->{title}} =$page; 242} 243} 244} 245if(!$user_defined) { 246# No user-provided list, get the list of pages from 247# the API. 248my$mw_pages=$mediawiki->list({ 249 action =>'query', 250 list =>'allpages', 251 aplimit =>500, 252}); 253if(!defined($mw_pages)) { 254print STDERR "fatal: could not get the list of wiki pages.\n"; 255print STDERR "fatal: '$url' does not appear to be a mediawiki\n"; 256print STDERR "fatal: make sure '$url/api.php' is a valid page.\n"; 257exit1; 258} 259foreachmy$page(@{$mw_pages}) { 260$pages{$page->{title}} =$page; 261} 262} 263returnvalues(%pages); 264} 265 266sub run_git { 267open(my$git,"-|:encoding(UTF-8)","git ".$_[0]); 268my$res=do{local$/; <$git> }; 269close($git); 270 271return$res; 272} 273 274 275sub get_last_local_revision { 276# Get note regarding last mediawiki revision 277my$note= run_git("notes --ref=$remotename/mediawikishow refs/mediawiki/$remotename/master2>/dev/null"); 278my@note_info=split(/ /,$note); 279 280my$lastrevision_number; 281if(!(defined($note_info[0]) &&$note_info[0]eq"mediawiki_revision:")) { 282print 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]; 287chomp($lastrevision_number); 288print STDERR "Last local mediawiki revision found is$lastrevision_number"; 289} 290return$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 299my@pages= get_mw_pages(); 300 301my$max_rev_num=0; 302 303foreachmy$page(@pages) { 304my$id=$page->{pageid}; 305 306my$query= { 307 action =>'query', 308 prop =>'revisions', 309 rvprop =>'ids|timestamp', 310 pageids =>$id, 311}; 312 313my$result=$mediawiki->api($query); 314 315my$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 322print STDERR "Last remote revision found is$max_rev_num.\n"; 323return$max_rev_num; 324} 325 326# Clean content before sending it to MediaWiki 327sub mediawiki_clean { 328my$string=shift; 329my$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+$//; 333if($stringeq""&&$page_created) { 334# Creating empty pages is forbidden. 335$string= EMPTY_CONTENT; 336} 337return$string."\n"; 338} 339 340# Filter applied on MediaWiki data before adding them to Git 341sub mediawiki_smudge { 342my$string=shift; 343if($stringeq EMPTY_CONTENT) { 344$string=""; 345} 346# This \n is important. This is due to mediawiki's way to handle end of files. 347return$string."\n"; 348} 349 350sub mediawiki_clean_filename { 351my$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 361return$filename; 362} 363 364sub mediawiki_smudge_filename { 365my$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; 370return$filename; 371} 372 373sub literal_data { 374my($content) =@_; 375print 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. 382print STDOUT "refspec refs/heads/*:refs/mediawiki/$remotename/*\n"; 383print STDOUT "import\n"; 384print STDOUT "list\n"; 385print STDOUT "push\n"; 386print 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. 392print STDOUT "? refs/heads/master\n"; 393print STDOUT "\@refs/heads/masterHEAD\n"; 394print STDOUT "\n"; 395} 396 397sub mw_option { 398print STDERR "remote-helper command 'option$_[0]' not yet implemented\n"; 399print STDOUT "unsupported\n"; 400} 401 402sub fetch_mw_revisions_for_page { 403my$page=shift; 404my$id=shift; 405my$fetch_from=shift; 406my@page_revs= (); 407my$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 417my$revnum=0; 418# Get 500 revisions at a time due to the mediawiki api limit 419while(1) { 420my$result=$mediawiki->api($query); 421 422# Parse each of those 500 revisions 423foreachmy$revision(@{$result->{query}->{pages}->{$id}->{revisions}}) { 424my$page_rev_ids; 425$page_rev_ids->{pageid} =$page->{pageid}; 426$page_rev_ids->{revid} =$revision->{revid}; 427push(@page_revs,$page_rev_ids); 428$revnum++; 429} 430last unless$result->{'query-continue'}; 431$query->{rvstartid} =$result->{'query-continue'}->{revisions}->{rvstartid}; 432} 433if($shallow_import&&@page_revs) { 434print STDERR " Found 1 revision (shallow import).\n"; 435@page_revs=sort{$b->{revid} <=>$a->{revid}} (@page_revs); 436return$page_revs[0]; 437} 438print STDERR " Found ",$revnum," revision(s).\n"; 439return@page_revs; 440} 441 442sub fetch_mw_revisions { 443my$pages=shift;my@pages= @{$pages}; 444my$fetch_from=shift; 445 446my@revisions= (); 447my$n=1; 448foreachmy$page(@pages) { 449my$id=$page->{pageid}; 450 451print STDERR "page$n/",scalar(@pages),": ".$page->{title} ."\n"; 452$n++; 453my@page_revs= fetch_mw_revisions_for_page($page,$id,$fetch_from); 454@revisions= (@page_revs,@revisions); 455} 456 457return($n,@revisions); 458} 459 460sub import_file_revision { 461my$commit=shift; 462my%commit= %{$commit}; 463my$full_import=shift; 464my$n=shift; 465 466my$title=$commit{title}; 467my$comment=$commit{comment}; 468my$content=$commit{content}; 469my$author=$commit{author}; 470my$date=$commit{date}; 471 472print STDOUT "commit refs/mediawiki/$remotename/master\n"; 473print STDOUT "mark :$n\n"; 474print 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 478if(!$full_import&&$n==1) { 479print STDOUT "from refs/mediawiki/$remotename/master^0\n"; 480} 481if($contentne DELETED_CONTENT) { 482print STDOUT "M 644 inline$title.mw\n"; 483 literal_data($content); 484print STDOUT "\n\n"; 485}else{ 486print STDOUT "D$title.mw\n"; 487} 488 489# mediawiki revision number in the git note 490if($full_import&&$n==1) { 491print STDOUT "reset refs/notes/$remotename/mediawiki\n"; 492} 493print STDOUT "commit refs/notes/$remotename/mediawiki\n"; 494print STDOUT "committer$author<$author\@$wiki_name> ",$date->epoch," +0000\n"; 495 literal_data("Note added by git-mediawiki during import"); 496if(!$full_import&&$n==1) { 497print STDOUT "from refs/notes/$remotename/mediawiki^0\n"; 498} 499print STDOUT "N inline :$n\n"; 500 literal_data("mediawiki_revision: ".$commit{mw_revision}); 501print 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 { 510my$cmd=shift; 511my@refs; 512while(1) { 513my$line= <STDIN>; 514if($line=~m/^$cmd (.*)$/) { 515push(@refs,$1); 516}elsif($lineeq"\n") { 517return@refs; 518}else{ 519die("Invalid command in a '$cmd' batch: ".$_); 520} 521} 522} 523 524sub mw_import { 525# multiple import commands can follow each other. 526my@refs= (shift, get_more_refs("import")); 527foreachmy$ref(@refs) { 528 mw_import_ref($ref); 529} 530print STDOUT "done\n"; 531} 532 533sub mw_import_ref { 534my$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. 540if($refeq"HEAD") { 541return; 542} 543 544 mw_connect_maybe(); 545 546my@pages= get_mw_pages(); 547 548print STDERR "Searching revisions...\n"; 549my$last_local= get_last_local_revision(); 550my$fetch_from=$last_local+1; 551if($fetch_from==1) { 552print STDERR ", fetching from beginning.\n"; 553}else{ 554print STDERR ", fetching from here.\n"; 555} 556my($n,@revisions) = fetch_mw_revisions(\@pages,$fetch_from); 557 558# Creation of the fast-import stream 559print STDERR "Fetching & writing export data...\n"; 560 561$n=0; 562my$last_timestamp=0;# Placeholer in case $rev->timestamp is undefined 563 564foreachmy$pagerevid(sort{$a->{revid} <=>$b->{revid}}@revisions) { 565# fetch the content of the pages 566my$query= { 567 action =>'query', 568 prop =>'revisions', 569 rvprop =>'content|timestamp|comment|user|ids', 570 revids =>$pagerevid->{revid}, 571}; 572 573my$result=$mediawiki->api($query); 574 575my$rev=pop(@{$result->{query}->{pages}->{$pagerevid->{pageid}}->{revisions}}); 576 577$n++; 578 579my%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 588if(!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 595print STDERR "$n/",scalar(@revisions),": Revision #$pagerevid->{revid} of$commit{title}\n"; 596 597 import_file_revision(\%commit, ($fetch_from==1),$n); 598} 599 600if($fetch_from==1&&$n==0) { 601print 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 { 609my$advice= run_git("config --bool advice.pushNonFastForward"); 610chomp($advice); 611if($advicene"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. 615print STDERR "To prevent you from losing history, non-fast-forward updates were rejected\n"; 616print STDERR "Merge the remote changes (e.g. 'git pull') before pushing again. See the\n"; 617print STDERR "'Note about fast-forwards' section of 'git push --help' for details.\n"; 618} 619print STDOUT "error$_[0]\"non-fast-forward\"\n"; 620return0; 621} 622 623sub mw_push_file { 624my$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> 627my@diff_info_split=split(/[ \t]/,$diff_info); 628 629# Filename, including .mw extension 630my$complete_file_name=shift; 631# Commit message 632my$summary=shift; 633# MediaWiki revision number. Keep the previous one by default, 634# in case there's no edit to perform. 635my$newrevid=shift; 636 637my$new_sha1=$diff_info_split[3]; 638my$old_sha1=$diff_info_split[2]; 639my$page_created= ($old_sha1eq NULL_SHA1); 640my$page_deleted= ($new_sha1eq NULL_SHA1); 641$complete_file_name= mediawiki_clean_filename($complete_file_name); 642 643if(substr($complete_file_name,-3)eq".mw") { 644my$title=substr($complete_file_name,0,-3); 645 646my$file_content; 647if($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 659my$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}); 668if(!$result) { 669if($mediawiki->{error}->{code} ==3) { 670# edit conflicts, considered as non-fast-forward 671print STDERR 'Warning: Error '. 672$mediawiki->{error}->{code} . 673' from mediwiki: '.$mediawiki->{error}->{details} . 674".\n"; 675return($newrevid,"non-fast-forward"); 676}else{ 677# Other errors. Shouldn't happen => just die() 678die'Fatal: Error '. 679$mediawiki->{error}->{code} . 680' from mediwiki: '.$mediawiki->{error}->{details}; 681} 682} 683$newrevid=$result->{edit}->{newrevid}; 684print STDERR "Pushed file:$new_sha1-$title\n"; 685}else{ 686print STDERR "$complete_file_namenot a mediawiki file (Not pushable on this version of git-remote-mediawiki).\n" 687} 688return($newrevid,"ok"); 689} 690 691sub mw_push { 692# multiple push statements can follow each other 693my@refsspecs= (shift, get_more_refs("push")); 694my$pushed; 695formy$refspec(@refsspecs) { 696my($force,$local,$remote) =$refspec=~/^(\+)?([^:]*):([^:]*)$/ 697or die("Invalid refspec for push. Expected <src>:<dst> or +<src>:<dst>"); 698if($force) { 699print STDERR "Warning: forced push not allowed on a MediaWiki.\n"; 700} 701if($localeq"") { 702print STDERR "Cannot delete remote branch on a MediaWiki\n"; 703print STDOUT "error$remotecannot delete\n"; 704next; 705} 706if($remotene"refs/heads/master") { 707print STDERR "Only push to the branch 'master' is supported on a MediaWiki\n"; 708print STDOUT "error$remoteonly master allowed\n"; 709next; 710} 711if(mw_push_revision($local,$remote)) { 712$pushed=1; 713} 714} 715 716# Notify Git that the push is done 717print STDOUT "\n"; 718 719if($pushed&&$dumb_push) { 720print STDERR "Just pushed some revisions to MediaWiki.\n"; 721print STDERR "The pushed revisions now have to be re-imported, and your current branch\n"; 722print STDERR "needs to be updated with these re-imported commits. You can do this with\n"; 723print STDERR "\n"; 724print STDERR " git pull --rebase\n"; 725print STDERR "\n"; 726} 727} 728 729sub mw_push_revision { 730my$local=shift; 731my$remote=shift;# actually, this has to be "refs/heads/master" at this point. 732my$last_local_revid= get_last_local_revision(); 733print STDERR ".\n";# Finish sentence started by get_last_local_revision() 734my$last_remote_revid= get_last_remote_revision(); 735my$mw_revision=$last_remote_revid; 736 737# Get sha1 of commit pointed by local HEAD 738my$HEAD_sha1= run_git("rev-parse$local2>/dev/null");chomp($HEAD_sha1); 739# Get sha1 of commit pointed by remotes/$remotename/master 740my$remoteorigin_sha1= run_git("rev-parse refs/remotes/$remotename/master2>/dev/null"); 741chomp($remoteorigin_sha1); 742 743if($last_local_revid>0&& 744$last_local_revid<$last_remote_revid) { 745return error_non_fast_forward($remote); 746} 747 748if($HEAD_sha1eq$remoteorigin_sha1) { 749# nothing to push 750return0; 751} 752 753# Get every commit in between HEAD and refs/remotes/origin/master, 754# including HEAD and refs/remotes/origin/master 755my@commit_pairs= (); 756if($last_local_revid>0) { 757my$parsed_sha1=$remoteorigin_sha1; 758# Find a path from last MediaWiki commit to pushed commit 759while($parsed_sha1ne$HEAD_sha1) { 760my@commit_info=grep(/^$parsed_sha1/,split(/\n/, run_git("rev-list --children$local"))); 761if(!@commit_info) { 762return error_non_fast_forward($remote); 763} 764my@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 767push(@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) 773print STDERR "Warning: no common ancestor, pushing complete history\n"; 774my$history= run_git("rev-list --first-parent --children$local"); 775my@history=split('\n',$history); 776@history=@history[1..$#history]; 777foreachmy$line(reverse@history) { 778my@commit_info_split=split(/ |\n/,$line); 779push(@commit_pairs, \@commit_info_split); 780} 781} 782 783foreachmy$commit_info_split(@commit_pairs) { 784my$sha1_child= @{$commit_info_split}[0]; 785my$sha1_commit= @{$commit_info_split}[1]; 786my$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 789my@diff_info_list=split(/\0/,$diff_infos); 790# Keep the first line of the commit message as mediawiki comment for the revision 791my$commit_msg= (split(/\n/, run_git("show --pretty=format:\"%s\"$sha1_commit")))[0]; 792chomp($commit_msg); 793# Push every blob 794while(@diff_info_list) { 795my$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. 800my$info=shift(@diff_info_list); 801my$file=shift(@diff_info_list); 802($mw_revision,$status) = mw_push_file($info,$file,$commit_msg,$mw_revision); 803if($statuseq"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. 809return error_non_fast_forward($remote); 810} 811if($statusne"ok") { 812die("Unknown error from mw_push_file()"); 813} 814} 815unless($dumb_push) { 816 run_git("notes --ref=$remotename/mediawikiadd -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 821print STDOUT "ok$remote\n"; 822return1; 823}