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 # Documentation & bugtracker: https://github.com/moy/Git-Mediawiki/
16 use DateTime
::Format
::ISO8601
;
18 # By default, use UTF-8 to communicate with Git and the user
19 binmode STDERR
, ":utf8";
20 binmode STDOUT
, ":utf8";
27 # Mediawiki filenames can contain forward slashes. This variable decides by which pattern they should be replaced
28 use constant SLASH_REPLACEMENT
=> "%2F";
30 # It's not always possible to delete pages (may require some
31 # privileges). Deleted pages are replaced with this content.
32 use constant DELETED_CONTENT
=> "[[Category:Deleted]]\n";
34 # It's not possible to create empty pages. New empty files in Git are
35 # sent with this content instead.
36 use constant EMPTY_CONTENT
=> "<!-- empty page -->\n";
38 # used to reflect file creation or deletion in diff.
39 use constant NULL_SHA1
=> "0000000000000000000000000000000000000000";
41 # Used on Git's side to reflect empty edit messages on the wiki
42 use constant EMPTY_MESSAGE
=> '*Empty MediaWiki Message*';
44 my $remotename = $ARGV[0];
47 # Accept both space-separated and multiple keys in config file.
48 # Spaces should be written as _ anyway because we'll use chomp.
49 my @tracked_pages = split(/[ \n]/, run_git
("config --get-all remote.". $remotename .".pages"));
50 chomp(@tracked_pages);
52 # Just like @tracked_pages, but for MediaWiki categories.
53 my @tracked_categories = split(/[ \n]/, run_git
("config --get-all remote.". $remotename .".categories"));
54 chomp(@tracked_categories);
56 # Import media files on pull
57 my $import_media = run_git
("config --get --bool remote.". $remotename .".mediaimport");
59 $import_media = ($import_media eq "true");
61 # Export media files on push
62 my $export_media = run_git
("config --get --bool remote.". $remotename .".mediaexport");
64 $export_media = !($export_media eq "false");
66 my $wiki_login = run_git
("config --get remote.". $remotename .".mwLogin");
67 # Note: mwPassword is discourraged. Use the credential system instead.
68 my $wiki_passwd = run_git
("config --get remote.". $remotename .".mwPassword");
69 my $wiki_domain = run_git
("config --get remote.". $remotename .".mwDomain");
74 # Import only last revisions (both for clone and fetch)
75 my $shallow_import = run_git
("config --get --bool remote.". $remotename .".shallow");
76 chomp($shallow_import);
77 $shallow_import = ($shallow_import eq "true");
79 # Fetch (clone and pull) by revisions instead of by pages. This behavior
80 # is more efficient when we have a wiki with lots of pages and we fetch
81 # the revisions quite often so that they concern only few pages.
83 # - by_rev: perform one query per new revision on the remote wiki
84 # - by_page: query each tracked page for new revision
85 my $fetch_strategy = run_git
("config --get remote.$remotename.fetchStrategy");
86 unless ($fetch_strategy) {
87 $fetch_strategy = run_git
("config --get mediawiki.fetchStrategy");
89 chomp($fetch_strategy);
90 unless ($fetch_strategy) {
91 $fetch_strategy = "by_page";
94 # Dumb push: don't update notes and mediawiki ref to reflect the last push.
96 # Configurable with mediawiki.dumbPush, or per-remote with
97 # remote.<remotename>.dumbPush.
99 # This means the user will have to re-import the just-pushed
100 # revisions. On the other hand, this means that the Git revisions
101 # corresponding to MediaWiki revisions are all imported from the wiki,
102 # regardless of whether they were initially created in Git or from the
103 # web interface, hence all users will get the same history (i.e. if
104 # the push from Git to MediaWiki loses some information, everybody
105 # will get the history with information lost). If the import is
106 # deterministic, this means everybody gets the same sha1 for each
107 # MediaWiki revision.
108 my $dumb_push = run_git
("config --get --bool remote.$remotename.dumbPush");
109 unless ($dumb_push) {
110 $dumb_push = run_git
("config --get --bool mediawiki.dumbPush");
113 $dumb_push = ($dumb_push eq "true");
115 my $wiki_name = $url;
116 $wiki_name =~ s/[^\/]*:\/\
///;
117 # If URL is like http://user:password@example.com/, we clearly don't
118 # want the password in $wiki_name. While we're there, also remove user
119 # and '@' sign, to avoid author like MWUser@HTTPUser@host.com
120 $wiki_name =~ s/^.*@//;
128 if (defined($cmd[0])) {
130 if ($cmd[0] eq "capabilities") {
131 die("Too many arguments for capabilities") unless (!defined($cmd[1]));
133 } elsif ($cmd[0] eq "list") {
134 die("Too many arguments for list") unless (!defined($cmd[2]));
136 } elsif ($cmd[0] eq "import") {
137 die("Invalid arguments for import") unless ($cmd[1] ne "" && !defined($cmd[2]));
139 } elsif ($cmd[0] eq "option") {
140 die("Too many arguments for option") unless ($cmd[1] ne "" && $cmd[2] ne "" && !defined($cmd[3]));
141 mw_option
($cmd[1],$cmd[2]);
142 } elsif ($cmd[0] eq "push") {
145 print STDERR
"Unknown command. Aborting...\n";
149 # blank line: we should terminate
153 BEGIN { $| = 1 } # flush STDOUT, to make sure the previous
154 # command is fully processed.
157 ########################## Functions ##############################
159 ## credential API management (generic functions)
161 sub credential_read
{
166 my ($key, $value) = /([^=]*)=(.*)/;
167 if (not defined $key) {
168 die "ERROR receiving response from git credential $op:\n$_\n";
170 $credential{$key} = $value;
175 sub credential_write
{
176 my $credential = shift;
178 # url overwrites other fields, so it must come first
179 print $writer "url=$credential->{url}\n" if exists $credential->{url
};
180 while (my ($key, $value) = each(%$credential) ) {
181 if (length $value && $key ne 'url') {
182 print $writer "$key=$value\n";
189 my $credential = shift;
190 my $pid = open2
(my $reader, my $writer, "git credential $op");
191 credential_write
($credential, $writer);
196 %$credential = credential_read
($reader, $op);
199 die "ERROR while running git credential $op:\n$_";
204 my $child_exit_status = $?
>> 8;
205 if ($child_exit_status != 0) {
206 die "'git credential $op' failed with code $child_exit_status.";
210 # MediaWiki API instance, created lazily.
213 sub mw_connect_maybe
{
217 $mediawiki = MediaWiki
::API
->new;
218 $mediawiki->{config
}->{api_url
} = "$url/api.php";
220 my %credential = (url
=> $url);
221 $credential{username
} = $wiki_login;
222 $credential{password
} = $wiki_passwd;
223 credential_run
("fill", \
%credential);
224 my $request = {lgname
=> $credential{username
},
225 lgpassword
=> $credential{password
},
226 lgdomain
=> $wiki_domain};
227 if ($mediawiki->login($request)) {
228 credential_run
("approve", \
%credential);
229 print STDERR
"Logged in mediawiki user \"$credential{username}\".\n";
231 print STDERR
"Failed to log in mediawiki user \"$credential{username}\" on $url\n";
232 print STDERR
" (error " .
233 $mediawiki->{error
}->{code
} . ': ' .
234 $mediawiki->{error
}->{details
} . ")\n";
235 credential_run
("reject", \
%credential);
243 print STDERR
"fatal: could not $action.\n";
244 print STDERR
"fatal: '$url' does not appear to be a mediawiki\n";
245 if ($url =~ /^https/) {
246 print STDERR
"fatal: make sure '$url/api.php' is a valid page\n";
247 print STDERR
"fatal: and the SSL certificate is correct.\n";
249 print STDERR
"fatal: make sure '$url/api.php' is a valid page.\n";
251 print STDERR
"fatal: (error " .
252 $mediawiki->{error
}->{code
} . ': ' .
253 $mediawiki->{error
}->{details
} . ")\n";
257 ## Functions for listing pages on the remote wiki
258 sub get_mw_tracked_pages
{
260 get_mw_page_list
(\
@tracked_pages, $pages);
263 sub get_mw_page_list
{
264 my $page_list = shift;
266 my @some_pages = @
$page_list;
267 while (@some_pages) {
269 if ($#some_pages < $last) {
270 $last = $#some_pages;
272 my @slice = @some_pages[0..$last];
273 get_mw_first_pages
(\
@slice, $pages);
274 @some_pages = @some_pages[51..$#some_pages];
278 sub get_mw_tracked_categories
{
280 foreach my $category (@tracked_categories) {
281 if (index($category, ':') < 0) {
282 # Mediawiki requires the Category
283 # prefix, but let's not force the user
285 $category = "Category:" . $category;
287 my $mw_pages = $mediawiki->list( {
289 list
=> 'categorymembers',
290 cmtitle
=> $category,
292 || die $mediawiki->{error
}->{code
} . ': '
293 . $mediawiki->{error
}->{details
};
294 foreach my $page (@
{$mw_pages}) {
295 $pages->{$page->{title
}} = $page;
300 sub get_mw_all_pages
{
302 # No user-provided list, get the list of pages from the API.
303 my $mw_pages = $mediawiki->list({
308 if (!defined($mw_pages)) {
309 fatal_mw_error
("get the list of wiki pages");
311 foreach my $page (@
{$mw_pages}) {
312 $pages->{$page->{title
}} = $page;
316 # queries the wiki for a set of pages. Meant to be used within a loop
317 # querying the wiki for slices of page list.
318 sub get_mw_first_pages
{
319 my $some_pages = shift;
320 my @some_pages = @
{$some_pages};
324 # pattern 'page1|page2|...' required by the API
325 my $titles = join('|', @some_pages);
327 my $mw_pages = $mediawiki->api({
331 if (!defined($mw_pages)) {
332 fatal_mw_error
("query the list of wiki pages");
334 while (my ($id, $page) = each(%{$mw_pages->{query
}->{pages
}})) {
336 print STDERR
"Warning: page $page->{title} not found on wiki\n";
338 $pages->{$page->{title
}} = $page;
343 # Get the list of pages to be fetched according to configuration.
347 print STDERR
"Listing pages on remote wiki...\n";
349 my %pages; # hash on page titles to avoid duplicates
351 if (@tracked_pages) {
353 # The user provided a list of pages titles, but we
354 # still need to query the API to get the page IDs.
355 get_mw_tracked_pages
(\
%pages);
357 if (@tracked_categories) {
359 get_mw_tracked_categories
(\
%pages);
361 if (!$user_defined) {
362 get_mw_all_pages
(\
%pages);
365 print STDERR
"Getting media files for selected pages...\n";
367 get_linked_mediafiles
(\
%pages);
369 get_all_mediafiles
(\
%pages);
372 print STDERR
(scalar keys %pages) . " pages found.\n";
376 # usage: $out = run_git("command args");
377 # $out = run_git("command args", "raw"); # don't interpret output as UTF-8.
380 my $encoding = (shift || "encoding(UTF-8)");
381 open(my $git, "-|:$encoding", "git " . $args);
382 my $res = do { local $/; <$git> };
389 sub get_all_mediafiles
{
391 # Attach list of all pages for media files from the API,
392 # they are in a different namespace, only one namespace
393 # can be queried at the same moment
394 my $mw_pages = $mediawiki->list({
397 apnamespace
=> get_mw_namespace_id
("File"),
400 if (!defined($mw_pages)) {
401 print STDERR
"fatal: could not get the list of pages for media files.\n";
402 print STDERR
"fatal: '$url' does not appear to be a mediawiki\n";
403 print STDERR
"fatal: make sure '$url/api.php' is a valid page.\n";
406 foreach my $page (@
{$mw_pages}) {
407 $pages->{$page->{title
}} = $page;
411 sub get_linked_mediafiles
{
413 my @titles = map $_->{title
}, values(%{$pages});
415 # The query is split in small batches because of the MW API limit of
416 # the number of links to be returned (500 links max).
419 if ($#titles < $batch) {
422 my @slice = @titles[0..$batch];
424 # pattern 'page1|page2|...' required by the API
425 my $mw_titles = join('|', @slice);
427 # Media files could be included or linked from
428 # a page, get all related
431 prop
=> 'links|images',
432 titles
=> $mw_titles,
433 plnamespace
=> get_mw_namespace_id
("File"),
436 my $result = $mediawiki->api($query);
438 while (my ($id, $page) = each(%{$result->{query
}->{pages
}})) {
440 if (defined($page->{links
})) {
441 my @link_titles = map $_->{title
}, @
{$page->{links
}};
442 push(@media_titles, @link_titles);
444 if (defined($page->{images
})) {
445 my @image_titles = map $_->{title
}, @
{$page->{images
}};
446 push(@media_titles, @image_titles);
449 get_mw_page_list
(\
@media_titles, $pages);
453 @titles = @titles[($batch+1)..$#titles];
457 sub get_mw_mediafile_for_page_revision
{
458 # Name of the file on Wiki, with the prefix.
459 my $filename = shift;
460 my $timestamp = shift;
463 # Search if on a media file with given timestamp exists on
464 # MediaWiki. In that case download the file.
468 titles
=> "File:" . $filename,
469 iistart
=> $timestamp,
471 iiprop
=> 'timestamp|archivename|url',
474 my $result = $mediawiki->api($query);
476 my ($fileid, $file) = each( %{$result->{query
}->{pages
}} );
477 # If not defined it means there is no revision of the file for
479 if (defined($file->{imageinfo
})) {
480 $mediafile{title
} = $filename;
482 my $fileinfo = pop(@
{$file->{imageinfo
}});
483 $mediafile{timestamp
} = $fileinfo->{timestamp
};
484 # Mediawiki::API's download function doesn't support https URLs
485 # and can't download old versions of files.
486 print STDERR
"\tDownloading file $mediafile{title}, version $mediafile{timestamp}\n";
487 $mediafile{content
} = download_mw_mediafile
($fileinfo->{url
});
492 sub download_mw_mediafile
{
495 my $response = $mediawiki->{ua
}->get($url);
496 if ($response->code == 200) {
497 return $response->decoded_content;
499 print STDERR
"Error downloading mediafile from :\n";
500 print STDERR
"URL: $url\n";
501 print STDERR
"Server response: " . $response->code . " " . $response->message . "\n";
506 sub get_last_local_revision
{
507 # Get note regarding last mediawiki revision
508 my $note = run_git
("notes --ref=$remotename/mediawiki show refs/mediawiki/$remotename/master 2>/dev/null");
509 my @note_info = split(/ /, $note);
511 my $lastrevision_number;
512 if (!(defined($note_info[0]) && $note_info[0] eq "mediawiki_revision:")) {
513 print STDERR
"No previous mediawiki revision found";
514 $lastrevision_number = 0;
516 # Notes are formatted : mediawiki_revision: #number
517 $lastrevision_number = $note_info[1];
518 chomp($lastrevision_number);
519 print STDERR
"Last local mediawiki revision found is $lastrevision_number";
521 return $lastrevision_number;
524 # Remember the timestamp corresponding to a revision id.
527 # Get the last remote revision without taking in account which pages are
528 # tracked or not. This function makes a single request to the wiki thus
529 # avoid a loop onto all tracked pages. This is useful for the fetch-by-rev
531 sub get_last_global_remote_rev
{
536 list
=> 'recentchanges',
541 my $result = $mediawiki->api($query);
542 return $result->{query
}->{recentchanges
}[0]->{revid
};
545 # Get the last remote revision concerning the tracked pages and the tracked
547 sub get_last_remote_revision
{
550 my %pages_hash = get_mw_pages
();
551 my @pages = values(%pages_hash);
555 print STDERR
"Getting last revision id on tracked pages...\n";
557 foreach my $page (@pages) {
558 my $id = $page->{pageid
};
563 rvprop
=> 'ids|timestamp',
567 my $result = $mediawiki->api($query);
569 my $lastrev = pop(@
{$result->{query
}->{pages
}->{$id}->{revisions
}});
571 $basetimestamps{$lastrev->{revid
}} = $lastrev->{timestamp
};
573 $max_rev_num = ($lastrev->{revid
} > $max_rev_num ?
$lastrev->{revid
} : $max_rev_num);
576 print STDERR
"Last remote revision found is $max_rev_num.\n";
580 # Clean content before sending it to MediaWiki
581 sub mediawiki_clean
{
583 my $page_created = shift;
584 # Mediawiki does not allow blank space at the end of a page and ends with a single \n.
585 # This function right trims a string and adds a \n at the end to follow this rule
587 if ($string eq "" && $page_created) {
588 # Creating empty pages is forbidden.
589 $string = EMPTY_CONTENT
;
594 # Filter applied on MediaWiki data before adding them to Git
595 sub mediawiki_smudge
{
597 if ($string eq EMPTY_CONTENT
) {
600 # This \n is important. This is due to mediawiki's way to handle end of files.
604 sub mediawiki_clean_filename
{
605 my $filename = shift;
606 $filename =~ s/@{[SLASH_REPLACEMENT]}/\//g
;
607 # [, ], |, {, and } are forbidden by MediaWiki, even URL-encoded.
608 # Do a variant of URL-encoding, i.e. looks like URL-encoding,
609 # but with _ added to prevent MediaWiki from thinking this is
610 # an actual special character.
611 $filename =~ s/[\[\]\{\}\|]/sprintf("_%%_%x", ord($&))/ge;
612 # If we use the uri escape before
613 # we should unescape here, before anything
618 sub mediawiki_smudge_filename
{
619 my $filename = shift;
620 $filename =~ s/\//@
{[SLASH_REPLACEMENT
]}/g
;
621 $filename =~ s/ /_/g;
622 # Decode forbidden characters encoded in mediawiki_clean_filename
623 $filename =~ s/_%_([0-9a-fA-F][0-9a-fA-F])/sprintf("%c", hex($1))/ge;
629 print STDOUT
"data ", bytes
::length($content), "\n", $content;
632 sub literal_data_raw
{
633 # Output possibly binary content.
635 # Avoid confusion between size in bytes and in characters
636 utf8
::downgrade
($content);
637 binmode STDOUT
, ":raw";
638 print STDOUT
"data ", bytes
::length($content), "\n", $content;
639 binmode STDOUT
, ":utf8";
642 sub mw_capabilities
{
643 # Revisions are imported to the private namespace
644 # refs/mediawiki/$remotename/ by the helper and fetched into
645 # refs/remotes/$remotename later by fetch.
646 print STDOUT
"refspec refs/heads/*:refs/mediawiki/$remotename/*\n";
647 print STDOUT
"import\n";
648 print STDOUT
"list\n";
649 print STDOUT
"push\n";
654 # MediaWiki do not have branches, we consider one branch arbitrarily
655 # called master, and HEAD pointing to it.
656 print STDOUT
"? refs/heads/master\n";
657 print STDOUT
"\@refs/heads/master HEAD\n";
662 print STDERR
"remote-helper command 'option $_[0]' not yet implemented\n";
663 print STDOUT
"unsupported\n";
666 sub fetch_mw_revisions_for_page
{
669 my $fetch_from = shift;
676 rvstartid
=> $fetch_from,
682 # Get 500 revisions at a time due to the mediawiki api limit
684 my $result = $mediawiki->api($query);
686 # Parse each of those 500 revisions
687 foreach my $revision (@
{$result->{query
}->{pages
}->{$id}->{revisions
}}) {
689 $page_rev_ids->{pageid
} = $page->{pageid
};
690 $page_rev_ids->{revid
} = $revision->{revid
};
691 push(@page_revs, $page_rev_ids);
694 last unless $result->{'query-continue'};
695 $query->{rvstartid
} = $result->{'query-continue'}->{revisions
}->{rvstartid
};
697 if ($shallow_import && @page_revs) {
698 print STDERR
" Found 1 revision (shallow import).\n";
699 @page_revs = sort {$b->{revid
} <=> $a->{revid
}} (@page_revs);
700 return $page_revs[0];
702 print STDERR
" Found ", $revnum, " revision(s).\n";
706 sub fetch_mw_revisions
{
707 my $pages = shift; my @pages = @
{$pages};
708 my $fetch_from = shift;
712 foreach my $page (@pages) {
713 my $id = $page->{pageid
};
715 print STDERR
"page $n/", scalar(@pages), ": ". $page->{title
} ."\n";
717 my @page_revs = fetch_mw_revisions_for_page
($page, $id, $fetch_from);
718 @revisions = (@page_revs, @revisions);
721 return ($n, @revisions);
726 $path =~ s/\\/\\\\/g;
729 return '"' . $path . '"';
732 sub import_file_revision
{
734 my %commit = %{$commit};
735 my $full_import = shift;
737 my $mediafile = shift;
740 %mediafile = %{$mediafile};
743 my $title = $commit{title
};
744 my $comment = $commit{comment
};
745 my $content = $commit{content
};
746 my $author = $commit{author
};
747 my $date = $commit{date
};
749 print STDOUT
"commit refs/mediawiki/$remotename/master\n";
750 print STDOUT
"mark :$n\n";
751 print STDOUT
"committer $author <$author\@$wiki_name> ", $date->epoch, " +0000\n";
752 literal_data
($comment);
754 # If it's not a clone, we need to know where to start from
755 if (!$full_import && $n == 1) {
756 print STDOUT
"from refs/mediawiki/$remotename/master^0\n";
758 if ($content ne DELETED_CONTENT
) {
759 print STDOUT
"M 644 inline " .
760 fe_escape_path
($title . ".mw") . "\n";
761 literal_data
($content);
763 print STDOUT
"M 644 inline "
764 . fe_escape_path
($mediafile{title
}) . "\n";
765 literal_data_raw
($mediafile{content
});
769 print STDOUT
"D " . fe_escape_path
($title . ".mw") . "\n";
772 # mediawiki revision number in the git note
773 if ($full_import && $n == 1) {
774 print STDOUT
"reset refs/notes/$remotename/mediawiki\n";
776 print STDOUT
"commit refs/notes/$remotename/mediawiki\n";
777 print STDOUT
"committer $author <$author\@$wiki_name> ", $date->epoch, " +0000\n";
778 literal_data
("Note added by git-mediawiki during import");
779 if (!$full_import && $n == 1) {
780 print STDOUT
"from refs/notes/$remotename/mediawiki^0\n";
782 print STDOUT
"N inline :$n\n";
783 literal_data
("mediawiki_revision: " . $commit{mw_revision
});
787 # parse a sequence of
791 # (like batch sequence of import and sequence of push statements)
797 if ($line =~ m/^$cmd (.*)$/) {
799 } elsif ($line eq "\n") {
802 die("Invalid command in a '$cmd' batch: ". $_);
808 # multiple import commands can follow each other.
809 my @refs = (shift, get_more_refs
("import"));
810 foreach my $ref (@refs) {
813 print STDOUT
"done\n";
818 # The remote helper will call "import HEAD" and
819 # "import refs/heads/master".
820 # Since HEAD is a symbolic ref to master (by convention,
821 # followed by the output of the command "list" that we gave),
822 # we don't need to do anything in this case.
823 if ($ref eq "HEAD") {
829 print STDERR
"Searching revisions...\n";
830 my $last_local = get_last_local_revision
();
831 my $fetch_from = $last_local + 1;
832 if ($fetch_from == 1) {
833 print STDERR
", fetching from beginning.\n";
835 print STDERR
", fetching from here.\n";
839 if ($fetch_strategy eq "by_rev") {
840 print STDERR
"Fetching & writing export data by revs...\n";
841 $n = mw_import_ref_by_revs
($fetch_from);
842 } elsif ($fetch_strategy eq "by_page") {
843 print STDERR
"Fetching & writing export data by pages...\n";
844 $n = mw_import_ref_by_pages
($fetch_from);
846 print STDERR
"fatal: invalid fetch strategy \"$fetch_strategy\".\n";
847 print STDERR
"Check your configuration variables remote.$remotename.fetchStrategy and mediawiki.fetchStrategy\n";
851 if ($fetch_from == 1 && $n == 0) {
852 print STDERR
"You appear to have cloned an empty MediaWiki.\n";
853 # Something has to be done remote-helper side. If nothing is done, an error is
854 # thrown saying that HEAD is referring to unknown object 0000000000000000000
855 # and the clone fails.
859 sub mw_import_ref_by_pages
{
861 my $fetch_from = shift;
862 my %pages_hash = get_mw_pages
();
863 my @pages = values(%pages_hash);
865 my ($n, @revisions) = fetch_mw_revisions
(\
@pages, $fetch_from);
867 @revisions = sort {$a->{revid
} <=> $b->{revid
}} @revisions;
868 my @revision_ids = map $_->{revid
}, @revisions;
870 return mw_import_revids
($fetch_from, \
@revision_ids, \
%pages_hash);
873 sub mw_import_ref_by_revs
{
875 my $fetch_from = shift;
876 my %pages_hash = get_mw_pages
();
878 my $last_remote = get_last_global_remote_rev
();
879 my @revision_ids = $fetch_from..$last_remote;
880 return mw_import_revids
($fetch_from, \
@revision_ids, \
%pages_hash);
883 # Import revisions given in second argument (array of integers).
884 # Only pages appearing in the third argument (hash indexed by page titles)
886 sub mw_import_revids
{
887 my $fetch_from = shift;
888 my $revision_ids = shift;
893 my $last_timestamp = 0; # Placeholer in case $rev->timestamp is undefined
895 foreach my $pagerevid (@
$revision_ids) {
896 # Count page even if we skip it, since we display
897 # $n/$total and $total includes skipped pages.
900 # fetch the content of the pages
904 rvprop
=> 'content|timestamp|comment|user|ids',
905 revids
=> $pagerevid,
908 my $result = $mediawiki->api($query);
911 die "Failed to retrieve modified page for revision $pagerevid";
914 if (defined($result->{query
}->{badrevids
}->{$pagerevid})) {
915 # The revision id does not exist on the remote wiki.
919 if (!defined($result->{query
}->{pages
})) {
920 die "Invalid revision $pagerevid.";
923 my @result_pages = values(%{$result->{query
}->{pages
}});
924 my $result_page = $result_pages[0];
925 my $rev = $result_pages[0]->{revisions
}->[0];
927 my $page_title = $result_page->{title
};
929 if (!exists($pages->{$page_title})) {
930 print STDERR
"$n/", scalar(@
$revision_ids),
931 ": Skipping revision #$rev->{revid} of $page_title\n";
938 $commit{author
} = $rev->{user
} || 'Anonymous';
939 $commit{comment
} = $rev->{comment
} || EMPTY_MESSAGE
;
940 $commit{title
} = mediawiki_smudge_filename
($page_title);
941 $commit{mw_revision
} = $rev->{revid
};
942 $commit{content
} = mediawiki_smudge
($rev->{'*'});
944 if (!defined($rev->{timestamp
})) {
947 $last_timestamp = $rev->{timestamp
};
949 $commit{date
} = DateTime
::Format
::ISO8601
->parse_datetime($last_timestamp);
951 # Differentiates classic pages and media files.
952 my ($namespace, $filename) = $page_title =~ /^([^:]*):(.*)$/;
955 my $id = get_mw_namespace_id
($namespace);
956 if ($id && $id == get_mw_namespace_id
("File")) {
957 %mediafile = get_mw_mediafile_for_page_revision
($filename, $rev->{timestamp
});
960 # If this is a revision of the media page for new version
961 # of a file do one common commit for both file and media page.
962 # Else do commit only for that page.
963 print STDERR
"$n/", scalar(@
$revision_ids), ": Revision #$rev->{revid} of $commit{title}\n";
964 import_file_revision
(\
%commit, ($fetch_from == 1), $n_actual, \
%mediafile);
970 sub error_non_fast_forward
{
971 my $advice = run_git
("config --bool advice.pushNonFastForward");
973 if ($advice ne "false") {
974 # Native git-push would show this after the summary.
975 # We can't ask it to display it cleanly, so print it
977 print STDERR
"To prevent you from losing history, non-fast-forward updates were rejected\n";
978 print STDERR
"Merge the remote changes (e.g. 'git pull') before pushing again. See the\n";
979 print STDERR
"'Note about fast-forwards' section of 'git push --help' for details.\n";
981 print STDOUT
"error $_[0] \"non-fast-forward\"\n";
986 my $complete_file_name = shift;
987 my $new_sha1 = shift;
988 my $extension = shift;
989 my $file_deleted = shift;
992 my $path = "File:" . $complete_file_name;
993 my %hashFiles = get_allowed_file_extensions
();
994 if (!exists($hashFiles{$extension})) {
995 print STDERR
"$complete_file_name is not a permitted file on this wiki.\n";
996 print STDERR
"Check the configuration of file uploads in your mediawiki.\n";
999 # Deleting and uploading a file requires a priviledged user
1000 if ($file_deleted) {
1007 if (!$mediawiki->edit($query)) {
1008 print STDERR
"Failed to delete file on remote wiki\n";
1009 print STDERR
"Check your permissions on the remote site. Error code:\n";
1010 print STDERR
$mediawiki->{error
}->{code
} . ':' . $mediawiki->{error
}->{details
};
1014 # Don't let perl try to interpret file content as UTF-8 => use "raw"
1015 my $content = run_git
("cat-file blob $new_sha1", "raw");
1016 if ($content ne "") {
1018 $mediawiki->{config
}->{upload_url
} =
1019 "$url/index.php/Special:Upload";
1022 filename
=> $complete_file_name,
1023 comment
=> $summary,
1025 $complete_file_name,
1026 Content
=> $content],
1027 ignorewarnings
=> 1,
1030 } ) || die $mediawiki->{error
}->{code
} . ':'
1031 . $mediawiki->{error
}->{details
};
1032 my $last_file_page = $mediawiki->get_page({title
=> $path});
1033 $newrevid = $last_file_page->{revid
};
1034 print STDERR
"Pushed file: $new_sha1 - $complete_file_name.\n";
1036 print STDERR
"Empty file $complete_file_name not pushed.\n";
1043 my $diff_info = shift;
1044 # $diff_info contains a string in this format:
1045 # 100644 100644 <sha1_of_blob_before_commit> <sha1_of_blob_now> <status>
1046 my @diff_info_split = split(/[ \t]/, $diff_info);
1048 # Filename, including .mw extension
1049 my $complete_file_name = shift;
1051 my $summary = shift;
1052 # MediaWiki revision number. Keep the previous one by default,
1053 # in case there's no edit to perform.
1054 my $oldrevid = shift;
1057 if ($summary eq EMPTY_MESSAGE
) {
1061 my $new_sha1 = $diff_info_split[3];
1062 my $old_sha1 = $diff_info_split[2];
1063 my $page_created = ($old_sha1 eq NULL_SHA1
);
1064 my $page_deleted = ($new_sha1 eq NULL_SHA1
);
1065 $complete_file_name = mediawiki_clean_filename
($complete_file_name);
1067 my ($title, $extension) = $complete_file_name =~ /^(.*)\.([^\.]*)$/;
1068 if (!defined($extension)) {
1071 if ($extension eq "mw") {
1072 my $ns = get_mw_namespace_id_for_page
($complete_file_name);
1073 if ($ns && $ns == get_mw_namespace_id
("File") && (!$export_media)) {
1074 print STDERR
"Ignoring media file related page: $complete_file_name\n";
1075 return ($oldrevid, "ok");
1078 if ($page_deleted) {
1079 # Deleting a page usually requires
1080 # special privileges. A common
1081 # convention is to replace the page
1082 # with this content instead:
1083 $file_content = DELETED_CONTENT
;
1085 $file_content = run_git
("cat-file blob $new_sha1");
1090 my $result = $mediawiki->edit( {
1092 summary
=> $summary,
1094 basetimestamp
=> $basetimestamps{$oldrevid},
1095 text
=> mediawiki_clean
($file_content, $page_created),
1097 skip_encoding
=> 1 # Helps with names with accentuated characters
1100 if ($mediawiki->{error
}->{code
} == 3) {
1101 # edit conflicts, considered as non-fast-forward
1102 print STDERR
'Warning: Error ' .
1103 $mediawiki->{error
}->{code
} .
1104 ' from mediwiki: ' . $mediawiki->{error
}->{details
} .
1106 return ($oldrevid, "non-fast-forward");
1108 # Other errors. Shouldn't happen => just die()
1109 die 'Fatal: Error ' .
1110 $mediawiki->{error
}->{code
} .
1111 ' from mediwiki: ' . $mediawiki->{error
}->{details
};
1114 $newrevid = $result->{edit
}->{newrevid
};
1115 print STDERR
"Pushed file: $new_sha1 - $title\n";
1116 } elsif ($export_media) {
1117 $newrevid = mw_upload_file
($complete_file_name, $new_sha1,
1118 $extension, $page_deleted,
1121 print STDERR
"Ignoring media file $title\n";
1123 $newrevid = ($newrevid or $oldrevid);
1124 return ($newrevid, "ok");
1128 # multiple push statements can follow each other
1129 my @refsspecs = (shift, get_more_refs
("push"));
1131 for my $refspec (@refsspecs) {
1132 my ($force, $local, $remote) = $refspec =~ /^(\+)?([^:]*):([^:]*)$/
1133 or die("Invalid refspec for push. Expected <src>:<dst> or +<src>:<dst>");
1135 print STDERR
"Warning: forced push not allowed on a MediaWiki.\n";
1138 print STDERR
"Cannot delete remote branch on a MediaWiki\n";
1139 print STDOUT
"error $remote cannot delete\n";
1142 if ($remote ne "refs/heads/master") {
1143 print STDERR
"Only push to the branch 'master' is supported on a MediaWiki\n";
1144 print STDOUT
"error $remote only master allowed\n";
1147 if (mw_push_revision
($local, $remote)) {
1152 # Notify Git that the push is done
1155 if ($pushed && $dumb_push) {
1156 print STDERR
"Just pushed some revisions to MediaWiki.\n";
1157 print STDERR
"The pushed revisions now have to be re-imported, and your current branch\n";
1158 print STDERR
"needs to be updated with these re-imported commits. You can do this with\n";
1160 print STDERR
" git pull --rebase\n";
1165 sub mw_push_revision
{
1167 my $remote = shift; # actually, this has to be "refs/heads/master" at this point.
1168 my $last_local_revid = get_last_local_revision
();
1169 print STDERR
".\n"; # Finish sentence started by get_last_local_revision()
1170 my $last_remote_revid = get_last_remote_revision
();
1171 my $mw_revision = $last_remote_revid;
1173 # Get sha1 of commit pointed by local HEAD
1174 my $HEAD_sha1 = run_git
("rev-parse $local 2>/dev/null"); chomp($HEAD_sha1);
1175 # Get sha1 of commit pointed by remotes/$remotename/master
1176 my $remoteorigin_sha1 = run_git
("rev-parse refs/remotes/$remotename/master 2>/dev/null");
1177 chomp($remoteorigin_sha1);
1179 if ($last_local_revid > 0 &&
1180 $last_local_revid < $last_remote_revid) {
1181 return error_non_fast_forward
($remote);
1184 if ($HEAD_sha1 eq $remoteorigin_sha1) {
1189 # Get every commit in between HEAD and refs/remotes/origin/master,
1190 # including HEAD and refs/remotes/origin/master
1191 my @commit_pairs = ();
1192 if ($last_local_revid > 0) {
1193 my $parsed_sha1 = $remoteorigin_sha1;
1194 # Find a path from last MediaWiki commit to pushed commit
1195 print STDERR
"Computing path from local to remote ...\n";
1196 my @local_ancestry = split(/\n/, run_git
("rev-list --boundary --parents $local ^$parsed_sha1"));
1198 foreach my $line (@local_ancestry) {
1199 if (my ($child, $parents) = $line =~ m/^-?([a-f0-9]+) ([a-f0-9 ]+)/) {
1200 foreach my $parent (split(' ', $parents)) {
1201 $local_ancestry{$parent} = $child;
1203 } elsif (!$line =~ m/^([a-f0-9]+)/) {
1204 die "Unexpected output from git rev-list: $line";
1207 while ($parsed_sha1 ne $HEAD_sha1) {
1208 my $child = $local_ancestry{$parsed_sha1};
1210 printf STDERR
"Cannot find a path in history from remote commit to last commit\n";
1211 return error_non_fast_forward
($remote);
1213 push(@commit_pairs, [$parsed_sha1, $child]);
1214 $parsed_sha1 = $child;
1217 # No remote mediawiki revision. Export the whole
1218 # history (linearized with --first-parent)
1219 print STDERR
"Warning: no common ancestor, pushing complete history\n";
1220 my $history = run_git
("rev-list --first-parent --children $local");
1221 my @history = split('\n', $history);
1222 @history = @history[1..$#history];
1223 foreach my $line (reverse @history) {
1224 my @commit_info_split = split(/ |\n/, $line);
1225 push(@commit_pairs, \
@commit_info_split);
1229 foreach my $commit_info_split (@commit_pairs) {
1230 my $sha1_child = @
{$commit_info_split}[0];
1231 my $sha1_commit = @
{$commit_info_split}[1];
1232 my $diff_infos = run_git
("diff-tree -r --raw -z $sha1_child $sha1_commit");
1233 # TODO: we could detect rename, and encode them with a #redirect on the wiki.
1234 # TODO: for now, it's just a delete+add
1235 my @diff_info_list = split(/\0/, $diff_infos);
1236 # Keep the subject line of the commit message as mediawiki comment for the revision
1237 my $commit_msg = run_git
("log --no-walk --format=\"%s\" $sha1_commit");
1240 while (@diff_info_list) {
1242 # git diff-tree -z gives an output like
1243 # <metadata>\0<filename1>\0
1244 # <metadata>\0<filename2>\0
1245 # and we've split on \0.
1246 my $info = shift(@diff_info_list);
1247 my $file = shift(@diff_info_list);
1248 ($mw_revision, $status) = mw_push_file
($info, $file, $commit_msg, $mw_revision);
1249 if ($status eq "non-fast-forward") {
1250 # we may already have sent part of the
1251 # commit to MediaWiki, but it's too
1252 # late to cancel it. Stop the push in
1253 # the middle, but still give an
1254 # accurate error message.
1255 return error_non_fast_forward
($remote);
1257 if ($status ne "ok") {
1258 die("Unknown error from mw_push_file()");
1261 unless ($dumb_push) {
1262 run_git
("notes --ref=$remotename/mediawiki add -f -m \"mediawiki_revision: $mw_revision\" $sha1_commit");
1263 run_git
("update-ref -m \"Git-MediaWiki push\" refs/mediawiki/$remotename/master $sha1_commit $sha1_child");
1267 print STDOUT
"ok $remote\n";
1271 sub get_allowed_file_extensions
{
1277 siprop
=> 'fileextensions'
1279 my $result = $mediawiki->api($query);
1280 my @file_extensions= map $_->{ext
},@
{$result->{query
}->{fileextensions
}};
1281 my %hashFile = map {$_ => 1}@file_extensions;
1286 # In memory cache for MediaWiki namespace ids.
1289 # Namespaces whose id is cached in the configuration file
1290 # (to avoid duplicates)
1291 my %cached_mw_namespace_id;
1293 # Return MediaWiki id for a canonical namespace name.
1294 # Ex.: "File", "Project".
1295 sub get_mw_namespace_id
{
1299 if (!exists $namespace_id{$name}) {
1300 # Look at configuration file, if the record for that namespace is
1301 # already cached. Namespaces are stored in form:
1302 # "Name_of_namespace:Id_namespace", ex.: "File:6".
1303 my @temp = split(/[\n]/, run_git
("config --get-all remote."
1304 . $remotename .".namespaceCache"));
1306 foreach my $ns (@temp) {
1307 my ($n, $id) = split(/:/, $ns);
1308 if ($id eq 'notANameSpace') {
1309 $namespace_id{$n} = {is_namespace
=> 0};
1311 $namespace_id{$n} = {is_namespace
=> 1, id
=> $id};
1313 $cached_mw_namespace_id{$n} = 1;
1317 if (!exists $namespace_id{$name}) {
1318 print STDERR
"Namespace $name not found in cache, querying the wiki ...\n";
1319 # NS not found => get namespace id from MW and store it in
1320 # configuration file.
1324 siprop
=> 'namespaces'
1326 my $result = $mediawiki->api($query);
1328 while (my ($id, $ns) = each(%{$result->{query
}->{namespaces
}})) {
1329 if (defined($ns->{id
}) && defined($ns->{canonical
})) {
1330 $namespace_id{$ns->{canonical
}} = {is_namespace
=> 1, id
=> $ns->{id
}};
1332 # alias (e.g. french Fichier: as alias for canonical File:)
1333 $namespace_id{$ns->{'*'}} = {is_namespace
=> 1, id
=> $ns->{id
}};
1339 my $ns = $namespace_id{$name};
1342 unless (defined $ns) {
1343 print STDERR
"No such namespace $name on MediaWiki.\n";
1344 $ns = {is_namespace
=> 0};
1345 $namespace_id{$name} = $ns;
1348 if ($ns->{is_namespace
}) {
1352 # Store "notANameSpace" as special value for inexisting namespaces
1353 my $store_id = ($id || 'notANameSpace');
1355 # Store explicitely requested namespaces on disk
1356 if (!exists $cached_mw_namespace_id{$name}) {
1357 run_git
("config --add remote.". $remotename
1358 .".namespaceCache \"". $name .":". $store_id ."\"");
1359 $cached_mw_namespace_id{$name} = 1;
1364 sub get_mw_namespace_id_for_page
{
1365 if (my ($namespace) = $_[0] =~ /^([^:]*):/) {
1366 return get_mw_namespace_id
($namespace);