git-svn: introduce add_path_to_url function
[git.git] / perl / Git / SVN / Ra.pm
blobec3c570b216f55429be975d577ab4df6e07fcab7
1 package Git::SVN::Ra;
2 use vars qw/@ISA $config_dir $_ignore_refs_regex $_log_window_size/;
3 use strict;
4 use warnings;
5 use SVN::Client;
6 use Git::SVN::Utils qw(
7 canonicalize_url
8 add_path_to_url
9 );
11 use SVN::Ra;
12 BEGIN {
13 @ISA = qw(SVN::Ra);
16 my ($ra_invalid, $can_do_switch, %ignored_err, $RA);
18 BEGIN {
19 # enforce temporary pool usage for some simple functions
20 no strict 'refs';
21 for my $f (qw/rev_proplist get_latest_revnum get_uuid get_repos_root
22 get_file/) {
23 my $SUPER = "SUPER::$f";
24 *$f = sub {
25 my $self = shift;
26 my $pool = SVN::Pool->new;
27 my @ret = $self->$SUPER(@_,$pool);
28 $pool->clear;
29 wantarray ? @ret : $ret[0];
34 sub _auth_providers () {
35 my @rv = (
36 SVN::Client::get_simple_provider(),
37 SVN::Client::get_ssl_server_trust_file_provider(),
38 SVN::Client::get_simple_prompt_provider(
39 \&Git::SVN::Prompt::simple, 2),
40 SVN::Client::get_ssl_client_cert_file_provider(),
41 SVN::Client::get_ssl_client_cert_prompt_provider(
42 \&Git::SVN::Prompt::ssl_client_cert, 2),
43 SVN::Client::get_ssl_client_cert_pw_file_provider(),
44 SVN::Client::get_ssl_client_cert_pw_prompt_provider(
45 \&Git::SVN::Prompt::ssl_client_cert_pw, 2),
46 SVN::Client::get_username_provider(),
47 SVN::Client::get_ssl_server_trust_prompt_provider(
48 \&Git::SVN::Prompt::ssl_server_trust),
49 SVN::Client::get_username_prompt_provider(
50 \&Git::SVN::Prompt::username, 2)
53 # earlier 1.6.x versions would segfault, and <= 1.5.x didn't have
54 # this function
55 if (::compare_svn_version('1.6.15') >= 0) {
56 my $config = SVN::Core::config_get_config($config_dir);
57 my ($p, @a);
58 # config_get_config returns all config files from
59 # ~/.subversion, auth_get_platform_specific_client_providers
60 # just wants the config "file".
61 @a = ($config->{'config'}, undef);
62 $p = SVN::Core::auth_get_platform_specific_client_providers(@a);
63 # Insert the return value from
64 # auth_get_platform_specific_providers
65 unshift @rv, @$p;
67 \@rv;
71 sub new {
72 my ($class, $url) = @_;
73 $url = canonicalize_url($url);
74 return $RA if ($RA && $RA->url eq $url);
76 ::_req_svn();
78 SVN::_Core::svn_config_ensure($config_dir, undef);
79 my ($baton, $callbacks) = SVN::Core::auth_open_helper(_auth_providers);
80 my $config = SVN::Core::config_get_config($config_dir);
81 $RA = undef;
82 my $dont_store_passwords = 1;
83 my $conf_t = ${$config}{'config'};
85 no warnings 'once';
86 # The usage of $SVN::_Core::SVN_CONFIG_* variables
87 # produces warnings that variables are used only once.
88 # I had not found the better way to shut them up, so
89 # the warnings of type 'once' are disabled in this block.
90 if (SVN::_Core::svn_config_get_bool($conf_t,
91 $SVN::_Core::SVN_CONFIG_SECTION_AUTH,
92 $SVN::_Core::SVN_CONFIG_OPTION_STORE_PASSWORDS,
93 1) == 0) {
94 SVN::_Core::svn_auth_set_parameter($baton,
95 $SVN::_Core::SVN_AUTH_PARAM_DONT_STORE_PASSWORDS,
96 bless (\$dont_store_passwords, "_p_void"));
98 if (SVN::_Core::svn_config_get_bool($conf_t,
99 $SVN::_Core::SVN_CONFIG_SECTION_AUTH,
100 $SVN::_Core::SVN_CONFIG_OPTION_STORE_AUTH_CREDS,
101 1) == 0) {
102 $Git::SVN::Prompt::_no_auth_cache = 1;
104 } # no warnings 'once'
105 my $self = SVN::Ra->new(url => $url, auth => $baton,
106 config => $config,
107 pool => SVN::Pool->new,
108 auth_provider_callbacks => $callbacks);
109 $RA = bless $self, $class;
111 # Make sure its canonicalized
112 $self->url($url);
113 $self->{svn_path} = $url;
114 $self->{repos_root} = $self->get_repos_root;
115 $self->{svn_path} =~ s#^\Q$self->{repos_root}\E(/|$)##;
116 $self->{cache} = { check_path => { r => 0, data => {} },
117 get_dir => { r => 0, data => {} } };
119 return $RA;
122 sub url {
123 my $self = shift;
125 if (@_) {
126 my $url = shift;
127 $self->{url} = canonicalize_url($url);
128 return;
131 return $self->{url};
134 sub check_path {
135 my ($self, $path, $r) = @_;
136 my $cache = $self->{cache}->{check_path};
137 if ($r == $cache->{r} && exists $cache->{data}->{$path}) {
138 return $cache->{data}->{$path};
140 my $pool = SVN::Pool->new;
141 my $t = $self->SUPER::check_path($path, $r, $pool);
142 $pool->clear;
143 if ($r != $cache->{r}) {
144 %{$cache->{data}} = ();
145 $cache->{r} = $r;
147 $cache->{data}->{$path} = $t;
150 sub get_dir {
151 my ($self, $dir, $r) = @_;
152 my $cache = $self->{cache}->{get_dir};
153 if ($r == $cache->{r}) {
154 if (my $x = $cache->{data}->{$dir}) {
155 return wantarray ? @$x : $x->[0];
158 my $pool = SVN::Pool->new;
159 my ($d, undef, $props) = $self->SUPER::get_dir($dir, $r, $pool);
160 my %dirents = map { $_ => { kind => $d->{$_}->kind } } keys %$d;
161 $pool->clear;
162 if ($r != $cache->{r}) {
163 %{$cache->{data}} = ();
164 $cache->{r} = $r;
166 $cache->{data}->{$dir} = [ \%dirents, $r, $props ];
167 wantarray ? (\%dirents, $r, $props) : \%dirents;
170 sub DESTROY {
171 # do not call the real DESTROY since we store ourselves in $RA
174 # get_log(paths, start, end, limit,
175 # discover_changed_paths, strict_node_history, receiver)
176 sub get_log {
177 my ($self, @args) = @_;
178 my $pool = SVN::Pool->new;
180 # svn_log_changed_path_t objects passed to get_log are likely to be
181 # overwritten even if only the refs are copied to an external variable,
182 # so we should dup the structures in their entirety. Using an
183 # externally passed pool (instead of our temporary and quickly cleared
184 # pool in Git::SVN::Ra) does not help matters at all...
185 my $receiver = pop @args;
186 my $prefix = "/".$self->{svn_path};
187 $prefix =~ s#/+($)##;
188 my $prefix_regex = qr#^\Q$prefix\E#;
189 push(@args, sub {
190 my ($paths) = $_[0];
191 return &$receiver(@_) unless $paths;
192 $_[0] = ();
193 foreach my $p (keys %$paths) {
194 my $i = $paths->{$p};
195 # Make path relative to our url, not repos_root
196 $p =~ s/$prefix_regex//;
197 my %s = map { $_ => $i->$_; }
198 qw/copyfrom_path copyfrom_rev action/;
199 if ($s{'copyfrom_path'}) {
200 $s{'copyfrom_path'} =~ s/$prefix_regex//;
202 $_[0]{$p} = \%s;
204 &$receiver(@_);
208 # the limit parameter was not supported in SVN 1.1.x, so we
209 # drop it. Therefore, the receiver callback passed to it
210 # is made aware of this limitation by being wrapped if
211 # the limit passed to is being wrapped.
212 if (::compare_svn_version('1.2.0') <= 0) {
213 my $limit = splice(@args, 3, 1);
214 if ($limit > 0) {
215 my $receiver = pop @args;
216 push(@args, sub { &$receiver(@_) if (--$limit >= 0) });
219 my $ret = $self->SUPER::get_log(@args, $pool);
220 $pool->clear;
221 $ret;
224 sub trees_match {
225 my ($self, $url1, $rev1, $url2, $rev2) = @_;
226 my $ctx = SVN::Client->new(auth => _auth_providers);
227 my $out = IO::File->new_tmpfile;
229 # older SVN (1.1.x) doesn't take $pool as the last parameter for
230 # $ctx->diff(), so we'll create a default one
231 my $pool = SVN::Pool->new_default_sub;
233 $ra_invalid = 1; # this will open a new SVN::Ra connection to $url1
234 $ctx->diff([], $url1, $rev1, $url2, $rev2, 1, 1, 0, $out, $out);
235 $out->flush;
236 my $ret = (($out->stat)[7] == 0);
237 close $out or croak $!;
239 $ret;
242 sub get_commit_editor {
243 my ($self, $log, $cb, $pool) = @_;
245 my @lock = (::compare_svn_version('1.2.0') >= 0) ? (undef, 0) : ();
246 $self->SUPER::get_commit_editor($log, $cb, @lock, $pool);
249 sub gs_do_update {
250 my ($self, $rev_a, $rev_b, $gs, $editor) = @_;
251 my $new = ($rev_a == $rev_b);
252 my $path = $gs->path;
254 if ($new && -e $gs->{index}) {
255 unlink $gs->{index} or die
256 "Couldn't unlink index: $gs->{index}: $!\n";
258 my $pool = SVN::Pool->new;
259 $editor->set_path_strip($path);
260 my (@pc) = split m#/#, $path;
261 my $reporter = $self->do_update($rev_b, (@pc ? shift @pc : ''),
262 1, $editor, $pool);
263 my @lock = (::compare_svn_version('1.2.0') >= 0) ? (undef) : ();
265 # Since we can't rely on svn_ra_reparent being available, we'll
266 # just have to do some magic with set_path to make it so
267 # we only want a partial path.
268 my $sp = '';
269 my $final = join('/', @pc);
270 while (@pc) {
271 $reporter->set_path($sp, $rev_b, 0, @lock, $pool);
272 $sp .= '/' if length $sp;
273 $sp .= shift @pc;
275 die "BUG: '$sp' != '$final'\n" if ($sp ne $final);
277 $reporter->set_path($sp, $rev_a, $new, @lock, $pool);
279 $reporter->finish_report($pool);
280 $pool->clear;
281 $editor->{git_commit_ok};
284 # this requires SVN 1.4.3 or later (do_switch didn't work before 1.4.3, and
285 # svn_ra_reparent didn't work before 1.4)
286 sub gs_do_switch {
287 my ($self, $rev_a, $rev_b, $gs, $url_b, $editor) = @_;
288 my $path = $gs->path;
289 my $pool = SVN::Pool->new;
291 my $old_url = $self->url;
292 my $full_url = add_path_to_url( $self->url, $path );
293 my ($ra, $reparented);
295 if ($old_url =~ m#^svn(\+ssh)?://# ||
296 ($full_url =~ m#^https?://# &&
297 canonicalize_url($full_url) ne $full_url)) {
298 $_[0] = undef;
299 $self = undef;
300 $RA = undef;
301 $ra = Git::SVN::Ra->new($full_url);
302 $ra_invalid = 1;
303 } elsif ($old_url ne $full_url) {
304 SVN::_Ra::svn_ra_reparent($self->{session}, $full_url, $pool);
305 $self->url($full_url);
306 $reparented = 1;
309 $ra ||= $self;
310 $url_b = canonicalize_url($url_b);
311 my $reporter = $ra->do_switch($rev_b, '', 1, $url_b, $editor, $pool);
312 my @lock = (::compare_svn_version('1.2.0') >= 0) ? (undef) : ();
313 $reporter->set_path('', $rev_a, 0, @lock, $pool);
314 $reporter->finish_report($pool);
316 if ($reparented) {
317 SVN::_Ra::svn_ra_reparent($self->{session}, $old_url, $pool);
318 $self->url($old_url);
321 $pool->clear;
322 $editor->{git_commit_ok};
325 sub longest_common_path {
326 my ($gsv, $globs) = @_;
327 my %common;
328 my $common_max = scalar @$gsv;
330 foreach my $gs (@$gsv) {
331 my @tmp = split m#/#, $gs->path;
332 my $p = '';
333 foreach (@tmp) {
334 $p .= length($p) ? "/$_" : $_;
335 $common{$p} ||= 0;
336 $common{$p}++;
339 $globs ||= [];
340 $common_max += scalar @$globs;
341 foreach my $glob (@$globs) {
342 my @tmp = split m#/#, $glob->{path}->{left};
343 my $p = '';
344 foreach (@tmp) {
345 $p .= length($p) ? "/$_" : $_;
346 $common{$p} ||= 0;
347 $common{$p}++;
351 my $longest_path = '';
352 foreach (sort {length $b <=> length $a} keys %common) {
353 if ($common{$_} == $common_max) {
354 $longest_path = $_;
355 last;
358 $longest_path;
361 sub gs_fetch_loop_common {
362 my ($self, $base, $head, $gsv, $globs) = @_;
363 return if ($base > $head);
364 my $inc = $_log_window_size;
365 my ($min, $max) = ($base, $head < $base + $inc ? $head : $base + $inc);
366 my $longest_path = longest_common_path($gsv, $globs);
367 my $ra_url = $self->url;
368 my $find_trailing_edge;
369 while (1) {
370 my %revs;
371 my $err;
372 my $err_handler = $SVN::Error::handler;
373 $SVN::Error::handler = sub {
374 ($err) = @_;
375 skip_unknown_revs($err);
377 sub _cb {
378 my ($paths, $r, $author, $date, $log) = @_;
379 [ $paths,
380 { author => $author, date => $date, log => $log } ];
382 $self->get_log([$longest_path], $min, $max, 0, 1, 1,
383 sub { $revs{$_[1]} = _cb(@_) });
384 if ($err) {
385 print "Checked through r$max\r";
386 } else {
387 $find_trailing_edge = 1;
389 if ($err and $find_trailing_edge) {
390 print STDERR "Path '$longest_path' ",
391 "was probably deleted:\n",
392 $err->expanded_message,
393 "\nWill attempt to follow ",
394 "revisions r$min .. r$max ",
395 "committed before the deletion\n";
396 my $hi = $max;
397 while (--$hi >= $min) {
398 my $ok;
399 $self->get_log([$longest_path], $min, $hi,
400 0, 1, 1, sub {
401 $ok = $_[1];
402 $revs{$_[1]} = _cb(@_) });
403 if ($ok) {
404 print STDERR "r$min .. r$ok OK\n";
405 last;
408 $find_trailing_edge = 0;
410 $SVN::Error::handler = $err_handler;
412 my %exists = map { $_->{path} => $_ } @$gsv;
413 foreach my $r (sort {$a <=> $b} keys %revs) {
414 my ($paths, $logged) = @{$revs{$r}};
416 foreach my $gs ($self->match_globs(\%exists, $paths,
417 $globs, $r)) {
418 if ($gs->rev_map_max >= $r) {
419 next;
421 next unless $gs->match_paths($paths, $r);
422 $gs->{logged_rev_props} = $logged;
423 if (my $last_commit = $gs->last_commit) {
424 $gs->assert_index_clean($last_commit);
426 my $log_entry = $gs->do_fetch($paths, $r);
427 if ($log_entry) {
428 $gs->do_git_commit($log_entry);
430 $Git::SVN::INDEX_FILES{$gs->{index}} = 1;
432 foreach my $g (@$globs) {
433 my $k = "svn-remote.$g->{remote}." .
434 "$g->{t}-maxRev";
435 Git::SVN::tmp_config($k, $r);
437 if ($ra_invalid) {
438 $_[0] = undef;
439 $self = undef;
440 $RA = undef;
441 $self = Git::SVN::Ra->new($ra_url);
442 $ra_invalid = undef;
445 # pre-fill the .rev_db since it'll eventually get filled in
446 # with '0' x40 if something new gets committed
447 foreach my $gs (@$gsv) {
448 next if $gs->rev_map_max >= $max;
449 next if defined $gs->rev_map_get($max);
450 $gs->rev_map_set($max, 0 x40);
452 foreach my $g (@$globs) {
453 my $k = "svn-remote.$g->{remote}.$g->{t}-maxRev";
454 Git::SVN::tmp_config($k, $max);
456 last if $max >= $head;
457 $min = $max + 1;
458 $max += $inc;
459 $max = $head if ($max > $head);
461 Git::SVN::gc();
464 sub get_dir_globbed {
465 my ($self, $left, $depth, $r) = @_;
467 my @x = eval { $self->get_dir($left, $r) };
468 return unless scalar @x == 3;
469 my $dirents = $x[0];
470 my @finalents;
471 foreach my $de (keys %$dirents) {
472 next if $dirents->{$de}->{kind} != $SVN::Node::dir;
473 if ($depth > 1) {
474 my @args = ("$left/$de", $depth - 1, $r);
475 foreach my $dir ($self->get_dir_globbed(@args)) {
476 push @finalents, "$de/$dir";
478 } else {
479 push @finalents, $de;
482 @finalents;
485 # return value: 0 -- don't ignore, 1 -- ignore
486 sub is_ref_ignored {
487 my ($g, $p) = @_;
488 my $refname = $g->{ref}->full_path($p);
489 return 1 if defined($g->{ignore_refs_regex}) &&
490 $refname =~ m!$g->{ignore_refs_regex}!;
491 return 0 unless defined($_ignore_refs_regex);
492 return 1 if $refname =~ m!$_ignore_refs_regex!o;
493 return 0;
496 sub match_globs {
497 my ($self, $exists, $paths, $globs, $r) = @_;
499 sub get_dir_check {
500 my ($self, $exists, $g, $r) = @_;
502 my @dirs = $self->get_dir_globbed($g->{path}->{left},
503 $g->{path}->{depth},
504 $r);
506 foreach my $de (@dirs) {
507 my $p = $g->{path}->full_path($de);
508 next if $exists->{$p};
509 next if (length $g->{path}->{right} &&
510 ($self->check_path($p, $r) !=
511 $SVN::Node::dir));
512 next unless $p =~ /$g->{path}->{regex}/;
513 $exists->{$p} = Git::SVN->init($self->url, $p, undef,
514 $g->{ref}->full_path($de), 1);
517 foreach my $g (@$globs) {
518 if (my $path = $paths->{"/$g->{path}->{left}"}) {
519 if ($path->{action} =~ /^[AR]$/) {
520 get_dir_check($self, $exists, $g, $r);
523 foreach (keys %$paths) {
524 if (/$g->{path}->{left_regex}/ &&
525 !/$g->{path}->{regex}/) {
526 next if $paths->{$_}->{action} !~ /^[AR]$/;
527 get_dir_check($self, $exists, $g, $r);
529 next unless /$g->{path}->{regex}/;
530 my $p = $1;
531 my $pathname = $g->{path}->full_path($p);
532 next if is_ref_ignored($g, $p);
533 next if $exists->{$pathname};
534 next if ($self->check_path($pathname, $r) !=
535 $SVN::Node::dir);
536 $exists->{$pathname} = Git::SVN->init(
537 $self->url, $pathname, undef,
538 $g->{ref}->full_path($p), 1);
540 my $c = '';
541 foreach (split m#/#, $g->{path}->{left}) {
542 $c .= "/$_";
543 next unless ($paths->{$c} &&
544 ($paths->{$c}->{action} =~ /^[AR]$/));
545 get_dir_check($self, $exists, $g, $r);
548 values %$exists;
551 sub minimize_url {
552 my ($self) = @_;
553 return $self->url if ($self->url eq $self->{repos_root});
554 my $url = $self->{repos_root};
555 my @components = split(m!/!, $self->{svn_path});
556 my $c = '';
557 do {
558 $url = add_path_to_url($url, $c);
559 eval {
560 my $ra = (ref $self)->new($url);
561 my $latest = $ra->get_latest_revnum;
562 $ra->get_log("", $latest, 0, 1, 0, 1, sub {});
564 } while ($@ && ($c = shift @components));
566 return canonicalize_url($url);
569 sub can_do_switch {
570 my $self = shift;
571 unless (defined $can_do_switch) {
572 my $pool = SVN::Pool->new;
573 my $rep = eval {
574 $self->do_switch(1, '', 0, $self->url,
575 SVN::Delta::Editor->new, $pool);
577 if ($@) {
578 $can_do_switch = 0;
579 } else {
580 $rep->abort_report($pool);
581 $can_do_switch = 1;
583 $pool->clear;
585 $can_do_switch;
588 sub skip_unknown_revs {
589 my ($err) = @_;
590 my $errno = $err->apr_err();
591 # Maybe the branch we're tracking didn't
592 # exist when the repo started, so it's
593 # not an error if it doesn't, just continue
595 # Wonderfully consistent library, eh?
596 # 160013 - svn:// and file://
597 # 175002 - http(s)://
598 # 175007 - http(s):// (this repo required authorization, too...)
599 # More codes may be discovered later...
600 if ($errno == 175007 || $errno == 175002 || $errno == 160013) {
601 my $err_key = $err->expanded_message;
602 # revision numbers change every time, filter them out
603 $err_key =~ s/\d+/\0/g;
604 $err_key = "$errno\0$err_key";
605 unless ($ignored_err{$err_key}) {
606 warn "W: Ignoring error from SVN, path probably ",
607 "does not exist: ($errno): ",
608 $err->expanded_message,"\n";
609 warn "W: Do not be alarmed at the above message ",
610 "git-svn is just searching aggressively for ",
611 "old history.\n",
612 "This may take a while on large repositories\n";
613 $ignored_err{$err_key} = 1;
615 return;
617 die "Error from SVN, ($errno): ", $err->expanded_message,"\n";
621 __END__
623 Git::SVN::Ra - Subversion remote access functions for git-svn
625 =head1 SYNOPSIS
627 use Git::SVN::Ra;
629 my $ra = Git::SVN::Ra->new($branchurl);
630 my ($dirents, $fetched_revnum, $props) =
631 $ra->get_dir('.', $SVN::Core::INVALID_REVNUM);
633 =head1 DESCRIPTION
635 This is a wrapper around the L<SVN::Ra> module for use by B<git-svn>.
636 It fills in some default parameters (such as the authentication
637 scheme), smooths over incompatibilities between libsvn versions, adds
638 caching, and implements some functions specific to B<git-svn>.
640 Do not use it unless you are developing git-svn. The interface will
641 change as git-svn evolves.
643 =head1 DEPENDENCIES
645 Subversion perl bindings,
646 L<Git::SVN>.
648 C<Git::SVN::Ra> has not been tested using callers other than
649 B<git-svn> itself.
651 =head1 SEE ALSO
653 L<SVN::Ra>.
655 =head1 INCOMPATIBILITIES
657 None reported.
659 =head1 BUGS
661 None.