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