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
;
19 # By default, use UTF-8 to communicate with Git and the user
20 binmode STDERR
, ":utf8";
21 binmode STDOUT
, ":utf8";
28 # Mediawiki filenames can contain forward slashes. This variable decides by which pattern they should be replaced
29 use constant SLASH_REPLACEMENT
=> "%2F";
31 # It's not always possible to delete pages (may require some
32 # privileges). Deleted pages are replaced with this content.
33 use constant DELETED_CONTENT
=> "[[Category:Deleted]]\n";
35 # It's not possible to create empty pages. New empty files in Git are
36 # sent with this content instead.
37 use constant EMPTY_CONTENT
=> "<!-- empty page -->\n";
39 # used to reflect file creation or deletion in diff.
40 use constant NULL_SHA1
=> "0000000000000000000000000000000000000000";
42 # Used on Git's side to reflect empty edit messages on the wiki
43 use constant EMPTY_MESSAGE
=> '*Empty MediaWiki Message*';
49 my $remotename = $ARGV[0];
52 # Accept both space-separated and multiple keys in config file.
53 # Spaces should be written as _ anyway because we'll use chomp.
54 my @tracked_pages = split(/[ \n]/, run_git
("config --get-all remote.". $remotename .".pages"));
55 chomp(@tracked_pages);
57 # Just like @tracked_pages, but for MediaWiki categories.
58 my @tracked_categories = split(/[ \n]/, run_git
("config --get-all remote.". $remotename .".categories"));
59 chomp(@tracked_categories);
61 # Import media files on pull
62 my $import_media = run_git
("config --get --bool remote.". $remotename .".mediaimport");
64 $import_media = ($import_media eq "true");
66 # Export media files on push
67 my $export_media = run_git
("config --get --bool remote.". $remotename .".mediaexport");
69 $export_media = !($export_media eq "false");
71 my $wiki_login = run_git
("config --get remote.". $remotename .".mwLogin");
72 # Note: mwPassword is discourraged. Use the credential system instead.
73 my $wiki_passwd = run_git
("config --get remote.". $remotename .".mwPassword");
74 my $wiki_domain = run_git
("config --get remote.". $remotename .".mwDomain");
79 # Import only last revisions (both for clone and fetch)
80 my $shallow_import = run_git
("config --get --bool remote.". $remotename .".shallow");
81 chomp($shallow_import);
82 $shallow_import = ($shallow_import eq "true");
84 # Fetch (clone and pull) by revisions instead of by pages. This behavior
85 # is more efficient when we have a wiki with lots of pages and we fetch
86 # the revisions quite often so that they concern only few pages.
88 # - by_rev: perform one query per new revision on the remote wiki
89 # - by_page: query each tracked page for new revision
90 my $fetch_strategy = run_git
("config --get remote.$remotename.fetchStrategy");
91 unless ($fetch_strategy) {
92 $fetch_strategy = run_git
("config --get mediawiki.fetchStrategy");
94 chomp($fetch_strategy);
95 unless ($fetch_strategy) {
96 $fetch_strategy = "by_page";
99 # Dumb push: don't update notes and mediawiki ref to reflect the last push.
101 # Configurable with mediawiki.dumbPush, or per-remote with
102 # remote.<remotename>.dumbPush.
104 # This means the user will have to re-import the just-pushed
105 # revisions. On the other hand, this means that the Git revisions
106 # corresponding to MediaWiki revisions are all imported from the wiki,
107 # regardless of whether they were initially created in Git or from the
108 # web interface, hence all users will get the same history (i.e. if
109 # the push from Git to MediaWiki loses some information, everybody
110 # will get the history with information lost). If the import is
111 # deterministic, this means everybody gets the same sha1 for each
112 # MediaWiki revision.
113 my $dumb_push = run_git
("config --get --bool remote.$remotename.dumbPush");
114 unless ($dumb_push) {
115 $dumb_push = run_git
("config --get --bool mediawiki.dumbPush");
118 $dumb_push = ($dumb_push eq "true");
120 my $wiki_name = $url;
121 $wiki_name =~ s/[^\/]*:\/\
///;
122 # If URL is like http://user:password@example.com/, we clearly don't
123 # want the password in $wiki_name. While we're there, also remove user
124 # and '@' sign, to avoid author like MWUser@HTTPUser@host.com
125 $wiki_name =~ s/^.*@//;
133 if (defined($cmd[0])) {
135 if ($cmd[0] eq "capabilities") {
136 die("Too many arguments for capabilities") unless (!defined($cmd[1]));
138 } elsif ($cmd[0] eq "list") {
139 die("Too many arguments for list") unless (!defined($cmd[2]));
141 } elsif ($cmd[0] eq "import") {
142 die("Invalid arguments for import") unless ($cmd[1] ne "" && !defined($cmd[2]));
144 } elsif ($cmd[0] eq "option") {
145 die("Too many arguments for option") unless ($cmd[1] ne "" && $cmd[2] ne "" && !defined($cmd[3]));
146 mw_option
($cmd[1],$cmd[2]);
147 } elsif ($cmd[0] eq "push") {
150 print STDERR
"Unknown command. Aborting...\n";
154 # blank line: we should terminate
158 BEGIN { $| = 1 } # flush STDOUT, to make sure the previous
159 # command is fully processed.
162 ########################## Functions ##############################
165 sub exit_error_usage
{
166 die "ERROR: git-remote-mediawiki module was not called with a correct number of\n" .
168 "You may obtain this error because you attempted to run the git-remote-mediawiki\n" .
169 "module directly.\n" .
170 "This module can be used the following way:\n" .
171 "\tgit clone mediawiki://<address of a mediawiki>\n" .
172 "Then, use git commit, push and pull as with every normal git repository.\n";
175 # MediaWiki API instance, created lazily.
178 sub mw_connect_maybe
{
182 $mediawiki = MediaWiki
::API
->new;
183 $mediawiki->{config
}->{api_url
} = "$url/api.php";
187 'username' => $wiki_login,
188 'password' => $wiki_passwd
190 Git
::credential
(\
%credential);
191 my $request = {lgname
=> $credential{username
},
192 lgpassword
=> $credential{password
},
193 lgdomain
=> $wiki_domain};
194 if ($mediawiki->login($request)) {
195 Git
::credential
(\
%credential, 'approve');
196 print STDERR
"Logged in mediawiki user \"$credential{username}\".\n";
198 print STDERR
"Failed to log in mediawiki user \"$credential{username}\" on $url\n";
199 print STDERR
" (error " .
200 $mediawiki->{error
}->{code
} . ': ' .
201 $mediawiki->{error
}->{details
} . ")\n";
202 Git
::credential
(\
%credential, 'reject');
210 print STDERR
"fatal: could not $action.\n";
211 print STDERR
"fatal: '$url' does not appear to be a mediawiki\n";
212 if ($url =~ /^https/) {
213 print STDERR
"fatal: make sure '$url/api.php' is a valid page\n";
214 print STDERR
"fatal: and the SSL certificate is correct.\n";
216 print STDERR
"fatal: make sure '$url/api.php' is a valid page.\n";
218 print STDERR
"fatal: (error " .
219 $mediawiki->{error
}->{code
} . ': ' .
220 $mediawiki->{error
}->{details
} . ")\n";
224 ## Functions for listing pages on the remote wiki
225 sub get_mw_tracked_pages
{
227 get_mw_page_list
(\
@tracked_pages, $pages);
230 sub get_mw_page_list
{
231 my $page_list = shift;
233 my @some_pages = @
$page_list;
234 while (@some_pages) {
236 if ($#some_pages < $last) {
237 $last = $#some_pages;
239 my @slice = @some_pages[0..$last];
240 get_mw_first_pages
(\
@slice, $pages);
241 @some_pages = @some_pages[51..$#some_pages];
245 sub get_mw_tracked_categories
{
247 foreach my $category (@tracked_categories) {
248 if (index($category, ':') < 0) {
249 # Mediawiki requires the Category
250 # prefix, but let's not force the user
252 $category = "Category:" . $category;
254 my $mw_pages = $mediawiki->list( {
256 list
=> 'categorymembers',
257 cmtitle
=> $category,
259 || die $mediawiki->{error
}->{code
} . ': '
260 . $mediawiki->{error
}->{details
};
261 foreach my $page (@
{$mw_pages}) {
262 $pages->{$page->{title
}} = $page;
267 sub get_mw_all_pages
{
269 # No user-provided list, get the list of pages from the API.
270 my $mw_pages = $mediawiki->list({
275 if (!defined($mw_pages)) {
276 fatal_mw_error
("get the list of wiki pages");
278 foreach my $page (@
{$mw_pages}) {
279 $pages->{$page->{title
}} = $page;
283 # queries the wiki for a set of pages. Meant to be used within a loop
284 # querying the wiki for slices of page list.
285 sub get_mw_first_pages
{
286 my $some_pages = shift;
287 my @some_pages = @
{$some_pages};
291 # pattern 'page1|page2|...' required by the API
292 my $titles = join('|', @some_pages);
294 my $mw_pages = $mediawiki->api({
298 if (!defined($mw_pages)) {
299 fatal_mw_error
("query the list of wiki pages");
301 while (my ($id, $page) = each(%{$mw_pages->{query
}->{pages
}})) {
303 print STDERR
"Warning: page $page->{title} not found on wiki\n";
305 $pages->{$page->{title
}} = $page;
310 # Get the list of pages to be fetched according to configuration.
314 print STDERR
"Listing pages on remote wiki...\n";
316 my %pages; # hash on page titles to avoid duplicates
318 if (@tracked_pages) {
320 # The user provided a list of pages titles, but we
321 # still need to query the API to get the page IDs.
322 get_mw_tracked_pages
(\
%pages);
324 if (@tracked_categories) {
326 get_mw_tracked_categories
(\
%pages);
328 if (!$user_defined) {
329 get_mw_all_pages
(\
%pages);
332 print STDERR
"Getting media files for selected pages...\n";
334 get_linked_mediafiles
(\
%pages);
336 get_all_mediafiles
(\
%pages);
339 print STDERR
(scalar keys %pages) . " pages found.\n";
343 # usage: $out = run_git("command args");
344 # $out = run_git("command args", "raw"); # don't interpret output as UTF-8.
347 my $encoding = (shift || "encoding(UTF-8)");
348 open(my $git, "-|:$encoding", "git " . $args);
349 my $res = do { local $/; <$git> };
356 sub get_all_mediafiles
{
358 # Attach list of all pages for media files from the API,
359 # they are in a different namespace, only one namespace
360 # can be queried at the same moment
361 my $mw_pages = $mediawiki->list({
364 apnamespace
=> get_mw_namespace_id
("File"),
367 if (!defined($mw_pages)) {
368 print STDERR
"fatal: could not get the list of pages for media files.\n";
369 print STDERR
"fatal: '$url' does not appear to be a mediawiki\n";
370 print STDERR
"fatal: make sure '$url/api.php' is a valid page.\n";
373 foreach my $page (@
{$mw_pages}) {
374 $pages->{$page->{title
}} = $page;
378 sub get_linked_mediafiles
{
380 my @titles = map $_->{title
}, values(%{$pages});
382 # The query is split in small batches because of the MW API limit of
383 # the number of links to be returned (500 links max).
386 if ($#titles < $batch) {
389 my @slice = @titles[0..$batch];
391 # pattern 'page1|page2|...' required by the API
392 my $mw_titles = join('|', @slice);
394 # Media files could be included or linked from
395 # a page, get all related
398 prop
=> 'links|images',
399 titles
=> $mw_titles,
400 plnamespace
=> get_mw_namespace_id
("File"),
403 my $result = $mediawiki->api($query);
405 while (my ($id, $page) = each(%{$result->{query
}->{pages
}})) {
407 if (defined($page->{links
})) {
408 my @link_titles = map $_->{title
}, @
{$page->{links
}};
409 push(@media_titles, @link_titles);
411 if (defined($page->{images
})) {
412 my @image_titles = map $_->{title
}, @
{$page->{images
}};
413 push(@media_titles, @image_titles);
416 get_mw_page_list
(\
@media_titles, $pages);
420 @titles = @titles[($batch+1)..$#titles];
424 sub get_mw_mediafile_for_page_revision
{
425 # Name of the file on Wiki, with the prefix.
426 my $filename = shift;
427 my $timestamp = shift;
430 # Search if on a media file with given timestamp exists on
431 # MediaWiki. In that case download the file.
435 titles
=> "File:" . $filename,
436 iistart
=> $timestamp,
438 iiprop
=> 'timestamp|archivename|url',
441 my $result = $mediawiki->api($query);
443 my ($fileid, $file) = each( %{$result->{query
}->{pages
}} );
444 # If not defined it means there is no revision of the file for
446 if (defined($file->{imageinfo
})) {
447 $mediafile{title
} = $filename;
449 my $fileinfo = pop(@
{$file->{imageinfo
}});
450 $mediafile{timestamp
} = $fileinfo->{timestamp
};
451 # Mediawiki::API's download function doesn't support https URLs
452 # and can't download old versions of files.
453 print STDERR
"\tDownloading file $mediafile{title}, version $mediafile{timestamp}\n";
454 $mediafile{content
} = download_mw_mediafile
($fileinfo->{url
});
459 sub download_mw_mediafile
{
462 my $response = $mediawiki->{ua
}->get($url);
463 if ($response->code == 200) {
464 return $response->decoded_content;
466 print STDERR
"Error downloading mediafile from :\n";
467 print STDERR
"URL: $url\n";
468 print STDERR
"Server response: " . $response->code . " " . $response->message . "\n";
473 sub get_last_local_revision
{
474 # Get note regarding last mediawiki revision
475 my $note = run_git
("notes --ref=$remotename/mediawiki show refs/mediawiki/$remotename/master 2>/dev/null");
476 my @note_info = split(/ /, $note);
478 my $lastrevision_number;
479 if (!(defined($note_info[0]) && $note_info[0] eq "mediawiki_revision:")) {
480 print STDERR
"No previous mediawiki revision found";
481 $lastrevision_number = 0;
483 # Notes are formatted : mediawiki_revision: #number
484 $lastrevision_number = $note_info[1];
485 chomp($lastrevision_number);
486 print STDERR
"Last local mediawiki revision found is $lastrevision_number";
488 return $lastrevision_number;
491 # Remember the timestamp corresponding to a revision id.
494 # Get the last remote revision without taking in account which pages are
495 # tracked or not. This function makes a single request to the wiki thus
496 # avoid a loop onto all tracked pages. This is useful for the fetch-by-rev
498 sub get_last_global_remote_rev
{
503 list
=> 'recentchanges',
508 my $result = $mediawiki->api($query);
509 return $result->{query
}->{recentchanges
}[0]->{revid
};
512 # Get the last remote revision concerning the tracked pages and the tracked
514 sub get_last_remote_revision
{
517 my %pages_hash = get_mw_pages
();
518 my @pages = values(%pages_hash);
522 print STDERR
"Getting last revision id on tracked pages...\n";
524 foreach my $page (@pages) {
525 my $id = $page->{pageid
};
530 rvprop
=> 'ids|timestamp',
534 my $result = $mediawiki->api($query);
536 my $lastrev = pop(@
{$result->{query
}->{pages
}->{$id}->{revisions
}});
538 $basetimestamps{$lastrev->{revid
}} = $lastrev->{timestamp
};
540 $max_rev_num = ($lastrev->{revid
} > $max_rev_num ?
$lastrev->{revid
} : $max_rev_num);
543 print STDERR
"Last remote revision found is $max_rev_num.\n";
547 # Clean content before sending it to MediaWiki
548 sub mediawiki_clean
{
550 my $page_created = shift;
551 # Mediawiki does not allow blank space at the end of a page and ends with a single \n.
552 # This function right trims a string and adds a \n at the end to follow this rule
554 if ($string eq "" && $page_created) {
555 # Creating empty pages is forbidden.
556 $string = EMPTY_CONTENT
;
561 # Filter applied on MediaWiki data before adding them to Git
562 sub mediawiki_smudge
{
564 if ($string eq EMPTY_CONTENT
) {
567 # This \n is important. This is due to mediawiki's way to handle end of files.
571 sub mediawiki_clean_filename
{
572 my $filename = shift;
573 $filename =~ s/@{[SLASH_REPLACEMENT]}/\//g
;
574 # [, ], |, {, and } are forbidden by MediaWiki, even URL-encoded.
575 # Do a variant of URL-encoding, i.e. looks like URL-encoding,
576 # but with _ added to prevent MediaWiki from thinking this is
577 # an actual special character.
578 $filename =~ s/[\[\]\{\}\|]/sprintf("_%%_%x", ord($&))/ge;
579 # If we use the uri escape before
580 # we should unescape here, before anything
585 sub mediawiki_smudge_filename
{
586 my $filename = shift;
587 $filename =~ s/\//@
{[SLASH_REPLACEMENT
]}/g
;
588 $filename =~ s/ /_/g;
589 # Decode forbidden characters encoded in mediawiki_clean_filename
590 $filename =~ s/_%_([0-9a-fA-F][0-9a-fA-F])/sprintf("%c", hex($1))/ge;
596 print STDOUT
"data ", bytes
::length($content), "\n", $content;
599 sub literal_data_raw
{
600 # Output possibly binary content.
602 # Avoid confusion between size in bytes and in characters
603 utf8
::downgrade
($content);
604 binmode STDOUT
, ":raw";
605 print STDOUT
"data ", bytes
::length($content), "\n", $content;
606 binmode STDOUT
, ":utf8";
609 sub mw_capabilities
{
610 # Revisions are imported to the private namespace
611 # refs/mediawiki/$remotename/ by the helper and fetched into
612 # refs/remotes/$remotename later by fetch.
613 print STDOUT
"refspec refs/heads/*:refs/mediawiki/$remotename/*\n";
614 print STDOUT
"import\n";
615 print STDOUT
"list\n";
616 print STDOUT
"push\n";
621 # MediaWiki do not have branches, we consider one branch arbitrarily
622 # called master, and HEAD pointing to it.
623 print STDOUT
"? refs/heads/master\n";
624 print STDOUT
"\@refs/heads/master HEAD\n";
629 print STDERR
"remote-helper command 'option $_[0]' not yet implemented\n";
630 print STDOUT
"unsupported\n";
633 sub fetch_mw_revisions_for_page
{
636 my $fetch_from = shift;
643 rvstartid
=> $fetch_from,
649 # Get 500 revisions at a time due to the mediawiki api limit
651 my $result = $mediawiki->api($query);
653 # Parse each of those 500 revisions
654 foreach my $revision (@
{$result->{query
}->{pages
}->{$id}->{revisions
}}) {
656 $page_rev_ids->{pageid
} = $page->{pageid
};
657 $page_rev_ids->{revid
} = $revision->{revid
};
658 push(@page_revs, $page_rev_ids);
661 last unless $result->{'query-continue'};
662 $query->{rvstartid
} = $result->{'query-continue'}->{revisions
}->{rvstartid
};
664 if ($shallow_import && @page_revs) {
665 print STDERR
" Found 1 revision (shallow import).\n";
666 @page_revs = sort {$b->{revid
} <=> $a->{revid
}} (@page_revs);
667 return $page_revs[0];
669 print STDERR
" Found ", $revnum, " revision(s).\n";
673 sub fetch_mw_revisions
{
674 my $pages = shift; my @pages = @
{$pages};
675 my $fetch_from = shift;
679 foreach my $page (@pages) {
680 my $id = $page->{pageid
};
682 print STDERR
"page $n/", scalar(@pages), ": ". $page->{title
} ."\n";
684 my @page_revs = fetch_mw_revisions_for_page
($page, $id, $fetch_from);
685 @revisions = (@page_revs, @revisions);
688 return ($n, @revisions);
693 $path =~ s/\\/\\\\/g;
696 return '"' . $path . '"';
699 sub import_file_revision
{
701 my %commit = %{$commit};
702 my $full_import = shift;
704 my $mediafile = shift;
707 %mediafile = %{$mediafile};
710 my $title = $commit{title
};
711 my $comment = $commit{comment
};
712 my $content = $commit{content
};
713 my $author = $commit{author
};
714 my $date = $commit{date
};
716 print STDOUT
"commit refs/mediawiki/$remotename/master\n";
717 print STDOUT
"mark :$n\n";
718 print STDOUT
"committer $author <$author\@$wiki_name> ", $date->epoch, " +0000\n";
719 literal_data
($comment);
721 # If it's not a clone, we need to know where to start from
722 if (!$full_import && $n == 1) {
723 print STDOUT
"from refs/mediawiki/$remotename/master^0\n";
725 if ($content ne DELETED_CONTENT
) {
726 print STDOUT
"M 644 inline " .
727 fe_escape_path
($title . ".mw") . "\n";
728 literal_data
($content);
730 print STDOUT
"M 644 inline "
731 . fe_escape_path
($mediafile{title
}) . "\n";
732 literal_data_raw
($mediafile{content
});
736 print STDOUT
"D " . fe_escape_path
($title . ".mw") . "\n";
739 # mediawiki revision number in the git note
740 if ($full_import && $n == 1) {
741 print STDOUT
"reset refs/notes/$remotename/mediawiki\n";
743 print STDOUT
"commit refs/notes/$remotename/mediawiki\n";
744 print STDOUT
"committer $author <$author\@$wiki_name> ", $date->epoch, " +0000\n";
745 literal_data
("Note added by git-mediawiki during import");
746 if (!$full_import && $n == 1) {
747 print STDOUT
"from refs/notes/$remotename/mediawiki^0\n";
749 print STDOUT
"N inline :$n\n";
750 literal_data
("mediawiki_revision: " . $commit{mw_revision
});
754 # parse a sequence of
758 # (like batch sequence of import and sequence of push statements)
764 if ($line =~ m/^$cmd (.*)$/) {
766 } elsif ($line eq "\n") {
769 die("Invalid command in a '$cmd' batch: ". $_);
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";
785 # The remote helper will call "import HEAD" and
786 # "import refs/heads/master".
787 # Since HEAD is a symbolic ref to master (by convention,
788 # followed by the output of the command "list" that we gave),
789 # we don't need to do anything in this case.
790 if ($ref eq "HEAD") {
796 print STDERR
"Searching revisions...\n";
797 my $last_local = get_last_local_revision
();
798 my $fetch_from = $last_local + 1;
799 if ($fetch_from == 1) {
800 print STDERR
", fetching from beginning.\n";
802 print STDERR
", fetching from here.\n";
806 if ($fetch_strategy eq "by_rev") {
807 print STDERR
"Fetching & writing export data by revs...\n";
808 $n = mw_import_ref_by_revs
($fetch_from);
809 } elsif ($fetch_strategy eq "by_page") {
810 print STDERR
"Fetching & writing export data by pages...\n";
811 $n = mw_import_ref_by_pages
($fetch_from);
813 print STDERR
"fatal: invalid fetch strategy \"$fetch_strategy\".\n";
814 print STDERR
"Check your configuration variables remote.$remotename.fetchStrategy and mediawiki.fetchStrategy\n";
818 if ($fetch_from == 1 && $n == 0) {
819 print STDERR
"You appear to have cloned an empty MediaWiki.\n";
820 # Something has to be done remote-helper side. If nothing is done, an error is
821 # thrown saying that HEAD is referring to unknown object 0000000000000000000
822 # and the clone fails.
826 sub mw_import_ref_by_pages
{
828 my $fetch_from = shift;
829 my %pages_hash = get_mw_pages
();
830 my @pages = values(%pages_hash);
832 my ($n, @revisions) = fetch_mw_revisions
(\
@pages, $fetch_from);
834 @revisions = sort {$a->{revid
} <=> $b->{revid
}} @revisions;
835 my @revision_ids = map $_->{revid
}, @revisions;
837 return mw_import_revids
($fetch_from, \
@revision_ids, \
%pages_hash);
840 sub mw_import_ref_by_revs
{
842 my $fetch_from = shift;
843 my %pages_hash = get_mw_pages
();
845 my $last_remote = get_last_global_remote_rev
();
846 my @revision_ids = $fetch_from..$last_remote;
847 return mw_import_revids
($fetch_from, \
@revision_ids, \
%pages_hash);
850 # Import revisions given in second argument (array of integers).
851 # Only pages appearing in the third argument (hash indexed by page titles)
853 sub mw_import_revids
{
854 my $fetch_from = shift;
855 my $revision_ids = shift;
860 my $last_timestamp = 0; # Placeholer in case $rev->timestamp is undefined
862 foreach my $pagerevid (@
$revision_ids) {
863 # Count page even if we skip it, since we display
864 # $n/$total and $total includes skipped pages.
867 # fetch the content of the pages
871 rvprop
=> 'content|timestamp|comment|user|ids',
872 revids
=> $pagerevid,
875 my $result = $mediawiki->api($query);
878 die "Failed to retrieve modified page for revision $pagerevid";
881 if (defined($result->{query
}->{badrevids
}->{$pagerevid})) {
882 # The revision id does not exist on the remote wiki.
886 if (!defined($result->{query
}->{pages
})) {
887 die "Invalid revision $pagerevid.";
890 my @result_pages = values(%{$result->{query
}->{pages
}});
891 my $result_page = $result_pages[0];
892 my $rev = $result_pages[0]->{revisions
}->[0];
894 my $page_title = $result_page->{title
};
896 if (!exists($pages->{$page_title})) {
897 print STDERR
"$n/", scalar(@
$revision_ids),
898 ": Skipping revision #$rev->{revid} of $page_title\n";
905 $commit{author
} = $rev->{user
} || 'Anonymous';
906 $commit{comment
} = $rev->{comment
} || EMPTY_MESSAGE
;
907 $commit{title
} = mediawiki_smudge_filename
($page_title);
908 $commit{mw_revision
} = $rev->{revid
};
909 $commit{content
} = mediawiki_smudge
($rev->{'*'});
911 if (!defined($rev->{timestamp
})) {
914 $last_timestamp = $rev->{timestamp
};
916 $commit{date
} = DateTime
::Format
::ISO8601
->parse_datetime($last_timestamp);
918 # Differentiates classic pages and media files.
919 my ($namespace, $filename) = $page_title =~ /^([^:]*):(.*)$/;
922 my $id = get_mw_namespace_id
($namespace);
923 if ($id && $id == get_mw_namespace_id
("File")) {
924 %mediafile = get_mw_mediafile_for_page_revision
($filename, $rev->{timestamp
});
927 # If this is a revision of the media page for new version
928 # of a file do one common commit for both file and media page.
929 # Else do commit only for that page.
930 print STDERR
"$n/", scalar(@
$revision_ids), ": Revision #$rev->{revid} of $commit{title}\n";
931 import_file_revision
(\
%commit, ($fetch_from == 1), $n_actual, \
%mediafile);
937 sub error_non_fast_forward
{
938 my $advice = run_git
("config --bool advice.pushNonFastForward");
940 if ($advice ne "false") {
941 # Native git-push would show this after the summary.
942 # We can't ask it to display it cleanly, so print it
944 print STDERR
"To prevent you from losing history, non-fast-forward updates were rejected\n";
945 print STDERR
"Merge the remote changes (e.g. 'git pull') before pushing again. See the\n";
946 print STDERR
"'Note about fast-forwards' section of 'git push --help' for details.\n";
948 print STDOUT
"error $_[0] \"non-fast-forward\"\n";
953 my $complete_file_name = shift;
954 my $new_sha1 = shift;
955 my $extension = shift;
956 my $file_deleted = shift;
959 my $path = "File:" . $complete_file_name;
960 my %hashFiles = get_allowed_file_extensions
();
961 if (!exists($hashFiles{$extension})) {
962 print STDERR
"$complete_file_name is not a permitted file on this wiki.\n";
963 print STDERR
"Check the configuration of file uploads in your mediawiki.\n";
966 # Deleting and uploading a file requires a priviledged user
974 if (!$mediawiki->edit($query)) {
975 print STDERR
"Failed to delete file on remote wiki\n";
976 print STDERR
"Check your permissions on the remote site. Error code:\n";
977 print STDERR
$mediawiki->{error
}->{code
} . ':' . $mediawiki->{error
}->{details
};
981 # Don't let perl try to interpret file content as UTF-8 => use "raw"
982 my $content = run_git
("cat-file blob $new_sha1", "raw");
983 if ($content ne "") {
985 $mediawiki->{config
}->{upload_url
} =
986 "$url/index.php/Special:Upload";
989 filename
=> $complete_file_name,
993 Content
=> $content],
997 } ) || die $mediawiki->{error
}->{code
} . ':'
998 . $mediawiki->{error
}->{details
};
999 my $last_file_page = $mediawiki->get_page({title
=> $path});
1000 $newrevid = $last_file_page->{revid
};
1001 print STDERR
"Pushed file: $new_sha1 - $complete_file_name.\n";
1003 print STDERR
"Empty file $complete_file_name not pushed.\n";
1010 my $diff_info = shift;
1011 # $diff_info contains a string in this format:
1012 # 100644 100644 <sha1_of_blob_before_commit> <sha1_of_blob_now> <status>
1013 my @diff_info_split = split(/[ \t]/, $diff_info);
1015 # Filename, including .mw extension
1016 my $complete_file_name = shift;
1018 my $summary = shift;
1019 # MediaWiki revision number. Keep the previous one by default,
1020 # in case there's no edit to perform.
1021 my $oldrevid = shift;
1024 if ($summary eq EMPTY_MESSAGE
) {
1028 my $new_sha1 = $diff_info_split[3];
1029 my $old_sha1 = $diff_info_split[2];
1030 my $page_created = ($old_sha1 eq NULL_SHA1
);
1031 my $page_deleted = ($new_sha1 eq NULL_SHA1
);
1032 $complete_file_name = mediawiki_clean_filename
($complete_file_name);
1034 my ($title, $extension) = $complete_file_name =~ /^(.*)\.([^\.]*)$/;
1035 if (!defined($extension)) {
1038 if ($extension eq "mw") {
1039 my $ns = get_mw_namespace_id_for_page
($complete_file_name);
1040 if ($ns && $ns == get_mw_namespace_id
("File") && (!$export_media)) {
1041 print STDERR
"Ignoring media file related page: $complete_file_name\n";
1042 return ($oldrevid, "ok");
1045 if ($page_deleted) {
1046 # Deleting a page usually requires
1047 # special privileges. A common
1048 # convention is to replace the page
1049 # with this content instead:
1050 $file_content = DELETED_CONTENT
;
1052 $file_content = run_git
("cat-file blob $new_sha1");
1057 my $result = $mediawiki->edit( {
1059 summary
=> $summary,
1061 basetimestamp
=> $basetimestamps{$oldrevid},
1062 text
=> mediawiki_clean
($file_content, $page_created),
1064 skip_encoding
=> 1 # Helps with names with accentuated characters
1067 if ($mediawiki->{error
}->{code
} == 3) {
1068 # edit conflicts, considered as non-fast-forward
1069 print STDERR
'Warning: Error ' .
1070 $mediawiki->{error
}->{code
} .
1071 ' from mediwiki: ' . $mediawiki->{error
}->{details
} .
1073 return ($oldrevid, "non-fast-forward");
1075 # Other errors. Shouldn't happen => just die()
1076 die 'Fatal: Error ' .
1077 $mediawiki->{error
}->{code
} .
1078 ' from mediwiki: ' . $mediawiki->{error
}->{details
};
1081 $newrevid = $result->{edit
}->{newrevid
};
1082 print STDERR
"Pushed file: $new_sha1 - $title\n";
1083 } elsif ($export_media) {
1084 $newrevid = mw_upload_file
($complete_file_name, $new_sha1,
1085 $extension, $page_deleted,
1088 print STDERR
"Ignoring media file $title\n";
1090 $newrevid = ($newrevid or $oldrevid);
1091 return ($newrevid, "ok");
1095 # multiple push statements can follow each other
1096 my @refsspecs = (shift, get_more_refs
("push"));
1098 for my $refspec (@refsspecs) {
1099 my ($force, $local, $remote) = $refspec =~ /^(\+)?([^:]*):([^:]*)$/
1100 or die("Invalid refspec for push. Expected <src>:<dst> or +<src>:<dst>");
1102 print STDERR
"Warning: forced push not allowed on a MediaWiki.\n";
1105 print STDERR
"Cannot delete remote branch on a MediaWiki\n";
1106 print STDOUT
"error $remote cannot delete\n";
1109 if ($remote ne "refs/heads/master") {
1110 print STDERR
"Only push to the branch 'master' is supported on a MediaWiki\n";
1111 print STDOUT
"error $remote only master allowed\n";
1114 if (mw_push_revision
($local, $remote)) {
1119 # Notify Git that the push is done
1122 if ($pushed && $dumb_push) {
1123 print STDERR
"Just pushed some revisions to MediaWiki.\n";
1124 print STDERR
"The pushed revisions now have to be re-imported, and your current branch\n";
1125 print STDERR
"needs to be updated with these re-imported commits. You can do this with\n";
1127 print STDERR
" git pull --rebase\n";
1132 sub mw_push_revision
{
1134 my $remote = shift; # actually, this has to be "refs/heads/master" at this point.
1135 my $last_local_revid = get_last_local_revision
();
1136 print STDERR
".\n"; # Finish sentence started by get_last_local_revision()
1137 my $last_remote_revid = get_last_remote_revision
();
1138 my $mw_revision = $last_remote_revid;
1140 # Get sha1 of commit pointed by local HEAD
1141 my $HEAD_sha1 = run_git
("rev-parse $local 2>/dev/null"); chomp($HEAD_sha1);
1142 # Get sha1 of commit pointed by remotes/$remotename/master
1143 my $remoteorigin_sha1 = run_git
("rev-parse refs/remotes/$remotename/master 2>/dev/null");
1144 chomp($remoteorigin_sha1);
1146 if ($last_local_revid > 0 &&
1147 $last_local_revid < $last_remote_revid) {
1148 return error_non_fast_forward
($remote);
1151 if ($HEAD_sha1 eq $remoteorigin_sha1) {
1156 # Get every commit in between HEAD and refs/remotes/origin/master,
1157 # including HEAD and refs/remotes/origin/master
1158 my @commit_pairs = ();
1159 if ($last_local_revid > 0) {
1160 my $parsed_sha1 = $remoteorigin_sha1;
1161 # Find a path from last MediaWiki commit to pushed commit
1162 print STDERR
"Computing path from local to remote ...\n";
1163 my @local_ancestry = split(/\n/, run_git
("rev-list --boundary --parents $local ^$parsed_sha1"));
1165 foreach my $line (@local_ancestry) {
1166 if (my ($child, $parents) = $line =~ m/^-?([a-f0-9]+) ([a-f0-9 ]+)/) {
1167 foreach my $parent (split(' ', $parents)) {
1168 $local_ancestry{$parent} = $child;
1170 } elsif (!$line =~ m/^([a-f0-9]+)/) {
1171 die "Unexpected output from git rev-list: $line";
1174 while ($parsed_sha1 ne $HEAD_sha1) {
1175 my $child = $local_ancestry{$parsed_sha1};
1177 printf STDERR
"Cannot find a path in history from remote commit to last commit\n";
1178 return error_non_fast_forward
($remote);
1180 push(@commit_pairs, [$parsed_sha1, $child]);
1181 $parsed_sha1 = $child;
1184 # No remote mediawiki revision. Export the whole
1185 # history (linearized with --first-parent)
1186 print STDERR
"Warning: no common ancestor, pushing complete history\n";
1187 my $history = run_git
("rev-list --first-parent --children $local");
1188 my @history = split('\n', $history);
1189 @history = @history[1..$#history];
1190 foreach my $line (reverse @history) {
1191 my @commit_info_split = split(/ |\n/, $line);
1192 push(@commit_pairs, \
@commit_info_split);
1196 foreach my $commit_info_split (@commit_pairs) {
1197 my $sha1_child = @
{$commit_info_split}[0];
1198 my $sha1_commit = @
{$commit_info_split}[1];
1199 my $diff_infos = run_git
("diff-tree -r --raw -z $sha1_child $sha1_commit");
1200 # TODO: we could detect rename, and encode them with a #redirect on the wiki.
1201 # TODO: for now, it's just a delete+add
1202 my @diff_info_list = split(/\0/, $diff_infos);
1203 # Keep the subject line of the commit message as mediawiki comment for the revision
1204 my $commit_msg = run_git
("log --no-walk --format=\"%s\" $sha1_commit");
1207 while (@diff_info_list) {
1209 # git diff-tree -z gives an output like
1210 # <metadata>\0<filename1>\0
1211 # <metadata>\0<filename2>\0
1212 # and we've split on \0.
1213 my $info = shift(@diff_info_list);
1214 my $file = shift(@diff_info_list);
1215 ($mw_revision, $status) = mw_push_file
($info, $file, $commit_msg, $mw_revision);
1216 if ($status eq "non-fast-forward") {
1217 # we may already have sent part of the
1218 # commit to MediaWiki, but it's too
1219 # late to cancel it. Stop the push in
1220 # the middle, but still give an
1221 # accurate error message.
1222 return error_non_fast_forward
($remote);
1224 if ($status ne "ok") {
1225 die("Unknown error from mw_push_file()");
1228 unless ($dumb_push) {
1229 run_git
("notes --ref=$remotename/mediawiki add -f -m \"mediawiki_revision: $mw_revision\" $sha1_commit");
1230 run_git
("update-ref -m \"Git-MediaWiki push\" refs/mediawiki/$remotename/master $sha1_commit $sha1_child");
1234 print STDOUT
"ok $remote\n";
1238 sub get_allowed_file_extensions
{
1244 siprop
=> 'fileextensions'
1246 my $result = $mediawiki->api($query);
1247 my @file_extensions= map $_->{ext
},@
{$result->{query
}->{fileextensions
}};
1248 my %hashFile = map {$_ => 1}@file_extensions;
1253 # In memory cache for MediaWiki namespace ids.
1256 # Namespaces whose id is cached in the configuration file
1257 # (to avoid duplicates)
1258 my %cached_mw_namespace_id;
1260 # Return MediaWiki id for a canonical namespace name.
1261 # Ex.: "File", "Project".
1262 sub get_mw_namespace_id
{
1266 if (!exists $namespace_id{$name}) {
1267 # Look at configuration file, if the record for that namespace is
1268 # already cached. Namespaces are stored in form:
1269 # "Name_of_namespace:Id_namespace", ex.: "File:6".
1270 my @temp = split(/[\n]/, run_git
("config --get-all remote."
1271 . $remotename .".namespaceCache"));
1273 foreach my $ns (@temp) {
1274 my ($n, $id) = split(/:/, $ns);
1275 if ($id eq 'notANameSpace') {
1276 $namespace_id{$n} = {is_namespace
=> 0};
1278 $namespace_id{$n} = {is_namespace
=> 1, id
=> $id};
1280 $cached_mw_namespace_id{$n} = 1;
1284 if (!exists $namespace_id{$name}) {
1285 print STDERR
"Namespace $name not found in cache, querying the wiki ...\n";
1286 # NS not found => get namespace id from MW and store it in
1287 # configuration file.
1291 siprop
=> 'namespaces'
1293 my $result = $mediawiki->api($query);
1295 while (my ($id, $ns) = each(%{$result->{query
}->{namespaces
}})) {
1296 if (defined($ns->{id
}) && defined($ns->{canonical
})) {
1297 $namespace_id{$ns->{canonical
}} = {is_namespace
=> 1, id
=> $ns->{id
}};
1299 # alias (e.g. french Fichier: as alias for canonical File:)
1300 $namespace_id{$ns->{'*'}} = {is_namespace
=> 1, id
=> $ns->{id
}};
1306 my $ns = $namespace_id{$name};
1309 unless (defined $ns) {
1310 print STDERR
"No such namespace $name on MediaWiki.\n";
1311 $ns = {is_namespace
=> 0};
1312 $namespace_id{$name} = $ns;
1315 if ($ns->{is_namespace
}) {
1319 # Store "notANameSpace" as special value for inexisting namespaces
1320 my $store_id = ($id || 'notANameSpace');
1322 # Store explicitely requested namespaces on disk
1323 if (!exists $cached_mw_namespace_id{$name}) {
1324 run_git
("config --add remote.". $remotename
1325 .".namespaceCache \"". $name .":". $store_id ."\"");
1326 $cached_mw_namespace_id{$name} = 1;
1331 sub get_mw_namespace_id_for_page
{
1332 if (my ($namespace) = $_[0] =~ /^([^:]*):/) {
1333 return get_mw_namespace_id
($namespace);