4 # Jérémie Nikaes <jeremie.nikaes@ensimag.imag.fr>
5 # Arnaud Lacurie <arnaud.lacurie@ensimag.imag.fr>
6 # Claire Fousse <claire.fousse@ensimag.imag.fr>
7 # David Amouyal <david.amouyal@ensimag.imag.fr>
8 # Matthieu Moy <matthieu.moy@grenoble-inp.fr>
9 # License: GPL v2 or later
11 # Gateway between Git and MediaWiki.
12 # https://github.com/Bibzball/Git-Mediawiki/wiki
16 # - Several strategies are provided to fetch modifications from the
17 # wiki, but no automatic heuristics is provided, the user has
18 # to understand and chose which strategy is appropriate for him.
20 # - Git renames could be turned into MediaWiki renames (see TODO
23 # - No way to import "one page, and all pages included in it"
25 # - Multiple remote MediaWikis have not been very well tested.
29 use DateTime
::Format
::ISO8601
;
31 # By default, use UTF-8 to communicate with Git and the user
32 binmode STDERR
, ":utf8";
33 binmode STDOUT
, ":utf8";
40 # Mediawiki filenames can contain forward slashes. This variable decides by which pattern they should be replaced
41 use constant SLASH_REPLACEMENT
=> "%2F";
43 # It's not always possible to delete pages (may require some
44 # priviledges). Deleted pages are replaced with this content.
45 use constant DELETED_CONTENT
=> "[[Category:Deleted]]\n";
47 # It's not possible to create empty pages. New empty files in Git are
48 # sent with this content instead.
49 use constant EMPTY_CONTENT
=> "<!-- empty page -->\n";
51 # used to reflect file creation or deletion in diff.
52 use constant NULL_SHA1
=> "0000000000000000000000000000000000000000";
54 my $remotename = $ARGV[0];
57 # Accept both space-separated and multiple keys in config file.
58 # Spaces should be written as _ anyway because we'll use chomp.
59 my @tracked_pages = split(/[ \n]/, run_git
("config --get-all remote.". $remotename .".pages"));
60 chomp(@tracked_pages);
62 # Just like @tracked_pages, but for MediaWiki categories.
63 my @tracked_categories = split(/[ \n]/, run_git
("config --get-all remote.". $remotename .".categories"));
64 chomp(@tracked_categories);
66 # Import media files too.
67 my $import_media = run_git
("config --get --bool remote.". $remotename .".mediaimport");
69 $import_media = ($import_media eq "true");
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 ##############################
164 ## credential API management (generic functions)
166 sub credential_read
{
171 my ($key, $value) = /([^=]*)=(.*)/;
172 if (not defined $key) {
173 die "ERROR receiving response from git credential $op:\n$_\n";
175 $credential{$key} = $value;
180 sub credential_write
{
181 my $credential = shift;
183 # url overwrites other fields, so it must come first
184 print $writer "url=$credential->{url}\n" if exists $credential->{url
};
185 while (my ($key, $value) = each(%$credential) ) {
186 if (length $value && $key ne 'url') {
187 print $writer "$key=$value\n";
194 my $credential = shift;
195 my $pid = open2
(my $reader, my $writer, "git credential $op");
196 credential_write
($credential, $writer);
201 %$credential = credential_read
($reader, $op);
204 die "ERROR while running git credential $op:\n$_";
209 my $child_exit_status = $?
>> 8;
210 if ($child_exit_status != 0) {
211 die "'git credential $op' failed with code $child_exit_status.";
215 # MediaWiki API instance, created lazily.
218 sub mw_connect_maybe
{
222 $mediawiki = MediaWiki
::API
->new;
223 $mediawiki->{config
}->{api_url
} = "$url/api.php";
225 my %credential = (url
=> $url);
226 $credential{username
} = $wiki_login;
227 $credential{password
} = $wiki_passwd;
228 credential_run
("fill", \
%credential);
229 my $request = {lgname
=> $credential{username
},
230 lgpassword
=> $credential{password
},
231 lgdomain
=> $wiki_domain};
232 if ($mediawiki->login($request)) {
233 credential_run
("approve", \
%credential);
234 print STDERR
"Logged in mediawiki user \"$credential{username}\".\n";
236 print STDERR
"Failed to log in mediawiki user \"$credential{username}\" on $url\n";
237 print STDERR
" (error " .
238 $mediawiki->{error
}->{code
} . ': ' .
239 $mediawiki->{error
}->{details
} . ")\n";
240 credential_run
("reject", \
%credential);
246 ## Functions for listing pages on the remote wiki
247 sub get_mw_tracked_pages
{
249 get_mw_page_list
(\
@tracked_pages, $pages);
252 sub get_mw_page_list
{
253 my $page_list = shift;
255 my @some_pages = @
$page_list;
256 while (@some_pages) {
258 if ($#some_pages < $last) {
259 $last = $#some_pages;
261 my @slice = @some_pages[0..$last];
262 get_mw_first_pages
(\
@slice, $pages);
263 @some_pages = @some_pages[51..$#some_pages];
267 sub get_mw_tracked_categories
{
269 foreach my $category (@tracked_categories) {
270 if (index($category, ':') < 0) {
271 # Mediawiki requires the Category
272 # prefix, but let's not force the user
274 $category = "Category:" . $category;
276 my $mw_pages = $mediawiki->list( {
278 list
=> 'categorymembers',
279 cmtitle
=> $category,
281 || die $mediawiki->{error
}->{code
} . ': '
282 . $mediawiki->{error
}->{details
};
283 foreach my $page (@
{$mw_pages}) {
284 $pages->{$page->{title
}} = $page;
289 sub get_mw_all_pages
{
291 # No user-provided list, get the list of pages from the API.
292 my $mw_pages = $mediawiki->list({
297 if (!defined($mw_pages)) {
298 print STDERR
"fatal: could not get the list of wiki pages.\n";
299 print STDERR
"fatal: '$url' does not appear to be a mediawiki\n";
300 print STDERR
"fatal: make sure '$url/api.php' is a valid page.\n";
303 foreach my $page (@
{$mw_pages}) {
304 $pages->{$page->{title
}} = $page;
308 # queries the wiki for a set of pages. Meant to be used within a loop
309 # querying the wiki for slices of page list.
310 sub get_mw_first_pages
{
311 my $some_pages = shift;
312 my @some_pages = @
{$some_pages};
316 # pattern 'page1|page2|...' required by the API
317 my $titles = join('|', @some_pages);
319 my $mw_pages = $mediawiki->api({
323 if (!defined($mw_pages)) {
324 print STDERR
"fatal: could not query the list of wiki pages.\n";
325 print STDERR
"fatal: '$url' does not appear to be a mediawiki\n";
326 print STDERR
"fatal: make sure '$url/api.php' is a valid page.\n";
329 while (my ($id, $page) = each(%{$mw_pages->{query
}->{pages
}})) {
331 print STDERR
"Warning: page $page->{title} not found on wiki\n";
333 $pages->{$page->{title
}} = $page;
338 # Get the list of pages to be fetched according to configuration.
342 my %pages; # hash on page titles to avoid duplicates
344 if (@tracked_pages) {
346 # The user provided a list of pages titles, but we
347 # still need to query the API to get the page IDs.
348 get_mw_tracked_pages
(\
%pages);
350 if (@tracked_categories) {
352 get_mw_tracked_categories
(\
%pages);
354 if (!$user_defined) {
355 get_mw_all_pages
(\
%pages);
358 print STDERR
"Getting media files for selected pages...\n";
360 get_linked_mediafiles
(\
%pages);
362 get_all_mediafiles
(\
%pages);
368 # usage: $out = run_git("command args");
369 # $out = run_git("command args", "raw"); # don't interpret output as UTF-8.
372 my $encoding = (shift || "encoding(UTF-8)");
373 open(my $git, "-|:$encoding", "git " . $args);
374 my $res = do { local $/; <$git> };
381 sub get_all_mediafiles
{
383 # Attach list of all pages for media files from the API,
384 # they are in a different namespace, only one namespace
385 # can be queried at the same moment
386 my $mw_pages = $mediawiki->list({
389 apnamespace
=> get_mw_namespace_id
("File"),
392 if (!defined($mw_pages)) {
393 print STDERR
"fatal: could not get the list of pages for media files.\n";
394 print STDERR
"fatal: '$url' does not appear to be a mediawiki\n";
395 print STDERR
"fatal: make sure '$url/api.php' is a valid page.\n";
398 foreach my $page (@
{$mw_pages}) {
399 $pages->{$page->{title
}} = $page;
403 sub get_linked_mediafiles
{
405 my @titles = map $_->{title
}, values(%{$pages});
407 # The query is split in small batches because of the MW API limit of
408 # the number of links to be returned (500 links max).
411 if ($#titles < $batch) {
414 my @slice = @titles[0..$batch];
416 # pattern 'page1|page2|...' required by the API
417 my $mw_titles = join('|', @slice);
419 # Media files could be included or linked from
420 # a page, get all related
423 prop
=> 'links|images',
424 titles
=> $mw_titles,
425 plnamespace
=> get_mw_namespace_id
("File"),
428 my $result = $mediawiki->api($query);
430 while (my ($id, $page) = each(%{$result->{query
}->{pages
}})) {
432 if (defined($page->{links
})) {
433 my @link_titles = map $_->{title
}, @
{$page->{links
}};
434 push(@media_titles, @link_titles);
436 if (defined($page->{images
})) {
437 my @image_titles = map $_->{title
}, @
{$page->{images
}};
438 push(@media_titles, @image_titles);
441 get_mw_page_list
(\
@media_titles, $pages);
445 @titles = @titles[($batch+1)..$#titles];
449 sub get_mw_mediafile_for_page_revision
{
450 # Name of the file on Wiki, with the prefix.
451 my $filename = shift;
452 my $timestamp = shift;
455 # Search if on a media file with given timestamp exists on
456 # MediaWiki. In that case download the file.
460 titles
=> "File:" . $filename,
461 iistart
=> $timestamp,
463 iiprop
=> 'timestamp|archivename|url',
466 my $result = $mediawiki->api($query);
468 my ($fileid, $file) = each( %{$result->{query
}->{pages
}} );
469 # If not defined it means there is no revision of the file for
471 if (defined($file->{imageinfo
})) {
472 $mediafile{title
} = $filename;
474 my $fileinfo = pop(@
{$file->{imageinfo
}});
475 $mediafile{timestamp
} = $fileinfo->{timestamp
};
476 # Mediawiki::API's download function doesn't support https URLs
477 # and can't download old versions of files.
478 print STDERR
"\tDownloading file $mediafile{title}, version $mediafile{timestamp}\n";
479 $mediafile{content
} = download_mw_mediafile
($fileinfo->{url
});
484 sub download_mw_mediafile
{
487 my $response = $mediawiki->{ua
}->get($url);
488 if ($response->code == 200) {
489 return $response->decoded_content;
491 print STDERR
"Error downloading mediafile from :\n";
492 print STDERR
"URL: $url\n";
493 print STDERR
"Server response: " . $response->code . " " . $response->message . "\n";
498 sub get_last_local_revision
{
499 # Get note regarding last mediawiki revision
500 my $note = run_git
("notes --ref=$remotename/mediawiki show refs/mediawiki/$remotename/master 2>/dev/null");
501 my @note_info = split(/ /, $note);
503 my $lastrevision_number;
504 if (!(defined($note_info[0]) && $note_info[0] eq "mediawiki_revision:")) {
505 print STDERR
"No previous mediawiki revision found";
506 $lastrevision_number = 0;
508 # Notes are formatted : mediawiki_revision: #number
509 $lastrevision_number = $note_info[1];
510 chomp($lastrevision_number);
511 print STDERR
"Last local mediawiki revision found is $lastrevision_number";
513 return $lastrevision_number;
516 # Remember the timestamp corresponding to a revision id.
519 # Get the last remote revision without taking in account which pages are
520 # tracked or not. This function makes a single request to the wiki thus
521 # avoid a loop onto all tracked pages. This is useful for the fetch-by-rev
523 sub get_last_global_remote_rev
{
528 list
=> 'recentchanges',
533 my $result = $mediawiki->api($query);
534 return $result->{query
}->{recentchanges
}[0]->{revid
};
537 # Get the last remote revision concerning the tracked pages and the tracked
539 sub get_last_remote_revision
{
542 my %pages_hash = get_mw_pages
();
543 my @pages = values(%pages_hash);
547 foreach my $page (@pages) {
548 my $id = $page->{pageid
};
553 rvprop
=> 'ids|timestamp',
557 my $result = $mediawiki->api($query);
559 my $lastrev = pop(@
{$result->{query
}->{pages
}->{$id}->{revisions
}});
561 $basetimestamps{$lastrev->{revid
}} = $lastrev->{timestamp
};
563 $max_rev_num = ($lastrev->{revid
} > $max_rev_num ?
$lastrev->{revid
} : $max_rev_num);
566 print STDERR
"Last remote revision found is $max_rev_num.\n";
570 # Clean content before sending it to MediaWiki
571 sub mediawiki_clean
{
573 my $page_created = shift;
574 # Mediawiki does not allow blank space at the end of a page and ends with a single \n.
575 # This function right trims a string and adds a \n at the end to follow this rule
577 if ($string eq "" && $page_created) {
578 # Creating empty pages is forbidden.
579 $string = EMPTY_CONTENT
;
584 # Filter applied on MediaWiki data before adding them to Git
585 sub mediawiki_smudge
{
587 if ($string eq EMPTY_CONTENT
) {
590 # This \n is important. This is due to mediawiki's way to handle end of files.
594 sub mediawiki_clean_filename
{
595 my $filename = shift;
596 $filename =~ s/@{[SLASH_REPLACEMENT]}/\//g
;
597 # [, ], |, {, and } are forbidden by MediaWiki, even URL-encoded.
598 # Do a variant of URL-encoding, i.e. looks like URL-encoding,
599 # but with _ added to prevent MediaWiki from thinking this is
600 # an actual special character.
601 $filename =~ s/[\[\]\{\}\|]/sprintf("_%%_%x", ord($&))/ge;
602 # If we use the uri escape before
603 # we should unescape here, before anything
608 sub mediawiki_smudge_filename
{
609 my $filename = shift;
610 $filename =~ s/\//@
{[SLASH_REPLACEMENT
]}/g
;
611 $filename =~ s/ /_/g;
612 # Decode forbidden characters encoded in mediawiki_clean_filename
613 $filename =~ s/_%_([0-9a-fA-F][0-9a-fA-F])/sprintf("%c", hex($1))/ge;
619 print STDOUT
"data ", bytes
::length($content), "\n", $content;
622 sub literal_data_raw
{
623 # Output possibly binary content.
625 # Avoid confusion between size in bytes and in characters
626 utf8
::downgrade
($content);
627 binmode STDOUT
, ":raw";
628 print STDOUT
"data ", bytes
::length($content), "\n", $content;
629 binmode STDOUT
, ":utf8";
632 sub mw_capabilities
{
633 # Revisions are imported to the private namespace
634 # refs/mediawiki/$remotename/ by the helper and fetched into
635 # refs/remotes/$remotename later by fetch.
636 print STDOUT
"refspec refs/heads/*:refs/mediawiki/$remotename/*\n";
637 print STDOUT
"import\n";
638 print STDOUT
"list\n";
639 print STDOUT
"push\n";
644 # MediaWiki do not have branches, we consider one branch arbitrarily
645 # called master, and HEAD pointing to it.
646 print STDOUT
"? refs/heads/master\n";
647 print STDOUT
"\@refs/heads/master HEAD\n";
652 print STDERR
"remote-helper command 'option $_[0]' not yet implemented\n";
653 print STDOUT
"unsupported\n";
656 sub fetch_mw_revisions_for_page
{
659 my $fetch_from = shift;
666 rvstartid
=> $fetch_from,
672 # Get 500 revisions at a time due to the mediawiki api limit
674 my $result = $mediawiki->api($query);
676 # Parse each of those 500 revisions
677 foreach my $revision (@
{$result->{query
}->{pages
}->{$id}->{revisions
}}) {
679 $page_rev_ids->{pageid
} = $page->{pageid
};
680 $page_rev_ids->{revid
} = $revision->{revid
};
681 push(@page_revs, $page_rev_ids);
684 last unless $result->{'query-continue'};
685 $query->{rvstartid
} = $result->{'query-continue'}->{revisions
}->{rvstartid
};
687 if ($shallow_import && @page_revs) {
688 print STDERR
" Found 1 revision (shallow import).\n";
689 @page_revs = sort {$b->{revid
} <=> $a->{revid
}} (@page_revs);
690 return $page_revs[0];
692 print STDERR
" Found ", $revnum, " revision(s).\n";
696 sub fetch_mw_revisions
{
697 my $pages = shift; my @pages = @
{$pages};
698 my $fetch_from = shift;
702 foreach my $page (@pages) {
703 my $id = $page->{pageid
};
705 print STDERR
"page $n/", scalar(@pages), ": ". $page->{title
} ."\n";
707 my @page_revs = fetch_mw_revisions_for_page
($page, $id, $fetch_from);
708 @revisions = (@page_revs, @revisions);
711 return ($n, @revisions);
714 sub import_file_revision
{
716 my %commit = %{$commit};
717 my $full_import = shift;
719 my $mediafile = shift;
722 %mediafile = %{$mediafile};
725 my $title = $commit{title
};
726 my $comment = $commit{comment
};
727 my $content = $commit{content
};
728 my $author = $commit{author
};
729 my $date = $commit{date
};
731 print STDOUT
"commit refs/mediawiki/$remotename/master\n";
732 print STDOUT
"mark :$n\n";
733 print STDOUT
"committer $author <$author\@$wiki_name> ", $date->epoch, " +0000\n";
734 literal_data
($comment);
736 # If it's not a clone, we need to know where to start from
737 if (!$full_import && $n == 1) {
738 print STDOUT
"from refs/mediawiki/$remotename/master^0\n";
740 if ($content ne DELETED_CONTENT
) {
741 print STDOUT
"M 644 inline $title.mw\n";
742 literal_data
($content);
744 print STDOUT
"M 644 inline $mediafile{title}\n";
745 literal_data_raw
($mediafile{content
});
749 print STDOUT
"D $title.mw\n";
752 # mediawiki revision number in the git note
753 if ($full_import && $n == 1) {
754 print STDOUT
"reset refs/notes/$remotename/mediawiki\n";
756 print STDOUT
"commit refs/notes/$remotename/mediawiki\n";
757 print STDOUT
"committer $author <$author\@$wiki_name> ", $date->epoch, " +0000\n";
758 literal_data
("Note added by git-mediawiki during import");
759 if (!$full_import && $n == 1) {
760 print STDOUT
"from refs/notes/$remotename/mediawiki^0\n";
762 print STDOUT
"N inline :$n\n";
763 literal_data
("mediawiki_revision: " . $commit{mw_revision
});
767 # parse a sequence of
771 # (like batch sequence of import and sequence of push statements)
777 if ($line =~ m/^$cmd (.*)$/) {
779 } elsif ($line eq "\n") {
782 die("Invalid command in a '$cmd' batch: ". $_);
788 # multiple import commands can follow each other.
789 my @refs = (shift, get_more_refs
("import"));
790 foreach my $ref (@refs) {
793 print STDOUT
"done\n";
798 # The remote helper will call "import HEAD" and
799 # "import refs/heads/master".
800 # Since HEAD is a symbolic ref to master (by convention,
801 # followed by the output of the command "list" that we gave),
802 # we don't need to do anything in this case.
803 if ($ref eq "HEAD") {
809 print STDERR
"Searching revisions...\n";
810 my $last_local = get_last_local_revision
();
811 my $fetch_from = $last_local + 1;
812 if ($fetch_from == 1) {
813 print STDERR
", fetching from beginning.\n";
815 print STDERR
", fetching from here.\n";
819 if ($fetch_strategy eq "by_rev") {
820 print STDERR
"Fetching & writing export data by revs...\n";
821 $n = mw_import_ref_by_revs
($fetch_from);
822 } elsif ($fetch_strategy eq "by_page") {
823 print STDERR
"Fetching & writing export data by pages...\n";
824 $n = mw_import_ref_by_pages
($fetch_from);
826 print STDERR
"fatal: invalid fetch strategy \"$fetch_strategy\".\n";
827 print STDERR
"Check your configuration variables remote.$remotename.fetchStrategy and mediawiki.fetchStrategy\n";
831 if ($fetch_from == 1 && $n == 0) {
832 print STDERR
"You appear to have cloned an empty MediaWiki.\n";
833 # Something has to be done remote-helper side. If nothing is done, an error is
834 # thrown saying that HEAD is refering to unknown object 0000000000000000000
835 # and the clone fails.
839 sub mw_import_ref_by_pages
{
841 my $fetch_from = shift;
842 my %pages_hash = get_mw_pages
();
843 my @pages = values(%pages_hash);
845 my ($n, @revisions) = fetch_mw_revisions
(\
@pages, $fetch_from);
847 @revisions = sort {$a->{revid
} <=> $b->{revid
}} @revisions;
848 my @revision_ids = map $_->{revid
}, @revisions;
850 return mw_import_revids
($fetch_from, \
@revision_ids, \
%pages_hash);
853 sub mw_import_ref_by_revs
{
855 my $fetch_from = shift;
856 my %pages_hash = get_mw_pages
();
858 my $last_remote = get_last_global_remote_rev
();
859 my @revision_ids = $fetch_from..$last_remote;
860 return mw_import_revids
($fetch_from, \
@revision_ids, \
%pages_hash);
863 # Import revisions given in second argument (array of integers).
864 # Only pages appearing in the third argument (hash indexed by page titles)
866 sub mw_import_revids
{
867 my $fetch_from = shift;
868 my $revision_ids = shift;
873 my $last_timestamp = 0; # Placeholer in case $rev->timestamp is undefined
875 foreach my $pagerevid (@
$revision_ids) {
876 # fetch the content of the pages
880 rvprop
=> 'content|timestamp|comment|user|ids',
881 revids
=> $pagerevid,
884 my $result = $mediawiki->api($query);
887 die "Failed to retrieve modified page for revision $pagerevid";
890 if (!defined($result->{query
}->{pages
})) {
891 die "Invalid revision $pagerevid.";
894 my @result_pages = values(%{$result->{query
}->{pages
}});
895 my $result_page = $result_pages[0];
896 my $rev = $result_pages[0]->{revisions
}->[0];
898 # Count page even if we skip it, since we display
899 # $n/$total and $total includes skipped pages.
902 my $page_title = $result_page->{title
};
904 if (!exists($pages->{$page_title})) {
905 print STDERR
"$n/", scalar(@
$revision_ids),
906 ": Skipping revision #$rev->{revid} of $page_title\n";
913 $commit{author
} = $rev->{user
} || 'Anonymous';
914 $commit{comment
} = $rev->{comment
} || '*Empty MediaWiki Message*';
915 $commit{title
} = mediawiki_smudge_filename
($page_title);
916 $commit{mw_revision
} = $rev->{revid
};
917 $commit{content
} = mediawiki_smudge
($rev->{'*'});
919 if (!defined($rev->{timestamp
})) {
922 $last_timestamp = $rev->{timestamp
};
924 $commit{date
} = DateTime
::Format
::ISO8601
->parse_datetime($last_timestamp);
926 # Differentiates classic pages and media files.
927 my ($namespace, $filename) = $page_title =~ /^([^:]*):(.*)$/;
929 if ($namespace && get_mw_namespace_id
($namespace) == get_mw_namespace_id
("File")) {
930 %mediafile = get_mw_mediafile_for_page_revision
($filename, $rev->{timestamp
});
932 # If this is a revision of the media page for new version
933 # of a file do one common commit for both file and media page.
934 # Else do commit only for that page.
935 print STDERR
"$n/", scalar(@
$revision_ids), ": Revision #$rev->{revid} of $commit{title}\n";
936 import_file_revision
(\
%commit, ($fetch_from == 1), $n_actual, \
%mediafile);
942 sub error_non_fast_forward
{
943 my $advice = run_git
("config --bool advice.pushNonFastForward");
945 if ($advice ne "false") {
946 # Native git-push would show this after the summary.
947 # We can't ask it to display it cleanly, so print it
949 print STDERR
"To prevent you from losing history, non-fast-forward updates were rejected\n";
950 print STDERR
"Merge the remote changes (e.g. 'git pull') before pushing again. See the\n";
951 print STDERR
"'Note about fast-forwards' section of 'git push --help' for details.\n";
953 print STDOUT
"error $_[0] \"non-fast-forward\"\n";
958 my $complete_file_name = shift;
959 my $new_sha1 = shift;
960 my $extension = shift;
961 my $file_deleted = shift;
964 my $path = "File:" . $complete_file_name;
965 my %hashFiles = get_allowed_file_extensions
();
966 if (!exists($hashFiles{$extension})) {
967 print STDERR
"$complete_file_name is not a permitted file on this wiki.\n";
968 print STDERR
"Check the configuration of file uploads in your mediawiki.\n";
971 # Deleting and uploading a file requires a priviledged user
979 if (!$mediawiki->edit($query)) {
980 print STDERR
"Failed to delete file on remote wiki\n";
981 print STDERR
"Check your permissions on the remote site. Error code:\n";
982 print STDERR
$mediawiki->{error
}->{code
} . ':' . $mediawiki->{error
}->{details
};
986 # Don't let perl try to interpret file content as UTF-8 => use "raw"
987 my $content = run_git
("cat-file blob $new_sha1", "raw");
988 if ($content ne "") {
990 $mediawiki->{config
}->{upload_url
} =
991 "$url/index.php/Special:Upload";
994 filename
=> $complete_file_name,
998 Content
=> $content],
1002 } ) || die $mediawiki->{error
}->{code
} . ':'
1003 . $mediawiki->{error
}->{details
};
1004 my $last_file_page = $mediawiki->get_page({title
=> $path});
1005 $newrevid = $last_file_page->{revid
};
1006 print STDERR
"Pushed file: $new_sha1 - $complete_file_name.\n";
1008 print STDERR
"Empty file $complete_file_name not pushed.\n";
1015 my $diff_info = shift;
1016 # $diff_info contains a string in this format:
1017 # 100644 100644 <sha1_of_blob_before_commit> <sha1_of_blob_now> <status>
1018 my @diff_info_split = split(/[ \t]/, $diff_info);
1020 # Filename, including .mw extension
1021 my $complete_file_name = shift;
1023 my $summary = shift;
1024 # MediaWiki revision number. Keep the previous one by default,
1025 # in case there's no edit to perform.
1026 my $oldrevid = shift;
1029 my $new_sha1 = $diff_info_split[3];
1030 my $old_sha1 = $diff_info_split[2];
1031 my $page_created = ($old_sha1 eq NULL_SHA1
);
1032 my $page_deleted = ($new_sha1 eq NULL_SHA1
);
1033 $complete_file_name = mediawiki_clean_filename
($complete_file_name);
1035 my ($title, $extension) = $complete_file_name =~ /^(.*)\.([^\.]*)$/;
1036 if (!defined($extension)) {
1039 if ($extension eq "mw") {
1041 if ($page_deleted) {
1042 # Deleting a page usually requires
1043 # special priviledges. A common
1044 # convention is to replace the page
1045 # with this content instead:
1046 $file_content = DELETED_CONTENT
;
1048 $file_content = run_git
("cat-file blob $new_sha1");
1053 my $result = $mediawiki->edit( {
1055 summary
=> $summary,
1057 basetimestamp
=> $basetimestamps{$oldrevid},
1058 text
=> mediawiki_clean
($file_content, $page_created),
1060 skip_encoding
=> 1 # Helps with names with accentuated characters
1063 if ($mediawiki->{error
}->{code
} == 3) {
1064 # edit conflicts, considered as non-fast-forward
1065 print STDERR
'Warning: Error ' .
1066 $mediawiki->{error
}->{code
} .
1067 ' from mediwiki: ' . $mediawiki->{error
}->{details
} .
1069 return ($oldrevid, "non-fast-forward");
1071 # Other errors. Shouldn't happen => just die()
1072 die 'Fatal: Error ' .
1073 $mediawiki->{error
}->{code
} .
1074 ' from mediwiki: ' . $mediawiki->{error
}->{details
};
1077 $newrevid = $result->{edit
}->{newrevid
};
1078 print STDERR
"Pushed file: $new_sha1 - $title\n";
1080 $newrevid = mw_upload_file
($complete_file_name, $new_sha1,
1081 $extension, $page_deleted,
1084 $newrevid = ($newrevid or $oldrevid);
1085 return ($newrevid, "ok");
1089 # multiple push statements can follow each other
1090 my @refsspecs = (shift, get_more_refs
("push"));
1092 for my $refspec (@refsspecs) {
1093 my ($force, $local, $remote) = $refspec =~ /^(\+)?([^:]*):([^:]*)$/
1094 or die("Invalid refspec for push. Expected <src>:<dst> or +<src>:<dst>");
1096 print STDERR
"Warning: forced push not allowed on a MediaWiki.\n";
1099 print STDERR
"Cannot delete remote branch on a MediaWiki\n";
1100 print STDOUT
"error $remote cannot delete\n";
1103 if ($remote ne "refs/heads/master") {
1104 print STDERR
"Only push to the branch 'master' is supported on a MediaWiki\n";
1105 print STDOUT
"error $remote only master allowed\n";
1108 if (mw_push_revision
($local, $remote)) {
1113 # Notify Git that the push is done
1116 if ($pushed && $dumb_push) {
1117 print STDERR
"Just pushed some revisions to MediaWiki.\n";
1118 print STDERR
"The pushed revisions now have to be re-imported, and your current branch\n";
1119 print STDERR
"needs to be updated with these re-imported commits. You can do this with\n";
1121 print STDERR
" git pull --rebase\n";
1126 sub mw_push_revision
{
1128 my $remote = shift; # actually, this has to be "refs/heads/master" at this point.
1129 my $last_local_revid = get_last_local_revision
();
1130 print STDERR
".\n"; # Finish sentence started by get_last_local_revision()
1131 my $last_remote_revid = get_last_remote_revision
();
1132 my $mw_revision = $last_remote_revid;
1134 # Get sha1 of commit pointed by local HEAD
1135 my $HEAD_sha1 = run_git
("rev-parse $local 2>/dev/null"); chomp($HEAD_sha1);
1136 # Get sha1 of commit pointed by remotes/$remotename/master
1137 my $remoteorigin_sha1 = run_git
("rev-parse refs/remotes/$remotename/master 2>/dev/null");
1138 chomp($remoteorigin_sha1);
1140 if ($last_local_revid > 0 &&
1141 $last_local_revid < $last_remote_revid) {
1142 return error_non_fast_forward
($remote);
1145 if ($HEAD_sha1 eq $remoteorigin_sha1) {
1150 # Get every commit in between HEAD and refs/remotes/origin/master,
1151 # including HEAD and refs/remotes/origin/master
1152 my @commit_pairs = ();
1153 if ($last_local_revid > 0) {
1154 my $parsed_sha1 = $remoteorigin_sha1;
1155 # Find a path from last MediaWiki commit to pushed commit
1156 while ($parsed_sha1 ne $HEAD_sha1) {
1157 my @commit_info = grep(/^$parsed_sha1/, split(/\n/, run_git
("rev-list --children $local")));
1158 if (!@commit_info) {
1159 return error_non_fast_forward
($remote);
1161 my @commit_info_split = split(/ |\n/, $commit_info[0]);
1162 # $commit_info_split[1] is the sha1 of the commit to export
1163 # $commit_info_split[0] is the sha1 of its direct child
1164 push(@commit_pairs, \
@commit_info_split);
1165 $parsed_sha1 = $commit_info_split[1];
1168 # No remote mediawiki revision. Export the whole
1169 # history (linearized with --first-parent)
1170 print STDERR
"Warning: no common ancestor, pushing complete history\n";
1171 my $history = run_git
("rev-list --first-parent --children $local");
1172 my @history = split('\n', $history);
1173 @history = @history[1..$#history];
1174 foreach my $line (reverse @history) {
1175 my @commit_info_split = split(/ |\n/, $line);
1176 push(@commit_pairs, \
@commit_info_split);
1180 foreach my $commit_info_split (@commit_pairs) {
1181 my $sha1_child = @
{$commit_info_split}[0];
1182 my $sha1_commit = @
{$commit_info_split}[1];
1183 my $diff_infos = run_git
("diff-tree -r --raw -z $sha1_child $sha1_commit");
1184 # TODO: we could detect rename, and encode them with a #redirect on the wiki.
1185 # TODO: for now, it's just a delete+add
1186 my @diff_info_list = split(/\0/, $diff_infos);
1187 # Keep the subject line of the commit message as mediawiki comment for the revision
1188 my $commit_msg = run_git
("log --no-walk --format=\"%s\" $sha1_commit");
1191 while (@diff_info_list) {
1193 # git diff-tree -z gives an output like
1194 # <metadata>\0<filename1>\0
1195 # <metadata>\0<filename2>\0
1196 # and we've split on \0.
1197 my $info = shift(@diff_info_list);
1198 my $file = shift(@diff_info_list);
1199 ($mw_revision, $status) = mw_push_file
($info, $file, $commit_msg, $mw_revision);
1200 if ($status eq "non-fast-forward") {
1201 # we may already have sent part of the
1202 # commit to MediaWiki, but it's too
1203 # late to cancel it. Stop the push in
1204 # the middle, but still give an
1205 # accurate error message.
1206 return error_non_fast_forward
($remote);
1208 if ($status ne "ok") {
1209 die("Unknown error from mw_push_file()");
1212 unless ($dumb_push) {
1213 run_git
("notes --ref=$remotename/mediawiki add -m \"mediawiki_revision: $mw_revision\" $sha1_commit");
1214 run_git
("update-ref -m \"Git-MediaWiki push\" refs/mediawiki/$remotename/master $sha1_commit $sha1_child");
1218 print STDOUT
"ok $remote\n";
1222 sub get_allowed_file_extensions
{
1228 siprop
=> 'fileextensions'
1230 my $result = $mediawiki->api($query);
1231 my @file_extensions= map $_->{ext
},@
{$result->{query
}->{fileextensions
}};
1232 my %hashFile = map {$_ => 1}@file_extensions;
1237 # In memory cache for MediaWiki namespace ids.
1240 # Namespaces whose id is cached in the configuration file
1241 # (to avoid duplicates)
1242 my %cached_mw_namespace_id;
1244 # Return MediaWiki id for a canonical namespace name.
1245 # Ex.: "File", "Project".
1246 sub get_mw_namespace_id
{
1250 if (!exists $namespace_id{$name}) {
1251 # Look at configuration file, if the record for that namespace is
1252 # already cached. Namespaces are stored in form:
1253 # "Name_of_namespace:Id_namespace", ex.: "File:6".
1254 my @temp = split(/[ \n]/, run_git
("config --get-all remote."
1255 . $remotename .".namespaceCache"));
1257 foreach my $ns (@temp) {
1258 my ($n, $id) = split(/:/, $ns);
1259 $namespace_id{$n} = $id;
1260 $cached_mw_namespace_id{$n} = 1;
1264 if (!exists $namespace_id{$name}) {
1265 print STDERR
"Namespace $name not found in cache, querying the wiki ...\n";
1266 # NS not found => get namespace id from MW and store it in
1267 # configuration file.
1271 siprop
=> 'namespaces'
1273 my $result = $mediawiki->api($query);
1275 while (my ($id, $ns) = each(%{$result->{query
}->{namespaces
}})) {
1276 if (defined($ns->{id
}) && defined($ns->{canonical
})) {
1277 $namespace_id{$ns->{canonical
}} = $ns->{id
};
1279 # alias (e.g. french Fichier: as alias for canonical File:)
1280 $namespace_id{$ns->{'*'}} = $ns->{id
};
1286 my $id = $namespace_id{$name};
1289 # Store explicitely requested namespaces on disk
1290 if (!exists $cached_mw_namespace_id{$name}) {
1291 run_git
("config --add remote.". $remotename
1292 .".namespaceCache \"". $name .":". $id ."\"");
1293 $cached_mw_namespace_id{$name} = 1;
1297 die "No such namespace $name on MediaWiki.";