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/
17 use DateTime
::Format
::ISO8601
;
20 # By default, use UTF-8 to communicate with Git and the user
21 binmode STDERR
, ":encoding(UTF-8)";
22 binmode STDOUT
, ":encoding(UTF-8)";
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 # Remember the timestamp corresponding to a revision id.
97 # Dumb push: don't update notes and mediawiki ref to reflect the last push.
99 # Configurable with mediawiki.dumbPush, or per-remote with
100 # remote.<remotename>.dumbPush.
102 # This means the user will have to re-import the just-pushed
103 # revisions. On the other hand, this means that the Git revisions
104 # corresponding to MediaWiki revisions are all imported from the wiki,
105 # regardless of whether they were initially created in Git or from the
106 # web interface, hence all users will get the same history (i.e. if
107 # the push from Git to MediaWiki loses some information, everybody
108 # will get the history with information lost). If the import is
109 # deterministic, this means everybody gets the same sha1 for each
110 # MediaWiki revision.
111 my $dumb_push = run_git
("config --get --bool remote.$remotename.dumbPush");
112 unless ($dumb_push) {
113 $dumb_push = run_git
("config --get --bool mediawiki.dumbPush");
116 $dumb_push = ($dumb_push eq "true");
118 my $wiki_name = $url;
119 $wiki_name =~ s{[^/]*://}{};
120 # If URL is like http://user:password@example.com/, we clearly don't
121 # want the password in $wiki_name. While we're there, also remove user
122 # and '@' sign, to avoid author like MWUser@HTTPUser@host.com
123 $wiki_name =~ s/^.*@//;
130 if (defined($cmd[0])) {
132 if ($cmd[0] eq "capabilities") {
133 die("Too many arguments for capabilities\n") if (defined($cmd[1]));
135 } elsif ($cmd[0] eq "list") {
136 die("Too many arguments for list\n") if (defined($cmd[2]));
138 } elsif ($cmd[0] eq "import") {
139 die("Invalid arguments for import\n") if ($cmd[1] eq "" || defined($cmd[2]));
141 } elsif ($cmd[0] eq "option") {
142 die("Too many arguments for option\n") if ($cmd[1] eq "" || $cmd[2] eq "" || defined($cmd[3]));
143 mw_option
($cmd[1],$cmd[2]);
144 } elsif ($cmd[0] eq "push") {
147 print STDERR
"Unknown command. Aborting...\n";
151 # blank line: we should terminate
155 BEGIN { $| = 1 } # flush STDOUT, to make sure the previous
156 # command is fully processed.
159 ########################## Functions ##############################
161 # MediaWiki API instance, created lazily.
164 sub mw_connect_maybe
{
168 $mediawiki = MediaWiki
::API
->new;
169 $mediawiki->{config
}->{api_url
} = "$url/api.php";
173 'username' => $wiki_login,
174 'password' => $wiki_passwd
176 Git
::credential
(\
%credential);
177 my $request = {lgname
=> $credential{username
},
178 lgpassword
=> $credential{password
},
179 lgdomain
=> $wiki_domain};
180 if ($mediawiki->login($request)) {
181 Git
::credential
(\
%credential, 'approve');
182 print STDERR
"Logged in mediawiki user \"$credential{username}\".\n";
184 print STDERR
"Failed to log in mediawiki user \"$credential{username}\" on $url\n";
185 print STDERR
" (error " .
186 $mediawiki->{error
}->{code
} . ': ' .
187 $mediawiki->{error
}->{details
} . ")\n";
188 Git
::credential
(\
%credential, 'reject');
197 print STDERR
"fatal: could not $action.\n";
198 print STDERR
"fatal: '$url' does not appear to be a mediawiki\n";
199 if ($url =~ /^https/) {
200 print STDERR
"fatal: make sure '$url/api.php' is a valid page\n";
201 print STDERR
"fatal: and the SSL certificate is correct.\n";
203 print STDERR
"fatal: make sure '$url/api.php' is a valid page.\n";
205 print STDERR
"fatal: (error " .
206 $mediawiki->{error
}->{code
} . ': ' .
207 $mediawiki->{error
}->{details
} . ")\n";
211 ## Functions for listing pages on the remote wiki
212 sub get_mw_tracked_pages
{
214 get_mw_page_list
(\
@tracked_pages, $pages);
218 sub get_mw_page_list
{
219 my $page_list = shift;
221 my @some_pages = @
$page_list;
222 while (@some_pages) {
224 if ($#some_pages < $last) {
225 $last = $#some_pages;
227 my @slice = @some_pages[0..$last];
228 get_mw_first_pages
(\
@slice, $pages);
229 @some_pages = @some_pages[51..$#some_pages];
234 sub get_mw_tracked_categories
{
236 foreach my $category (@tracked_categories) {
237 if (index($category, ':') < 0) {
238 # Mediawiki requires the Category
239 # prefix, but let's not force the user
241 $category = "Category:" . $category;
243 my $mw_pages = $mediawiki->list( {
245 list
=> 'categorymembers',
246 cmtitle
=> $category,
248 || die $mediawiki->{error
}->{code
} . ': '
249 . $mediawiki->{error
}->{details
} . "\n";
250 foreach my $page (@
{$mw_pages}) {
251 $pages->{$page->{title
}} = $page;
257 sub get_mw_all_pages
{
259 # No user-provided list, get the list of pages from the API.
260 my $mw_pages = $mediawiki->list({
265 if (!defined($mw_pages)) {
266 fatal_mw_error
("get the list of wiki pages");
268 foreach my $page (@
{$mw_pages}) {
269 $pages->{$page->{title
}} = $page;
274 # queries the wiki for a set of pages. Meant to be used within a loop
275 # querying the wiki for slices of page list.
276 sub get_mw_first_pages
{
277 my $some_pages = shift;
278 my @some_pages = @
{$some_pages};
282 # pattern 'page1|page2|...' required by the API
283 my $titles = join('|', @some_pages);
285 my $mw_pages = $mediawiki->api({
289 if (!defined($mw_pages)) {
290 fatal_mw_error
("query the list of wiki pages");
292 while (my ($id, $page) = each(%{$mw_pages->{query
}->{pages
}})) {
294 print STDERR
"Warning: page $page->{title} not found on wiki\n";
296 $pages->{$page->{title
}} = $page;
302 # Get the list of pages to be fetched according to configuration.
306 print STDERR
"Listing pages on remote wiki...\n";
308 my %pages; # hash on page titles to avoid duplicates
310 if (@tracked_pages) {
312 # The user provided a list of pages titles, but we
313 # still need to query the API to get the page IDs.
314 get_mw_tracked_pages
(\
%pages);
316 if (@tracked_categories) {
318 get_mw_tracked_categories
(\
%pages);
320 if (!$user_defined) {
321 get_mw_all_pages
(\
%pages);
324 print STDERR
"Getting media files for selected pages...\n";
326 get_linked_mediafiles
(\
%pages);
328 get_all_mediafiles
(\
%pages);
331 print STDERR
(scalar keys %pages) . " pages found.\n";
335 # usage: $out = run_git("command args");
336 # $out = run_git("command args", "raw"); # don't interpret output as UTF-8.
339 my $encoding = (shift || "encoding(UTF-8)");
340 open(my $git, "-|:$encoding", "git " . $args);
341 my $res = do { local $/; <$git> };
348 sub get_all_mediafiles
{
350 # Attach list of all pages for media files from the API,
351 # they are in a different namespace, only one namespace
352 # can be queried at the same moment
353 my $mw_pages = $mediawiki->list({
356 apnamespace
=> get_mw_namespace_id
("File"),
359 if (!defined($mw_pages)) {
360 print STDERR
"fatal: could not get the list of pages for media files.\n";
361 print STDERR
"fatal: '$url' does not appear to be a mediawiki\n";
362 print STDERR
"fatal: make sure '$url/api.php' is a valid page.\n";
365 foreach my $page (@
{$mw_pages}) {
366 $pages->{$page->{title
}} = $page;
371 sub get_linked_mediafiles
{
373 my @titles = map { $_->{title
} } values(%{$pages});
375 # The query is split in small batches because of the MW API limit of
376 # the number of links to be returned (500 links max).
379 if ($#titles < $batch) {
382 my @slice = @titles[0..$batch];
384 # pattern 'page1|page2|...' required by the API
385 my $mw_titles = join('|', @slice);
387 # Media files could be included or linked from
388 # a page, get all related
391 prop
=> 'links|images',
392 titles
=> $mw_titles,
393 plnamespace
=> get_mw_namespace_id
("File"),
396 my $result = $mediawiki->api($query);
398 while (my ($id, $page) = each(%{$result->{query
}->{pages
}})) {
400 if (defined($page->{links
})) {
402 = map { $_->{title
} } @
{$page->{links
}};
403 push(@media_titles, @link_titles);
405 if (defined($page->{images
})) {
407 = map { $_->{title
} } @
{$page->{images
}};
408 push(@media_titles, @image_titles);
411 get_mw_page_list
(\
@media_titles, $pages);
415 @titles = @titles[($batch+1)..$#titles];
420 sub get_mw_mediafile_for_page_revision
{
421 # Name of the file on Wiki, with the prefix.
422 my $filename = shift;
423 my $timestamp = shift;
426 # Search if on a media file with given timestamp exists on
427 # MediaWiki. In that case download the file.
431 titles
=> "File:" . $filename,
432 iistart
=> $timestamp,
434 iiprop
=> 'timestamp|archivename|url',
437 my $result = $mediawiki->api($query);
439 my ($fileid, $file) = each( %{$result->{query
}->{pages
}} );
440 # If not defined it means there is no revision of the file for
442 if (defined($file->{imageinfo
})) {
443 $mediafile{title
} = $filename;
445 my $fileinfo = pop(@
{$file->{imageinfo
}});
446 $mediafile{timestamp
} = $fileinfo->{timestamp
};
447 # Mediawiki::API's download function doesn't support https URLs
448 # and can't download old versions of files.
449 print STDERR
"\tDownloading file $mediafile{title}, version $mediafile{timestamp}\n";
450 $mediafile{content
} = download_mw_mediafile
($fileinfo->{url
});
455 sub download_mw_mediafile
{
456 my $download_url = shift;
458 my $response = $mediawiki->{ua
}->get($download_url);
459 if ($response->code == 200) {
460 return $response->decoded_content;
462 print STDERR
"Error downloading mediafile from :\n";
463 print STDERR
"URL: $download_url\n";
464 print STDERR
"Server response: " . $response->code . " " . $response->message . "\n";
469 sub get_last_local_revision
{
470 # Get note regarding last mediawiki revision
471 my $note = run_git
("notes --ref=$remotename/mediawiki show refs/mediawiki/$remotename/master 2>/dev/null");
472 my @note_info = split(/ /, $note);
474 my $lastrevision_number;
475 if (!(defined($note_info[0]) && $note_info[0] eq "mediawiki_revision:")) {
476 print STDERR
"No previous mediawiki revision found";
477 $lastrevision_number = 0;
479 # Notes are formatted : mediawiki_revision: #number
480 $lastrevision_number = $note_info[1];
481 chomp($lastrevision_number);
482 print STDERR
"Last local mediawiki revision found is $lastrevision_number";
484 return $lastrevision_number;
487 # Get the last remote revision without taking in account which pages are
488 # tracked or not. This function makes a single request to the wiki thus
489 # avoid a loop onto all tracked pages. This is useful for the fetch-by-rev
491 sub get_last_global_remote_rev
{
496 list
=> 'recentchanges',
501 my $result = $mediawiki->api($query);
502 return $result->{query
}->{recentchanges
}[0]->{revid
};
505 # Get the last remote revision concerning the tracked pages and the tracked
507 sub get_last_remote_revision
{
510 my %pages_hash = get_mw_pages
();
511 my @pages = values(%pages_hash);
515 print STDERR
"Getting last revision id on tracked pages...\n";
517 foreach my $page (@pages) {
518 my $id = $page->{pageid
};
523 rvprop
=> 'ids|timestamp',
527 my $result = $mediawiki->api($query);
529 my $lastrev = pop(@
{$result->{query
}->{pages
}->{$id}->{revisions
}});
531 $basetimestamps{$lastrev->{revid
}} = $lastrev->{timestamp
};
533 $max_rev_num = ($lastrev->{revid
} > $max_rev_num ?
$lastrev->{revid
} : $max_rev_num);
536 print STDERR
"Last remote revision found is $max_rev_num.\n";
540 # Clean content before sending it to MediaWiki
541 sub mediawiki_clean
{
543 my $page_created = shift;
544 # Mediawiki does not allow blank space at the end of a page and ends with a single \n.
545 # This function right trims a string and adds a \n at the end to follow this rule
547 if ($string eq "" && $page_created) {
548 # Creating empty pages is forbidden.
549 $string = EMPTY_CONTENT
;
554 # Filter applied on MediaWiki data before adding them to Git
555 sub mediawiki_smudge
{
557 if ($string eq EMPTY_CONTENT
) {
560 # This \n is important. This is due to mediawiki's way to handle end of files.
564 sub mediawiki_clean_filename
{
565 my $filename = shift;
566 $filename =~ s{@{[SLASH_REPLACEMENT]}}{/}g;
567 # [, ], |, {, and } are forbidden by MediaWiki, even URL-encoded.
568 # Do a variant of URL-encoding, i.e. looks like URL-encoding,
569 # but with _ added to prevent MediaWiki from thinking this is
570 # an actual special character.
571 $filename =~ s/[\[\]\{\}\|]/sprintf("_%%_%x", ord($&))/ge;
572 # If we use the uri escape before
573 # we should unescape here, before anything
578 sub mediawiki_smudge_filename
{
579 my $filename = shift;
580 $filename =~ s{/}{@{[SLASH_REPLACEMENT]}}g
;
581 $filename =~ s/ /_/g;
582 # Decode forbidden characters encoded in mediawiki_clean_filename
583 $filename =~ s/_%_([0-9a-fA-F][0-9a-fA-F])/sprintf("%c", hex($1))/ge;
589 print STDOUT
"data ", bytes
::length($content), "\n", $content;
593 sub literal_data_raw
{
594 # Output possibly binary content.
596 # Avoid confusion between size in bytes and in characters
597 utf8
::downgrade
($content);
598 binmode STDOUT
, ":raw";
599 print STDOUT
"data ", bytes
::length($content), "\n", $content;
600 binmode STDOUT
, ":encoding(UTF-8)";
604 sub mw_capabilities
{
605 # Revisions are imported to the private namespace
606 # refs/mediawiki/$remotename/ by the helper and fetched into
607 # refs/remotes/$remotename later by fetch.
608 print STDOUT
"refspec refs/heads/*:refs/mediawiki/$remotename/*\n";
609 print STDOUT
"import\n";
610 print STDOUT
"list\n";
611 print STDOUT
"push\n";
617 # MediaWiki do not have branches, we consider one branch arbitrarily
618 # called master, and HEAD pointing to it.
619 print STDOUT
"? refs/heads/master\n";
620 print STDOUT
"\@refs/heads/master HEAD\n";
626 print STDERR
"remote-helper command 'option $_[0]' not yet implemented\n";
627 print STDOUT
"unsupported\n";
631 sub fetch_mw_revisions_for_page
{
634 my $fetch_from = shift;
641 rvstartid
=> $fetch_from,
647 # Get 500 revisions at a time due to the mediawiki api limit
649 my $result = $mediawiki->api($query);
651 # Parse each of those 500 revisions
652 foreach my $revision (@
{$result->{query
}->{pages
}->{$id}->{revisions
}}) {
654 $page_rev_ids->{pageid
} = $page->{pageid
};
655 $page_rev_ids->{revid
} = $revision->{revid
};
656 push(@page_revs, $page_rev_ids);
659 last unless $result->{'query-continue'};
660 $query->{rvstartid
} = $result->{'query-continue'}->{revisions
}->{rvstartid
};
662 if ($shallow_import && @page_revs) {
663 print STDERR
" Found 1 revision (shallow import).\n";
664 @page_revs = sort {$b->{revid
} <=> $a->{revid
}} (@page_revs);
665 return $page_revs[0];
667 print STDERR
" Found ", $revnum, " revision(s).\n";
671 sub fetch_mw_revisions
{
672 my $pages = shift; my @pages = @
{$pages};
673 my $fetch_from = shift;
677 foreach my $page (@pages) {
678 my $id = $page->{pageid
};
680 print STDERR
"page $n/", scalar(@pages), ": ". $page->{title
} ."\n";
682 my @page_revs = fetch_mw_revisions_for_page
($page, $id, $fetch_from);
683 @revisions = (@page_revs, @revisions);
686 return ($n, @revisions);
691 $path =~ s/\\/\\\\/g;
694 return '"' . $path . '"';
697 sub import_file_revision
{
699 my %commit = %{$commit};
700 my $full_import = shift;
702 my $mediafile = shift;
705 %mediafile = %{$mediafile};
708 my $title = $commit{title
};
709 my $comment = $commit{comment
};
710 my $content = $commit{content
};
711 my $author = $commit{author
};
712 my $date = $commit{date
};
714 print STDOUT
"commit refs/mediawiki/$remotename/master\n";
715 print STDOUT
"mark :$n\n";
716 print STDOUT
"committer $author <$author\@$wiki_name> ", $date->epoch, " +0000\n";
717 literal_data
($comment);
719 # If it's not a clone, we need to know where to start from
720 if (!$full_import && $n == 1) {
721 print STDOUT
"from refs/mediawiki/$remotename/master^0\n";
723 if ($content ne DELETED_CONTENT
) {
724 print STDOUT
"M 644 inline " .
725 fe_escape_path
($title . ".mw") . "\n";
726 literal_data
($content);
728 print STDOUT
"M 644 inline "
729 . fe_escape_path
($mediafile{title
}) . "\n";
730 literal_data_raw
($mediafile{content
});
734 print STDOUT
"D " . fe_escape_path
($title . ".mw") . "\n";
737 # mediawiki revision number in the git note
738 if ($full_import && $n == 1) {
739 print STDOUT
"reset refs/notes/$remotename/mediawiki\n";
741 print STDOUT
"commit refs/notes/$remotename/mediawiki\n";
742 print STDOUT
"committer $author <$author\@$wiki_name> ", $date->epoch, " +0000\n";
743 literal_data
("Note added by git-mediawiki during import");
744 if (!$full_import && $n == 1) {
745 print STDOUT
"from refs/notes/$remotename/mediawiki^0\n";
747 print STDOUT
"N inline :$n\n";
748 literal_data
("mediawiki_revision: " . $commit{mw_revision
});
753 # parse a sequence of
757 # (like batch sequence of import and sequence of push statements)
763 if ($line =~ /^$cmd (.*)$/) {
765 } elsif ($line eq "\n") {
768 die("Invalid command in a '$cmd' batch: $_\n");
775 # multiple import commands can follow each other.
776 my @refs = (shift, get_more_refs
("import"));
777 foreach my $ref (@refs) {
780 print STDOUT
"done\n";
786 # The remote helper will call "import HEAD" and
787 # "import refs/heads/master".
788 # Since HEAD is a symbolic ref to master (by convention,
789 # followed by the output of the command "list" that we gave),
790 # we don't need to do anything in this case.
791 if ($ref eq "HEAD") {
797 print STDERR
"Searching revisions...\n";
798 my $last_local = get_last_local_revision
();
799 my $fetch_from = $last_local + 1;
800 if ($fetch_from == 1) {
801 print STDERR
", fetching from beginning.\n";
803 print STDERR
", fetching from here.\n";
807 if ($fetch_strategy eq "by_rev") {
808 print STDERR
"Fetching & writing export data by revs...\n";
809 $n = mw_import_ref_by_revs
($fetch_from);
810 } elsif ($fetch_strategy eq "by_page") {
811 print STDERR
"Fetching & writing export data by pages...\n";
812 $n = mw_import_ref_by_pages
($fetch_from);
814 print STDERR
"fatal: invalid fetch strategy \"$fetch_strategy\".\n";
815 print STDERR
"Check your configuration variables remote.$remotename.fetchStrategy and mediawiki.fetchStrategy\n";
819 if ($fetch_from == 1 && $n == 0) {
820 print STDERR
"You appear to have cloned an empty MediaWiki.\n";
821 # Something has to be done remote-helper side. If nothing is done, an error is
822 # thrown saying that HEAD is referring to unknown object 0000000000000000000
823 # and the clone fails.
828 sub mw_import_ref_by_pages
{
830 my $fetch_from = shift;
831 my %pages_hash = get_mw_pages
();
832 my @pages = values(%pages_hash);
834 my ($n, @revisions) = fetch_mw_revisions
(\
@pages, $fetch_from);
836 @revisions = sort {$a->{revid
} <=> $b->{revid
}} @revisions;
837 my @revision_ids = map { $_->{revid
} } @revisions;
839 return mw_import_revids
($fetch_from, \
@revision_ids, \
%pages_hash);
842 sub mw_import_ref_by_revs
{
844 my $fetch_from = shift;
845 my %pages_hash = get_mw_pages
();
847 my $last_remote = get_last_global_remote_rev
();
848 my @revision_ids = $fetch_from..$last_remote;
849 return mw_import_revids
($fetch_from, \
@revision_ids, \
%pages_hash);
852 # Import revisions given in second argument (array of integers).
853 # Only pages appearing in the third argument (hash indexed by page titles)
855 sub mw_import_revids
{
856 my $fetch_from = shift;
857 my $revision_ids = shift;
862 my $last_timestamp = 0; # Placeholer in case $rev->timestamp is undefined
864 foreach my $pagerevid (@
$revision_ids) {
865 # Count page even if we skip it, since we display
866 # $n/$total and $total includes skipped pages.
869 # fetch the content of the pages
873 rvprop
=> 'content|timestamp|comment|user|ids',
874 revids
=> $pagerevid,
877 my $result = $mediawiki->api($query);
880 die "Failed to retrieve modified page for revision $pagerevid\n";
883 if (defined($result->{query
}->{badrevids
}->{$pagerevid})) {
884 # The revision id does not exist on the remote wiki.
888 if (!defined($result->{query
}->{pages
})) {
889 die "Invalid revision $pagerevid.\n";
892 my @result_pages = values(%{$result->{query
}->{pages
}});
893 my $result_page = $result_pages[0];
894 my $rev = $result_pages[0]->{revisions
}->[0];
896 my $page_title = $result_page->{title
};
898 if (!exists($pages->{$page_title})) {
899 print STDERR
"$n/", scalar(@
$revision_ids),
900 ": Skipping revision #$rev->{revid} of $page_title\n";
907 $commit{author
} = $rev->{user
} || 'Anonymous';
908 $commit{comment
} = $rev->{comment
} || EMPTY_MESSAGE
;
909 $commit{title
} = mediawiki_smudge_filename
($page_title);
910 $commit{mw_revision
} = $rev->{revid
};
911 $commit{content
} = mediawiki_smudge
($rev->{'*'});
913 if (!defined($rev->{timestamp
})) {
916 $last_timestamp = $rev->{timestamp
};
918 $commit{date
} = DateTime
::Format
::ISO8601
->parse_datetime($last_timestamp);
920 # Differentiates classic pages and media files.
921 my ($namespace, $filename) = $page_title =~ /^([^:]*):(.*)$/;
924 my $id = get_mw_namespace_id
($namespace);
925 if ($id && $id == get_mw_namespace_id
("File")) {
926 %mediafile = get_mw_mediafile_for_page_revision
($filename, $rev->{timestamp
});
929 # If this is a revision of the media page for new version
930 # of a file do one common commit for both file and media page.
931 # Else do commit only for that page.
932 print STDERR
"$n/", scalar(@
$revision_ids), ": Revision #$rev->{revid} of $commit{title}\n";
933 import_file_revision
(\
%commit, ($fetch_from == 1), $n_actual, \
%mediafile);
939 sub error_non_fast_forward
{
940 my $advice = run_git
("config --bool advice.pushNonFastForward");
942 if ($advice ne "false") {
943 # Native git-push would show this after the summary.
944 # We can't ask it to display it cleanly, so print it
946 print STDERR
"To prevent you from losing history, non-fast-forward updates were rejected\n";
947 print STDERR
"Merge the remote changes (e.g. 'git pull') before pushing again. See the\n";
948 print STDERR
"'Note about fast-forwards' section of 'git push --help' for details.\n";
950 print STDOUT
"error $_[0] \"non-fast-forward\"\n";
955 my $complete_file_name = shift;
956 my $new_sha1 = shift;
957 my $extension = shift;
958 my $file_deleted = shift;
961 my $path = "File:" . $complete_file_name;
962 my %hashFiles = get_allowed_file_extensions
();
963 if (!exists($hashFiles{$extension})) {
964 print STDERR
"$complete_file_name is not a permitted file on this wiki.\n";
965 print STDERR
"Check the configuration of file uploads in your mediawiki.\n";
968 # Deleting and uploading a file requires a priviledged user
976 if (!$mediawiki->edit($query)) {
977 print STDERR
"Failed to delete file on remote wiki\n";
978 print STDERR
"Check your permissions on the remote site. Error code:\n";
979 print STDERR
$mediawiki->{error
}->{code
} . ':' . $mediawiki->{error
}->{details
};
983 # Don't let perl try to interpret file content as UTF-8 => use "raw"
984 my $content = run_git
("cat-file blob $new_sha1", "raw");
985 if ($content ne "") {
987 $mediawiki->{config
}->{upload_url
} =
988 "$url/index.php/Special:Upload";
991 filename
=> $complete_file_name,
995 Content
=> $content],
999 } ) || die $mediawiki->{error
}->{code
} . ':'
1000 . $mediawiki->{error
}->{details
} . "\n";
1001 my $last_file_page = $mediawiki->get_page({title
=> $path});
1002 $newrevid = $last_file_page->{revid
};
1003 print STDERR
"Pushed file: $new_sha1 - $complete_file_name.\n";
1005 print STDERR
"Empty file $complete_file_name not pushed.\n";
1012 my $diff_info = shift;
1013 # $diff_info contains a string in this format:
1014 # 100644 100644 <sha1_of_blob_before_commit> <sha1_of_blob_now> <status>
1015 my @diff_info_split = split(/[ \t]/, $diff_info);
1017 # Filename, including .mw extension
1018 my $complete_file_name = shift;
1020 my $summary = shift;
1021 # MediaWiki revision number. Keep the previous one by default,
1022 # in case there's no edit to perform.
1023 my $oldrevid = shift;
1026 if ($summary eq EMPTY_MESSAGE
) {
1030 my $new_sha1 = $diff_info_split[3];
1031 my $old_sha1 = $diff_info_split[2];
1032 my $page_created = ($old_sha1 eq NULL_SHA1
);
1033 my $page_deleted = ($new_sha1 eq NULL_SHA1
);
1034 $complete_file_name = mediawiki_clean_filename
($complete_file_name);
1036 my ($title, $extension) = $complete_file_name =~ /^(.*)\.([^\.]*)$/;
1037 if (!defined($extension)) {
1040 if ($extension eq "mw") {
1041 my $ns = get_mw_namespace_id_for_page
($complete_file_name);
1042 if ($ns && $ns == get_mw_namespace_id
("File") && (!$export_media)) {
1043 print STDERR
"Ignoring media file related page: $complete_file_name\n";
1044 return ($oldrevid, "ok");
1047 if ($page_deleted) {
1048 # Deleting a page usually requires
1049 # special privileges. A common
1050 # convention is to replace the page
1051 # with this content instead:
1052 $file_content = DELETED_CONTENT
;
1054 $file_content = run_git
("cat-file blob $new_sha1");
1059 my $result = $mediawiki->edit( {
1061 summary
=> $summary,
1063 basetimestamp
=> $basetimestamps{$oldrevid},
1064 text
=> mediawiki_clean
($file_content, $page_created),
1066 skip_encoding
=> 1 # Helps with names with accentuated characters
1069 if ($mediawiki->{error
}->{code
} == 3) {
1070 # edit conflicts, considered as non-fast-forward
1071 print STDERR
'Warning: Error ' .
1072 $mediawiki->{error
}->{code
} .
1073 ' from mediwiki: ' . $mediawiki->{error
}->{details
} .
1075 return ($oldrevid, "non-fast-forward");
1077 # Other errors. Shouldn't happen => just die()
1078 die 'Fatal: Error ' .
1079 $mediawiki->{error
}->{code
} .
1080 ' from mediwiki: ' . $mediawiki->{error
}->{details
} . "\n";
1083 $newrevid = $result->{edit
}->{newrevid
};
1084 print STDERR
"Pushed file: $new_sha1 - $title\n";
1085 } elsif ($export_media) {
1086 $newrevid = mw_upload_file
($complete_file_name, $new_sha1,
1087 $extension, $page_deleted,
1090 print STDERR
"Ignoring media file $title\n";
1092 $newrevid = ($newrevid or $oldrevid);
1093 return ($newrevid, "ok");
1097 # multiple push statements can follow each other
1098 my @refsspecs = (shift, get_more_refs
("push"));
1100 for my $refspec (@refsspecs) {
1101 my ($force, $local, $remote) = $refspec =~ /^(\+)?([^:]*):([^:]*)$/
1102 or die("Invalid refspec for push. Expected <src>:<dst> or +<src>:<dst>\n");
1104 print STDERR
"Warning: forced push not allowed on a MediaWiki.\n";
1107 print STDERR
"Cannot delete remote branch on a MediaWiki\n";
1108 print STDOUT
"error $remote cannot delete\n";
1111 if ($remote ne "refs/heads/master") {
1112 print STDERR
"Only push to the branch 'master' is supported on a MediaWiki\n";
1113 print STDOUT
"error $remote only master allowed\n";
1116 if (mw_push_revision
($local, $remote)) {
1121 # Notify Git that the push is done
1124 if ($pushed && $dumb_push) {
1125 print STDERR
"Just pushed some revisions to MediaWiki.\n";
1126 print STDERR
"The pushed revisions now have to be re-imported, and your current branch\n";
1127 print STDERR
"needs to be updated with these re-imported commits. You can do this with\n";
1129 print STDERR
" git pull --rebase\n";
1135 sub mw_push_revision
{
1137 my $remote = shift; # actually, this has to be "refs/heads/master" at this point.
1138 my $last_local_revid = get_last_local_revision
();
1139 print STDERR
".\n"; # Finish sentence started by get_last_local_revision()
1140 my $last_remote_revid = get_last_remote_revision
();
1141 my $mw_revision = $last_remote_revid;
1143 # Get sha1 of commit pointed by local HEAD
1144 my $HEAD_sha1 = run_git
("rev-parse $local 2>/dev/null"); chomp($HEAD_sha1);
1145 # Get sha1 of commit pointed by remotes/$remotename/master
1146 my $remoteorigin_sha1 = run_git
("rev-parse refs/remotes/$remotename/master 2>/dev/null");
1147 chomp($remoteorigin_sha1);
1149 if ($last_local_revid > 0 &&
1150 $last_local_revid < $last_remote_revid) {
1151 return error_non_fast_forward
($remote);
1154 if ($HEAD_sha1 eq $remoteorigin_sha1) {
1159 # Get every commit in between HEAD and refs/remotes/origin/master,
1160 # including HEAD and refs/remotes/origin/master
1161 my @commit_pairs = ();
1162 if ($last_local_revid > 0) {
1163 my $parsed_sha1 = $remoteorigin_sha1;
1164 # Find a path from last MediaWiki commit to pushed commit
1165 print STDERR
"Computing path from local to remote ...\n";
1166 my @local_ancestry = split(/\n/, run_git
("rev-list --boundary --parents $local ^$parsed_sha1"));
1168 foreach my $line (@local_ancestry) {
1169 if (my ($child, $parents) = $line =~ /^-?([a-f0-9]+) ([a-f0-9 ]+)/) {
1170 foreach my $parent (split(/ /, $parents)) {
1171 $local_ancestry{$parent} = $child;
1173 } elsif (!$line =~ /^([a-f0-9]+)/) {
1174 die "Unexpected output from git rev-list: $line\n";
1177 while ($parsed_sha1 ne $HEAD_sha1) {
1178 my $child = $local_ancestry{$parsed_sha1};
1180 printf STDERR
"Cannot find a path in history from remote commit to last commit\n";
1181 return error_non_fast_forward
($remote);
1183 push(@commit_pairs, [$parsed_sha1, $child]);
1184 $parsed_sha1 = $child;
1187 # No remote mediawiki revision. Export the whole
1188 # history (linearized with --first-parent)
1189 print STDERR
"Warning: no common ancestor, pushing complete history\n";
1190 my $history = run_git
("rev-list --first-parent --children $local");
1191 my @history = split(/\n/, $history);
1192 @history = @history[1..$#history];
1193 foreach my $line (reverse @history) {
1194 my @commit_info_split = split(/[ \n]/, $line);
1195 push(@commit_pairs, \
@commit_info_split);
1199 foreach my $commit_info_split (@commit_pairs) {
1200 my $sha1_child = @
{$commit_info_split}[0];
1201 my $sha1_commit = @
{$commit_info_split}[1];
1202 my $diff_infos = run_git
("diff-tree -r --raw -z $sha1_child $sha1_commit");
1203 # TODO: we could detect rename, and encode them with a #redirect on the wiki.
1204 # TODO: for now, it's just a delete+add
1205 my @diff_info_list = split(/\0/, $diff_infos);
1206 # Keep the subject line of the commit message as mediawiki comment for the revision
1207 my $commit_msg = run_git
("log --no-walk --format=\"%s\" $sha1_commit");
1210 while (@diff_info_list) {
1212 # git diff-tree -z gives an output like
1213 # <metadata>\0<filename1>\0
1214 # <metadata>\0<filename2>\0
1215 # and we've split on \0.
1216 my $info = shift(@diff_info_list);
1217 my $file = shift(@diff_info_list);
1218 ($mw_revision, $status) = mw_push_file
($info, $file, $commit_msg, $mw_revision);
1219 if ($status eq "non-fast-forward") {
1220 # we may already have sent part of the
1221 # commit to MediaWiki, but it's too
1222 # late to cancel it. Stop the push in
1223 # the middle, but still give an
1224 # accurate error message.
1225 return error_non_fast_forward
($remote);
1227 if ($status ne "ok") {
1228 die("Unknown error from mw_push_file()\n");
1231 unless ($dumb_push) {
1232 run_git
("notes --ref=$remotename/mediawiki add -f -m \"mediawiki_revision: $mw_revision\" $sha1_commit");
1233 run_git
("update-ref -m \"Git-MediaWiki push\" refs/mediawiki/$remotename/master $sha1_commit $sha1_child");
1237 print STDOUT
"ok $remote\n";
1241 sub get_allowed_file_extensions
{
1247 siprop
=> 'fileextensions'
1249 my $result = $mediawiki->api($query);
1250 my @file_extensions = map { $_->{ext
}} @
{$result->{query
}->{fileextensions
}};
1251 my %hashFile = map { $_ => 1 } @file_extensions;
1256 # In memory cache for MediaWiki namespace ids.
1259 # Namespaces whose id is cached in the configuration file
1260 # (to avoid duplicates)
1261 my %cached_mw_namespace_id;
1263 # Return MediaWiki id for a canonical namespace name.
1264 # Ex.: "File", "Project".
1265 sub get_mw_namespace_id
{
1269 if (!exists $namespace_id{$name}) {
1270 # Look at configuration file, if the record for that namespace is
1271 # already cached. Namespaces are stored in form:
1272 # "Name_of_namespace:Id_namespace", ex.: "File:6".
1273 my @temp = split(/\n/, run_git
("config --get-all remote."
1274 . $remotename .".namespaceCache"));
1276 foreach my $ns (@temp) {
1277 my ($n, $id) = split(/:/, $ns);
1278 if ($id eq 'notANameSpace') {
1279 $namespace_id{$n} = {is_namespace
=> 0};
1281 $namespace_id{$n} = {is_namespace
=> 1, id
=> $id};
1283 $cached_mw_namespace_id{$n} = 1;
1287 if (!exists $namespace_id{$name}) {
1288 print STDERR
"Namespace $name not found in cache, querying the wiki ...\n";
1289 # NS not found => get namespace id from MW and store it in
1290 # configuration file.
1294 siprop
=> 'namespaces'
1296 my $result = $mediawiki->api($query);
1298 while (my ($id, $ns) = each(%{$result->{query
}->{namespaces
}})) {
1299 if (defined($ns->{id
}) && defined($ns->{canonical
})) {
1300 $namespace_id{$ns->{canonical
}} = {is_namespace
=> 1, id
=> $ns->{id
}};
1302 # alias (e.g. french Fichier: as alias for canonical File:)
1303 $namespace_id{$ns->{'*'}} = {is_namespace
=> 1, id
=> $ns->{id
}};
1309 my $ns = $namespace_id{$name};
1312 unless (defined $ns) {
1313 print STDERR
"No such namespace $name on MediaWiki.\n";
1314 $ns = {is_namespace
=> 0};
1315 $namespace_id{$name} = $ns;
1318 if ($ns->{is_namespace
}) {
1322 # Store "notANameSpace" as special value for inexisting namespaces
1323 my $store_id = ($id || 'notANameSpace');
1325 # Store explicitely requested namespaces on disk
1326 if (!exists $cached_mw_namespace_id{$name}) {
1327 run_git
("config --add remote.". $remotename
1328 .".namespaceCache \"". $name .":". $store_id ."\"");
1329 $cached_mw_namespace_id{$name} = 1;
1334 sub get_mw_namespace_id_for_page
{
1335 my $namespace = shift;
1336 if ($namespace =~ /^([^:]*):/) {
1337 return get_mw_namespace_id
($namespace);