]> git.ipfire.org Git - thirdparty/git.git/blame - git-svn.perl
INSTALL: update asciidoc recommendation
[thirdparty/git.git] / git-svn.perl
CommitLineData
0754e089 1#!/usr/bin/perl
551ce28f
EW
2# Copyright (C) 2006, Eric Wong <normalperson@yhbt.net>
3# License: GPL v2 or later
d48b2841 4use 5.008;
3397f9df
EW
5use warnings;
6use strict;
7use vars qw/ $AUTHOR $VERSION
ffe256f9 8 $sha1 $sha1_short $_revision $_repository
36db1edd 9 $_q $_authors $_authors_prog %users/;
3397f9df 10$AUTHOR = 'Eric Wong <normalperson@yhbt.net>';
60d02ccc 11$VERSION = '@@GIT_VERSION@@';
13ccd6d4 12
15153451
BS
13# From which subdir have we been invoked?
14my $cmd_dir_prefix = eval {
15 command_oneline([qw/rev-parse --show-prefix/], STDERR => 0)
16} || '';
17
5253dc33 18my $git_dir_user_set = 1 if defined $ENV{GIT_DIR};
706587fc 19$ENV{GIT_DIR} ||= '.git';
9fa00b65 20$Git::SVN::default_repo_id = 'svn';
8b8fc068 21$Git::SVN::default_ref_id = $ENV{GIT_SVN_ID} || 'git-svn';
6af1db44 22$Git::SVN::Ra::_log_window_size = 100;
6b48829d 23$Git::SVN::_minimize_url = 'unset';
13ccd6d4 24
184892fb
SS
25if (! exists $ENV{SVN_SSH} && exists $ENV{GIT_SSH}) {
26 $ENV{SVN_SSH} = $ENV{GIT_SSH};
27}
28
29if (exists $ENV{SVN_SSH} && $^O eq 'msys') {
30 $ENV{SVN_SSH} =~ s/\\/\\\\/g;
31 $ENV{SVN_SSH} =~ s/(.*)/"$1"/;
f3a87d92
K
32}
33
f8c9d1d2 34$Git::SVN::Log::TZ = $ENV{TZ};
3397f9df 35$ENV{TZ} = 'UTC';
a00439ac 36$| = 1; # unbuffer STDOUT
3397f9df 37
207f1a75 38sub fatal (@) { print STDERR "@_\n"; exit 1 }
6ade9bda
RK
39
40# All SVN commands do it. Otherwise we may die on SIGPIPE when the remote
41# repository decides to close the connection which we expect to be kept alive.
42$SIG{PIPE} = 'IGNORE';
43
f760c903
JH
44# Given a dot separated version number, "subtract" it from
45# the SVN::Core::VERSION; non-negaitive return means the SVN::Core
46# is at least at the version the caller asked for.
47sub compare_svn_version {
48 my (@ours) = split(/\./, $SVN::Core::VERSION);
49 my (@theirs) = split(/\./, $_[0]);
50 my ($i, $diff);
51
52 for ($i = 0; $i < @ours && $i < @theirs; $i++) {
53 $diff = $ours[$i] - $theirs[$i];
54 return $diff if ($diff);
55 }
56 return 1 if ($i < @ours);
57 return -1 if ($i < @theirs);
58 return 0;
59}
60
d32fad2b 61sub _req_svn {
62 require SVN::Core; # use()-ing this causes segfaults for me... *shrug*
63 require SVN::Ra;
64 require SVN::Delta;
f760c903 65 if (::compare_svn_version('1.1.0') < 0) {
d32fad2b 66 fatal "Need SVN::Core 1.1.0 or better (got $SVN::Core::VERSION)";
67 }
b9c85187 68}
2da9ee08 69my $can_compress = eval { require Compress::Zlib; 1};
d81bf827 70push @Git::SVN::Ra::ISA, 'SVN::Ra';
72827aa4 71push @Git::SVN::Editor::ISA, 'SVN::Delta::Editor';
3397f9df 72use Carp qw/croak/;
8d7c4fad 73use Digest::MD5;
3397f9df
EW
74use IO::File qw//;
75use File::Basename qw/dirname basename/;
76use File::Path qw/mkpath/;
36db1edd 77use File::Spec;
2da9ee08 78use File::Find;
512b620b 79use Getopt::Long qw/:config gnu_getopt no_ignore_case auto_abbrev/;
968bdf1f 80use IPC::Open3;
336f1714 81use Git;
a6180325 82use Git::SVN::Fetcher qw//;
c102f4cf 83use Git::SVN::Prompt qw//;
f5549afd 84use Memoize; # core since 5.8.0, Jul 2002
a5e0cedc 85
336f1714 86BEGIN {
c5f71ad0
SV
87 # import functions from Git into our packages, en masse
88 no strict 'refs';
336f1714 89 foreach (qw/command command_oneline command_noisy command_output_pipe
6ea42032
BB
90 command_input_pipe command_close_pipe
91 command_bidi_pipe command_close_bidi_pipe/) {
a6180325 92 for my $package ( qw(Git::SVN::Editor
8d7c4fad 93 Git::SVN::Migration Git::SVN::Log Git::SVN),
c5f71ad0
SV
94 __PACKAGE__) {
95 *{"${package}::$_"} = \&{"Git::$_"};
96 }
336f1714 97 }
f5549afd
JK
98 Memoize::memoize 'Git::config';
99 Memoize::memoize 'Git::config_bool';
336f1714
EW
100}
101
b9c85187 102my ($SVN);
83e9940a 103
f8c9d1d2
EW
104$sha1 = qr/[a-f\d]{40}/;
105$sha1_short = qr/[a-f\d]{4,40}/;
44320b9e 106my ($_stdin, $_help, $_edit,
62244069 107 $_message, $_file, $_branch_dest,
d05d72e0 108 $_template, $_shared,
c2abd83f 109 $_version, $_fetch_all, $_no_rebase, $_fetch_parent,
b64e1f58 110 $_merge, $_strategy, $_preserve_merges, $_dry_run, $_local,
4be40381 111 $_prefix, $_no_checkout, $_url, $_verbose,
afd7f1eb 112 $_git_format, $_commit_url, $_tag, $_merge_info, $_interactive);
0bed5eaa 113$Git::SVN::_follow_parent = 1;
72827aa4 114$Git::SVN::Fetcher::_placeholder_filename = ".gitignore";
49750f30 115$_q ||= 0;
706587fc
EW
116my %remote_opts = ( 'username=s' => \$Git::SVN::Prompt::_username,
117 'config-dir=s' => \$Git::SVN::Ra::config_dir,
edc662f9 118 'no-auth-cache' => \$Git::SVN::Prompt::_no_auth_cache,
72827aa4 119 'ignore-paths=s' => \$Git::SVN::Fetcher::_ignore_regex,
cdb51a13 120 'ignore-refs=s' => \$Git::SVN::Ra::_ignore_refs_regex );
0bed5eaa 121my %fc_opts = ( 'follow-parent|follow!' => \$Git::SVN::_follow_parent,
dc5869c0 122 'authors-file|A=s' => \$_authors,
36db1edd 123 'authors-prog=s' => \$_authors_prog,
ecc712dd 124 'repack:i' => \$Git::SVN::_repack,
97ae0911
EW
125 'noMetadata' => \$Git::SVN::_no_metadata,
126 'useSvmProps' => \$Git::SVN::_use_svm_props,
62e349d2 127 'useSvnsyncProps' => \$Git::SVN::_use_svnsync_props,
6af1db44 128 'log-window-size=i' => \$Git::SVN::Ra::_log_window_size,
1e889ef3 129 'no-checkout' => \$_no_checkout,
49750f30 130 'quiet|q+' => \$_q,
ecc712dd
EW
131 'repack-flags|repack-args|repack-opts=s' =>
132 \$Git::SVN::_repack_flags,
70ae04e4 133 'use-log-author' => \$Git::SVN::_use_log_author,
6aa9ba14 134 'add-author-from' => \$Git::SVN::_add_author_from,
e82f0d73 135 'localtime' => \$Git::SVN::_localtime,
706587fc 136 %remote_opts );
36f5b1f0 137
62244069 138my ($_trunk, @_tags, @_branches, $_stdlayout);
0dfaf0a4 139my %icv;
dadc6d2a 140my %init_opts = ( 'template=s' => \$_template, 'shared:s' => \$_shared,
62244069
MB
141 'trunk|T=s' => \$_trunk, 'tags|t=s@' => \@_tags,
142 'branches|b=s@' => \@_branches, 'prefix=s' => \$_prefix,
8f728fb9 143 'stdlayout|s' => \$_stdlayout,
6b48829d 144 'minimize-url|m!' => \$Git::SVN::_minimize_url,
0dfaf0a4
EW
145 'no-metadata' => sub { $icv{noMetadata} = 1 },
146 'use-svm-props' => sub { $icv{useSvmProps} = 1 },
147 'use-svnsync-props' => sub { $icv{useSvnsyncProps} = 1 },
148 'rewrite-root=s' => sub { $icv{rewriteRoot} = $_[1] },
3e18ce1a 149 'rewrite-uuid=s' => sub { $icv{rewriteUUID} = $_[1] },
dadc6d2a 150 %remote_opts );
27e9fb8d 151my %cmt_opts = ( 'edit|e' => \$_edit,
72827aa4
JN
152 'rmdir' => \$Git::SVN::Editor::_rmdir,
153 'find-copies-harder' => \$Git::SVN::Editor::_find_copies_harder,
154 'l=i' => \$Git::SVN::Editor::_rename_limit,
155 'copy-similarity|C=i'=> \$Git::SVN::Editor::_cp_similarity
27e9fb8d 156);
9d55b41a 157
3397f9df 158my %cmd = (
2a3240be 159 fetch => [ \&cmd_fetch, "Download new revisions from SVN",
e98671e5 160 { 'revision|r=s' => \$_revision,
905f8b7d 161 'fetch-all|all' => \$_fetch_all,
c2abd83f 162 'parent|p' => \$_fetch_parent,
e98671e5 163 %fc_opts } ],
0425ea90
EW
164 clone => [ \&cmd_clone, "Initialize and fetch revisions",
165 { 'revision|r=s' => \$_revision,
40a1530c 166 'preserve-empty-dirs' =>
72827aa4 167 \$Git::SVN::Fetcher::_preserve_empty_dirs,
40a1530c 168 'placeholder-filename=s' =>
72827aa4 169 \$Git::SVN::Fetcher::_placeholder_filename,
0425ea90 170 %fc_opts, %init_opts } ],
d2866f9e 171 init => [ \&cmd_init, "Initialize a repo for tracking" .
f8ab6b73 172 " (requires URL argument)",
9d55b41a 173 \%init_opts ],
dadc6d2a
EW
174 'multi-init' => [ \&cmd_multi_init,
175 "Deprecated alias for ".
176 "'$0 init -T<trunk> -b<branches> -t<tags>'",
177 \%init_opts ],
d7ad3bed
EW
178 dcommit => [ \&cmd_dcommit,
179 'Commit several diffs to merge with upstream',
3289e86e
EW
180 { 'merge|m|M' => \$_merge,
181 'strategy|s=s' => \$_strategy,
905f8b7d 182 'verbose|v' => \$_verbose,
3289e86e 183 'dry-run|n' => \$_dry_run,
905f8b7d 184 'fetch-all|all' => \$_fetch_all,
ba24e745
EW
185 'commit-url=s' => \$_commit_url,
186 'revision|r=i' => \$_revision,
171af110 187 'no-rebase' => \$_no_rebase,
6abd9332 188 'mergeinfo=s' => \$_merge_info,
afd7f1eb 189 'interactive|i' => \$_interactive,
4b155223 190 %cmt_opts, %fc_opts } ],
5de70efb
FR
191 branch => [ \&cmd_branch,
192 'Create a branch in the SVN repository',
193 { 'message|m=s' => \$_message,
62244069 194 'destination|d=s' => \$_branch_dest,
5de70efb 195 'dry-run|n' => \$_dry_run,
6594f0b7
IM
196 'tag|t' => \$_tag,
197 'username=s' => \$Git::SVN::Prompt::_username,
198 'commit-url=s' => \$_commit_url } ],
5de70efb
FR
199 tag => [ sub { $_tag = 1; cmd_branch(@_) },
200 'Create a tag in the SVN repository',
201 { 'message|m=s' => \$_message,
62244069 202 'destination|d=s' => \$_branch_dest,
6594f0b7
IM
203 'dry-run|n' => \$_dry_run,
204 'username=s' => \$Git::SVN::Prompt::_username,
205 'commit-url=s' => \$_commit_url } ],
1ce255dc
EW
206 'set-tree' => [ \&cmd_set_tree,
207 "Set an SVN repository to a git tree-ish",
e84dc6df 208 { 'stdin' => \$_stdin, %cmt_opts, %fc_opts, } ],
d05ddec5
BS
209 'create-ignore' => [ \&cmd_create_ignore,
210 'Create a .gitignore per svn:ignore',
211 { 'revision|r=i' => \$_revision
212 } ],
6111b934
EW
213 'mkdirs' => [ \&cmd_mkdirs ,
214 "recreate empty directories after a checkout",
215 { 'revision|r=i' => \$_revision } ],
15153451
BS
216 'propget' => [ \&cmd_propget,
217 'Print the value of a property on a file or directory',
218 { 'revision|r=i' => \$_revision } ],
51e057cf
BS
219 'proplist' => [ \&cmd_proplist,
220 'List all properties of a file or directory',
221 { 'revision|r=i' => \$_revision } ],
5969cbe1 222 'show-ignore' => [ \&cmd_show_ignore, "Show svn:ignore listings",
4dbfe2e9 223 { 'revision|r=i' => \$_revision
05b4df31 224 } ],
2d879792
VK
225 'show-externals' => [ \&cmd_show_externals, "Show svn:externals listings",
226 { 'revision|r=i' => \$_revision
227 } ],
1c8443b0 228 'multi-fetch' => [ \&cmd_multi_fetch,
e98671e5
EW
229 "Deprecated alias for $0 fetch --all",
230 { 'revision|r=s' => \$_revision, %fc_opts } ],
706587fc
EW
231 'migrate' => [ sub { },
232 # no-op, we automatically run this anyways,
706587fc
EW
233 'Migrate configuration/metadata/layout from
234 previous versions of git-svn',
a836a0e1
EW
235 { 'minimize' => \$Git::SVN::Migration::_minimize,
236 %remote_opts } ],
f8c9d1d2
EW
237 'log' => [ \&Git::SVN::Log::cmd_show_log, 'Show commit logs',
238 { 'limit=i' => \$Git::SVN::Log::limit,
79bb8d88 239 'revision|r=s' => \$_revision,
f8c9d1d2
EW
240 'verbose|v' => \$Git::SVN::Log::verbose,
241 'incremental' => \$Git::SVN::Log::incremental,
242 'oneline' => \$Git::SVN::Log::oneline,
243 'show-commit' => \$Git::SVN::Log::show_commit,
244 'non-recursive' => \$Git::SVN::Log::non_recursive,
79bb8d88 245 'authors-file|A=s' => \$_authors,
f8c9d1d2 246 'color' => \$Git::SVN::Log::color,
4dbfe2e9 247 'pager=s' => \$Git::SVN::Log::pager
79bb8d88 248 } ],
222566e4
EW
249 'find-rev' => [ \&cmd_find_rev,
250 "Translate between SVN revision numbers and tree-ish",
4dbfe2e9 251 {} ],
905f8b7d
EW
252 'rebase' => [ \&cmd_rebase, "Fetch and rebase your working directory",
253 { 'merge|m|M' => \$_merge,
254 'verbose|v' => \$_verbose,
255 'strategy|s=s' => \$_strategy,
dee41f3e 256 'local|l' => \$_local,
905f8b7d 257 'fetch-all|all' => \$_fetch_all,
7d45e146 258 'dry-run|n' => \$_dry_run,
b64e1f58 259 'preserve-merges|p' => \$_preserve_merges,
905f8b7d 260 %fc_opts } ],
44320b9e
EW
261 'commit-diff' => [ \&cmd_commit_diff,
262 'Commit a diff between two trees',
27e9fb8d
EW
263 { 'message|m=s' => \$_message,
264 'file|F=s' => \$_file,
45bf473a 265 'revision|r=s' => \$_revision,
27e9fb8d 266 %cmt_opts } ],
e6fefa92
DK
267 'info' => [ \&cmd_info,
268 "Show info about the latest SVN revision
269 on the current branch",
8b014d71 270 { 'url' => \$_url, } ],
6fb5375e
TS
271 'blame' => [ \&Git::SVN::Log::cmd_blame,
272 "Show what revision and author last modified each line of a file",
4be40381 273 { 'git-format' => \$_git_format } ],
195643f2
BJ
274 'reset' => [ \&cmd_reset,
275 "Undo fetches back to the specified SVN revision",
276 { 'revision|r=s' => \$_revision,
277 'parent|p' => \$_fetch_parent } ],
2da9ee08
RZ
278 'gc' => [ \&cmd_gc,
279 "Compress unhandled.log files in .git/svn and remove " .
280 "index files in .git/svn",
281 {} ],
3397f9df 282);
9d55b41a 283
afd7f1eb
FH
284use Term::ReadLine;
285package FakeTerm;
286sub new {
287 my ($class, $reason) = @_;
288 return bless \$reason, shift;
289}
290sub readline {
291 my $self = shift;
292 die "Cannot use readline on FakeTerm: $$self";
293}
294package main;
295
296my $term = eval {
297 $ENV{"GIT_SVN_NOTTY"}
298 ? new Term::ReadLine 'git-svn', \*STDIN, \*STDOUT
299 : new Term::ReadLine 'git-svn';
300};
301if ($@) {
302 $term = new FakeTerm "$@: going non-interactive";
303}
304
3397f9df
EW
305my $cmd;
306for (my $i = 0; $i < @ARGV; $i++) {
307 if (defined $cmd{$ARGV[$i]}) {
308 $cmd = $ARGV[$i];
309 splice @ARGV, $i, 1;
310 last;
9a8c92ac
BJ
311 } elsif ($ARGV[$i] eq 'help') {
312 $cmd = $ARGV[$i+1];
313 usage(0);
3397f9df
EW
314 }
315};
316
540424b2
EW
317# make sure we're always running at the top-level working directory
318unless ($cmd && $cmd =~ /(?:clone|init|multi-init)$/) {
5253dc33
EW
319 unless (-d $ENV{GIT_DIR}) {
320 if ($git_dir_user_set) {
321 die "GIT_DIR=$ENV{GIT_DIR} explicitly set, ",
322 "but it is not a directory\n";
323 }
324 my $git_dir = delete $ENV{GIT_DIR};
fe4003f6
DM
325 my $cdup = undef;
326 git_cmd_try {
327 $cdup = command_oneline(qw/rev-parse --show-cdup/);
328 $git_dir = '.' unless ($cdup);
329 chomp $cdup if ($cdup);
330 $cdup = "." unless ($cdup && length $cdup);
331 } "Already at toplevel, but $git_dir not found\n";
5253dc33
EW
332 chdir $cdup or die "Unable to chdir up to '$cdup'\n";
333 unless (-d $git_dir) {
334 die "$git_dir still not found after going to ",
335 "'$cdup'\n";
336 }
337 $ENV{GIT_DIR} = $git_dir;
338 }
ffe256f9 339 $_repository = Git->repository(Repository => $ENV{GIT_DIR});
5253dc33 340}
f4dd334b
GH
341
342my %opts = %{$cmd{$cmd}->[2]} if (defined $cmd);
343
1a30582b 344read_git_config(\%opts);
222566e4
EW
345if ($cmd && ($cmd eq 'log' || $cmd eq 'blame')) {
346 Getopt::Long::Configure('pass_through');
347}
87182b17 348my $rv = GetOptions(%opts, 'h|H' => \$_help, 'version|V' => \$_version,
f4dd334b
GH
349 'minimize-connections' => \$Git::SVN::Migration::_minimize,
350 'id|i=s' => \$Git::SVN::default_ref_id,
351 'svn-remote|remote|R=s' => sub {
352 $Git::SVN::no_reuse_existing = 1;
353 $Git::SVN::default_repo_id = $_[1] });
354exit 1 if (!$rv && $cmd && $cmd ne 'log');
355
356usage(0) if $_help;
357version() if $_version;
358usage(1) unless defined $cmd;
359load_authors() if $_authors;
36db1edd
ML
360if (defined $_authors_prog) {
361 $_authors_prog = "'" . File::Spec->rel2abs($_authors_prog) . "'";
362}
f4dd334b 363
0425ea90 364unless ($cmd =~ /^(?:clone|init|multi-init|commit-diff)$/) {
706587fc
EW
365 Git::SVN::Migration::migration_check();
366}
ecc712dd 367Git::SVN::init_vars();
b805b44a
EW
368eval {
369 Git::SVN::verify_remotes_sanity();
370 $cmd{$cmd}->[0]->(@ARGV);
371};
372fatal $@ if $@;
1e889ef3 373post_fetch_checkout();
3397f9df
EW
374exit 0;
375
376####################### primary functions ######################
377sub usage {
378 my $exit = shift || 0;
379 my $fd = $exit ? \*STDERR : \*STDOUT;
380 print $fd <<"";
381git-svn - bidirectional operations between a single Subversion tree and git
1b1dd23f 382Usage: git svn <command> [options] [arguments]\n
448c81b4
EW
383
384 print $fd "Available commands:\n" unless $cmd;
3397f9df
EW
385
386 foreach (sort keys %cmd) {
448c81b4 387 next if $cmd && $cmd ne $_;
a836a0e1 388 next if /^multi-/; # don't show deprecated commands
b203b769 389 print $fd ' ',pack('A17',$_),$cmd{$_}->[1],"\n";
aa807bc2 390 foreach (sort keys %{$cmd{$_}->[2]}) {
512b620b
EW
391 # mixed-case options are for .git/config only
392 next if /[A-Z]/ && /^[a-z]+$/i;
448c81b4 393 # prints out arguments as they should be passed:
b8c92cad 394 my $x = s#[:=]s$## ? '<arg>' : s#[:=]i$## ? '<num>' : '';
b203b769 395 print $fd ' ' x 21, join(', ', map { length $_ > 1 ?
448c81b4
EW
396 "--$_" : "-$_" }
397 split /\|/,$_)," $x\n";
398 }
3397f9df
EW
399 }
400 print $fd <<"";
448c81b4
EW
401\nGIT_SVN_ID may be set in the environment or via the --id/-i switch to an
402arbitrary identifier if you're tracking multiple SVN branches/repositories in
403one git repository and want to keep them separate. See git-svn(1) for more
404information.
3397f9df
EW
405
406 exit $exit;
407}
408
551ce28f 409sub version {
b0779246 410 ::_req_svn();
7d60ab2c 411 print "git-svn version $VERSION (svn $SVN::Core::VERSION)\n";
551ce28f
EW
412 exit 0;
413}
414
afd7f1eb
FH
415sub ask {
416 my ($prompt, %arg) = @_;
417 my $valid_re = $arg{valid_re};
418 my $default = $arg{default};
419 my $resp;
420 my $i = 0;
421
422 if ( !( defined($term->IN)
423 && defined( fileno($term->IN) )
424 && defined( $term->OUT )
425 && defined( fileno($term->OUT) ) ) ){
426 return defined($default) ? $default : undef;
427 }
428
429 while ($i++ < 10) {
430 $resp = $term->readline($prompt);
431 if (!defined $resp) { # EOF
432 print "\n";
433 return defined $default ? $default : undef;
434 }
435 if ($resp eq '' and defined $default) {
436 return $default;
437 }
438 if (!defined $valid_re or $resp =~ /$valid_re/) {
439 return $resp;
440 }
441 }
442 return undef;
443}
444
8164b652
EW
445sub do_git_init_db {
446 unless (-d $ENV{GIT_DIR}) {
447 my @init_db = ('init');
448 push @init_db, "--template=$_template" if defined $_template;
dadc6d2a
EW
449 if (defined $_shared) {
450 if ($_shared =~ /[a-z]/) {
451 push @init_db, "--shared=$_shared";
452 } else {
453 push @init_db, "--shared";
454 }
455 }
8164b652 456 command_noisy(@init_db);
ffe256f9 457 $_repository = Git->repository(Repository => ".git");
8164b652 458 }
0dfaf0a4
EW
459 my $set;
460 my $pfx = "svn-remote.$Git::SVN::default_repo_id";
461 foreach my $i (keys %icv) {
462 die "'$set' and '$i' cannot both be set\n" if $set;
463 next unless defined $icv{$i};
464 command_noisy('config', "$pfx.$i", $icv{$i});
465 $set = $i;
466 }
72827aa4 467 my $ignore_paths_regex = \$Git::SVN::Fetcher::_ignore_regex;
cdb51a13
MO
468 command_noisy('config', "$pfx.ignore-paths", $$ignore_paths_regex)
469 if defined $$ignore_paths_regex;
470 my $ignore_refs_regex = \$Git::SVN::Ra::_ignore_refs_regex;
471 command_noisy('config', "$pfx.ignore-refs", $$ignore_refs_regex)
472 if defined $$ignore_refs_regex;
40a1530c 473
72827aa4
JN
474 if (defined $Git::SVN::Fetcher::_preserve_empty_dirs) {
475 my $fname = \$Git::SVN::Fetcher::_placeholder_filename;
40a1530c
RC
476 command_noisy('config', "$pfx.preserve-empty-dirs", 'true');
477 command_noisy('config', "$pfx.placeholder-filename", $$fname);
478 }
8164b652
EW
479}
480
dadc6d2a
EW
481sub init_subdir {
482 my $repo_path = shift or return;
483 mkpath([$repo_path]) unless -d $repo_path;
484 chdir $repo_path or die "Couldn't chdir to $repo_path: $!\n";
f30603fc 485 $ENV{GIT_DIR} = '.git';
ffe256f9 486 $_repository = Git->repository(Repository => $ENV{GIT_DIR});
dadc6d2a
EW
487}
488
0425ea90
EW
489sub cmd_clone {
490 my ($url, $path) = @_;
491 if (!defined $path &&
62244069 492 (defined $_trunk || @_branches || @_tags ||
8f728fb9 493 defined $_stdlayout) &&
0425ea90
EW
494 $url !~ m#^[a-z\+]+://#) {
495 $path = $url;
496 }
0425ea90 497 $path = basename($url) if !defined $path || !length $path;
2bc35dcb 498 my $authors_absolute = $_authors ? File::Spec->rel2abs($_authors) : "";
f30603fc 499 cmd_init($url, $path);
2bc35dcb
AV
500 command_oneline('config', 'svn.authorsfile', $authors_absolute)
501 if $_authors;
f5841509 502 Git::SVN::fetch_all($Git::SVN::default_repo_id);
0425ea90
EW
503}
504
d2866f9e 505sub cmd_init {
8f728fb9 506 if (defined $_stdlayout) {
507 $_trunk = 'trunk' if (!defined $_trunk);
62244069
MB
508 @_tags = 'tags' if (! @_tags);
509 @_branches = 'branches' if (! @_branches);
8f728fb9 510 }
62244069 511 if (defined $_trunk || @_branches || @_tags) {
dadc6d2a 512 return cmd_multi_init(@_);
03e0ea87 513 }
dadc6d2a
EW
514 my $url = shift or die "SVN repository location required ",
515 "as a command-line argument\n";
50ff2366 516 $url = canonicalize_url($url);
dadc6d2a 517 init_subdir(@_);
8164b652 518 do_git_init_db();
03e0ea87 519
6b48829d
EW
520 if ($Git::SVN::_minimize_url eq 'unset') {
521 $Git::SVN::_minimize_url = 0;
522 }
523
706587fc 524 Git::SVN->init($url);
3397f9df
EW
525}
526
2a3240be 527sub cmd_fetch {
e98671e5
EW
528 if (grep /^\d+=./, @_) {
529 die "'<rev>=<commit>' fetch arguments are ",
530 "no longer supported.\n";
07a1c950 531 }
e98671e5
EW
532 my ($remote) = @_;
533 if (@_ > 1) {
c2abd83f 534 die "Usage: $0 fetch [--all] [--parent] [svn-remote]\n";
e98671e5 535 }
4d0157d6 536 $Git::SVN::no_reuse_existing = undef;
c2abd83f
JM
537 if ($_fetch_parent) {
538 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
539 unless ($gs) {
540 die "Unable to determine upstream SVN information from ",
541 "working tree history\n";
542 }
543 # just fetch, don't checkout.
544 $_no_checkout = 'true';
545 $_fetch_all ? $gs->fetch_all : $gs->fetch;
546 } elsif ($_fetch_all) {
e98671e5
EW
547 cmd_multi_fetch();
548 } else {
c2abd83f 549 $remote ||= $Git::SVN::default_repo_id;
e98671e5 550 Git::SVN::fetch_all($remote, Git::SVN::read_all_remotes());
1c8443b0 551 }
2a3240be
EW
552}
553
1ce255dc 554sub cmd_set_tree {
3397f9df
EW
555 my (@commits) = @_;
556 if ($_stdin || !@commits) {
557 print "Reading from stdin...\n";
558 @commits = ();
559 while (<STDIN>) {
1ca72aef 560 if (/\b($sha1_short)\b/o) {
3397f9df
EW
561 unshift @commits, $1;
562 }
563 }
564 }
565 my @revs;
8de010ad 566 foreach my $c (@commits) {
aef4e921 567 my @tmp = command('rev-parse',$c);
8de010ad
EW
568 if (scalar @tmp == 1) {
569 push @revs, $tmp[0];
570 } elsif (scalar @tmp > 1) {
aef4e921 571 push @revs, reverse(command('rev-list',@tmp));
8de010ad 572 } else {
207f1a75 573 fatal "Failed to rev-parse $c";
8de010ad 574 }
3397f9df 575 }
1ce255dc
EW
576 my $gs = Git::SVN->new;
577 my ($r_last, $cmt_last) = $gs->last_rev_commit;
578 $gs->fetch;
97f6987a 579 if (defined $gs->{last_rev} && $r_last != $gs->{last_rev}) {
1ce255dc
EW
580 fatal "There are new revisions that were fetched ",
581 "and need to be merged (or acknowledged) ",
582 "before committing.\nlast rev: $r_last\n",
207f1a75 583 " current: $gs->{last_rev}";
a5e0cedc 584 }
1ce255dc
EW
585 $gs->set_tree($_) foreach @revs;
586 print "Done committing ",scalar @revs," revisions to SVN\n";
3157dd9e 587 unlink $gs->{index};
a5e0cedc 588}
8f22562c 589
1e5814f3
BJ
590sub split_merge_info_range {
591 my ($range) = @_;
592 if ($range =~ /(\d+)-(\d+)/) {
593 return (int($1), int($2));
594 } else {
595 return (int($range), int($range));
596 }
597}
598
599sub combine_ranges {
600 my ($in) = @_;
601
602 my @fnums = ();
603 my @arr = split(/,/, $in);
604 for my $element (@arr) {
605 my ($start, $end) = split_merge_info_range($element);
606 push @fnums, $start;
607 }
608
609 my @sorted = @arr [ sort {
610 $fnums[$a] <=> $fnums[$b]
611 } 0..$#arr ];
612
613 my @return = ();
614 my $last = -1;
615 my $first = -1;
616 for my $element (@sorted) {
617 my ($start, $end) = split_merge_info_range($element);
618
619 if ($last == -1) {
620 $first = $start;
621 $last = $end;
622 next;
623 }
624 if ($start <= $last+1) {
625 if ($end > $last) {
626 $last = $end;
627 }
628 next;
629 }
630 if ($first == $last) {
631 push @return, "$first";
632 } else {
633 push @return, "$first-$last";
634 }
635 $first = $start;
636 $last = $end;
637 }
638
639 if ($first != -1) {
640 if ($first == $last) {
641 push @return, "$first";
642 } else {
643 push @return, "$first-$last";
644 }
645 }
646
647 return join(',', @return);
648}
649
650sub merge_revs_into_hash {
651 my ($hash, $minfo) = @_;
652 my @lines = split(' ', $minfo);
653
654 for my $line (@lines) {
655 my ($branchpath, $revs) = split(/:/, $line);
656
657 if (exists($hash->{$branchpath})) {
658 # Merge the two revision sets
659 my $combined = "$hash->{$branchpath},$revs";
660 $hash->{$branchpath} = combine_ranges($combined);
661 } else {
662 # Just do range combining for consolidation
663 $hash->{$branchpath} = combine_ranges($revs);
664 }
665 }
666}
667
668sub merge_merge_info {
669 my ($mergeinfo_one, $mergeinfo_two) = @_;
670 my %result_hash = ();
671
672 merge_revs_into_hash(\%result_hash, $mergeinfo_one);
673 merge_revs_into_hash(\%result_hash, $mergeinfo_two);
674
675 my $result = '';
676 # Sort below is for consistency's sake
677 for my $branchname (sort keys(%result_hash)) {
678 my $revlist = $result_hash{$branchname};
679 $result .= "$branchname:$revlist\n"
680 }
681 return $result;
682}
683
684sub populate_merge_info {
685 my ($d, $gs, $uuid, $linear_refs, $rewritten_parent) = @_;
686
687 my %parentshash;
688 read_commit_parents(\%parentshash, $d);
689 my @parents = @{$parentshash{$d}};
690 if ($#parents > 0) {
691 # Merge commit
692 my $all_parents_ok = 1;
693 my $aggregate_mergeinfo = '';
694 my $rooturl = $gs->repos_root;
695
696 if (defined($rewritten_parent)) {
697 # Replace first parent with newly-rewritten version
698 shift @parents;
699 unshift @parents, $rewritten_parent;
700 }
701
702 foreach my $parent (@parents) {
703 my ($branchurl, $svnrev, $paruuid) =
704 cmt_metadata($parent);
705
706 unless (defined($svnrev)) {
707 # Should have been caught be preflight check
708 fatal "merge commit $d has ancestor $parent, but that change "
709 ."does not have git-svn metadata!";
710 }
0e7e30f5 711 unless ($branchurl =~ /^\Q$rooturl\E(.*)/) {
1e5814f3
BJ
712 fatal "commit $parent git-svn metadata changed mid-run!";
713 }
714 my $branchpath = $1;
715
716 my $ra = Git::SVN::Ra->new($branchurl);
717 my (undef, undef, $props) =
718 $ra->get_dir(canonicalize_path("."), $svnrev);
719 my $par_mergeinfo = $props->{'svn:mergeinfo'};
720 unless (defined $par_mergeinfo) {
721 $par_mergeinfo = '';
722 }
723 # Merge previous mergeinfo values
724 $aggregate_mergeinfo =
725 merge_merge_info($aggregate_mergeinfo,
726 $par_mergeinfo, 0);
727
728 next if $parent eq $parents[0]; # Skip first parent
729 # Add new changes being placed in tree by merge
730 my @cmd = (qw/rev-list --reverse/,
731 $parent, qw/--not/);
732 foreach my $par (@parents) {
733 unless ($par eq $parent) {
734 push @cmd, $par;
735 }
736 }
737 my @revsin = ();
738 my ($revlist, $ctx) = command_output_pipe(@cmd);
739 while (<$revlist>) {
740 my $irev = $_;
741 chomp $irev;
742 my (undef, $csvnrev, undef) =
743 cmt_metadata($irev);
744 unless (defined $csvnrev) {
745 # A child is missing SVN annotations...
746 # this might be OK, or might not be.
747 warn "W:child $irev is merged into revision "
748 ."$d but does not have git-svn metadata. "
749 ."This means git-svn cannot determine the "
750 ."svn revision numbers to place into the "
751 ."svn:mergeinfo property. You must ensure "
752 ."a branch is entirely committed to "
753 ."SVN before merging it in order for "
754 ."svn:mergeinfo population to function "
755 ."properly";
756 }
757 push @revsin, $csvnrev;
758 }
759 command_close_pipe($revlist, $ctx);
760
761 last unless $all_parents_ok;
762
763 # We now have a list of all SVN revnos which are
764 # merged by this particular parent. Integrate them.
765 next if $#revsin == -1;
766 my $newmergeinfo = "$branchpath:" . join(',', @revsin);
767 $aggregate_mergeinfo =
768 merge_merge_info($aggregate_mergeinfo,
769 $newmergeinfo, 1);
770 }
771 if ($all_parents_ok and $aggregate_mergeinfo) {
772 return $aggregate_mergeinfo;
773 }
774 }
775
776 return undef;
777}
778
d7ad3bed
EW
779sub cmd_dcommit {
780 my $head = shift;
181264ad 781 command_noisy(qw/update-index --refresh/);
c8cfa3e4 782 git_cmd_try { command_oneline(qw/diff-index --quiet HEAD/) }
826a9339 783 'Cannot dcommit with a dirty index. Commit your changes first, '
c8cfa3e4 784 . "or stash them with `git stash'.\n";
d7ad3bed 785 $head ||= 'HEAD';
5eec27e3
TR
786
787 my $old_head;
788 if ($head ne 'HEAD') {
789 $old_head = eval {
790 command_oneline([qw/symbolic-ref -q HEAD/])
791 };
792 if ($old_head) {
793 $old_head =~ s{^refs/heads/}{};
794 } else {
795 $old_head = eval { command_oneline(qw/rev-parse HEAD/) };
796 }
797 command(['checkout', $head], STDERR => 0);
798 }
799
a8ae2623 800 my @refs;
5eec27e3 801 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD', \@refs);
2cb61105
TR
802 unless ($gs) {
803 die "Unable to determine upstream SVN information from ",
804 "$head history.\nPerhaps the repository is empty.";
805 }
0df84059
PO
806
807 if (defined $_commit_url) {
808 $url = $_commit_url;
809 } else {
810 $url = eval { command_oneline('config', '--get',
811 "svn-remote.$gs->{repo_id}.commiturl") };
812 if (!$url) {
12a296bc 813 $url = $gs->full_pushurl
0df84059
PO
814 }
815 }
816
ba24e745 817 my $last_rev = $_revision if defined $_revision;
59b0c24d
MM
818 if ($url) {
819 print "Committing to $url ...\n";
820 }
733a65aa 821 my ($linear_refs, $parents) = linearize_history($gs, \@refs);
751eb395
EW
822 if ($_no_rebase && scalar(@$linear_refs) > 1) {
823 warn "Attempting to commit more than one change while ",
824 "--no-rebase is enabled.\n",
825 "If these changes depend on each other, re-running ",
7dfa16b9 826 "without --no-rebase may be required."
751eb395 827 }
afd7f1eb
FH
828
829 if (defined $_interactive){
830 my $ask_default = "y";
831 foreach my $d (@$linear_refs){
832 my ($fh, $ctx) = command_output_pipe(qw(show --summary), "$d");
833 while (<$fh>){
834 print $_;
835 }
836 command_close_pipe($fh, $ctx);
837 $_ = ask("Commit this patch to SVN? ([y]es (default)|[n]o|[q]uit|[a]ll): ",
838 valid_re => qr/^(?:yes|y|no|n|quit|q|all|a)/i,
839 default => $ask_default);
840 die "Commit this patch reply required" unless defined $_;
841 if (/^[nq]/i) {
842 exit(0);
843 } elsif (/^a/i) {
844 last;
845 }
846 }
847 }
848
711521e2 849 my $expect_url = $url;
1e5814f3
BJ
850
851 my $push_merge_info = eval {
852 command_oneline(qw/config --get svn.pushmergeinfo/)
853 };
854 if (not defined($push_merge_info)
855 or $push_merge_info eq "false"
856 or $push_merge_info eq "no"
857 or $push_merge_info eq "never") {
858 $push_merge_info = 0;
859 }
860
861 unless (defined($_merge_info) || ! $push_merge_info) {
862 # Preflight check of changes to ensure no issues with mergeinfo
863 # This includes check for uncommitted-to-SVN parents
864 # (other than the first parent, which we will handle),
865 # information from different SVN repos, and paths
866 # which are not underneath this repository root.
867 my $rooturl = $gs->repos_root;
868 foreach my $d (@$linear_refs) {
869 my %parentshash;
870 read_commit_parents(\%parentshash, $d);
871 my @realparents = @{$parentshash{$d}};
872 if ($#realparents > 0) {
873 # Merge commit
874 shift @realparents; # Remove/ignore first parent
875 foreach my $parent (@realparents) {
876 my ($branchurl, $svnrev, $paruuid) = cmt_metadata($parent);
877 unless (defined $paruuid) {
878 # A parent is missing SVN annotations...
879 # abort the whole operation.
880 fatal "$parent is merged into revision $d, "
881 ."but does not have git-svn metadata. "
882 ."Either dcommit the branch or use a "
883 ."local cherry-pick, FF merge, or rebase "
884 ."instead of an explicit merge commit.";
885 }
886
887 unless ($paruuid eq $uuid) {
888 # Parent has SVN metadata from different repository
889 fatal "merge parent $parent for change $d has "
890 ."git-svn uuid $paruuid, while current change "
891 ."has uuid $uuid!";
892 }
893
0e7e30f5 894 unless ($branchurl =~ /^\Q$rooturl\E(.*)/) {
1e5814f3
BJ
895 # This branch is very strange indeed.
896 fatal "merge parent $parent for $d is on branch "
897 ."$branchurl, which is not under the "
898 ."git-svn root $rooturl!";
899 }
900 }
901 }
902 }
903 }
904
905 my $rewritten_parent;
711521e2 906 Git::SVN::remove_username($expect_url);
98c4ab32
BJ
907 if (defined($_merge_info)) {
908 $_merge_info =~ tr{ }{\n};
909 }
c74d9acf
EW
910 while (1) {
911 my $d = shift @$linear_refs or last;
45bf473a
EW
912 unless (defined $last_rev) {
913 (undef, $last_rev, undef) = cmt_metadata("$d~1");
914 unless (defined $last_rev) {
d7ad3bed 915 fatal "Unable to extract revision information ",
207f1a75 916 "from commit $d~1";
45bf473a
EW
917 }
918 }
b22d4497
EW
919 if ($_dry_run) {
920 print "diff-tree $d~1 $d\n";
921 } else {
751eb395 922 my $cmt_rev;
1e5814f3
BJ
923
924 unless (defined($_merge_info) || ! $push_merge_info) {
925 $_merge_info = populate_merge_info($d, $gs,
926 $uuid,
927 $linear_refs,
928 $rewritten_parent);
929 }
930
d7ad3bed 931 my %ed_opts = ( r => $last_rev,
61395354 932 log => get_commit_entry($d)->{log},
ba24e745 933 ra => Git::SVN::Ra->new($url),
3caf320b
KA
934 config => SVN::Core::config_get_config(
935 $Git::SVN::Ra::config_dir
936 ),
61395354
EW
937 tree_a => "$d~1",
938 tree_b => $d,
939 editor_cb => sub {
940 print "Committed r$_[0]\n";
751eb395
EW
941 $cmt_rev = $_[0];
942 },
6abd9332 943 mergeinfo => $_merge_info,
a8ae2623 944 svn_path => '');
72827aa4 945 if (!Git::SVN::Editor->new(\%ed_opts)->apply_diff) {
d7ad3bed 946 print "No changes\n$d~1 == $d\n";
733a65aa 947 } elsif ($parents->{$d} && @{$parents->{$d}}) {
751eb395 948 $gs->{inject_parents_dcommit}->{$cmt_rev} =
733a65aa 949 $parents->{$d};
d7ad3bed 950 }
751eb395 951 $_fetch_all ? $gs->fetch_all : $gs->fetch;
7dfa16b9 952 $last_rev = $cmt_rev;
751eb395
EW
953 next if $_no_rebase;
954
955 # we always want to rebase against the current HEAD,
956 # not any head that was passed to us
c74d9acf 957 my @diff = command('diff-tree', $d,
751eb395
EW
958 $gs->refname, '--');
959 my @finish;
960 if (@diff) {
961 @finish = rebase_cmd();
c74d9acf 962 print STDERR "W: $d and ", $gs->refname,
751eb395 963 " differ, using @finish:\n",
c74d9acf 964 join("\n", @diff), "\n";
751eb395
EW
965 } else {
966 print "No changes between current HEAD and ",
967 $gs->refname,
968 "\nResetting to the latest ",
969 $gs->refname, "\n";
970 @finish = qw/reset --mixed/;
971 }
972 command_noisy(@finish, $gs->refname);
1e5814f3
BJ
973
974 $rewritten_parent = command_oneline(qw/rev-parse HEAD/);
975
c74d9acf
EW
976 if (@diff) {
977 @refs = ();
978 my ($url_, $rev_, $uuid_, $gs_) =
5eec27e3 979 working_head_info('HEAD', \@refs);
c74d9acf
EW
980 my ($linear_refs_, $parents_) =
981 linearize_history($gs_, \@refs);
982 if (scalar(@$linear_refs) !=
983 scalar(@$linear_refs_)) {
984 fatal "# of revisions changed ",
985 "\nbefore:\n",
986 join("\n", @$linear_refs),
987 "\n\nafter:\n",
988 join("\n", @$linear_refs_), "\n",
989 'If you are attempting to commit ',
990 "merges, try running:\n\t",
991 'git rebase --interactive',
992 '--preserve-merges ',
993 $gs->refname,
994 "\nBefore dcommitting";
995 }
711521e2 996 if ($url_ ne $expect_url) {
c03c1f79
AG
997 if ($url_ eq $gs->metadata_url) {
998 print
999 "Accepting rewritten URL:",
1000 " $url_\n";
1001 } else {
1002 fatal
1003 "URL mismatch after rebase:",
1004 " $url_ != $expect_url";
1005 }
c74d9acf
EW
1006 }
1007 if ($uuid_ ne $uuid) {
1008 fatal "uuid mismatch after rebase: ",
1009 "$uuid_ != $uuid";
1010 }
1011 # remap parents
1012 my (%p, @l, $i);
1013 for ($i = 0; $i < scalar @$linear_refs; $i++) {
1014 my $new = $linear_refs_->[$i] or next;
1015 $p{$new} =
1016 $parents->{$linear_refs->[$i]};
1017 push @l, $new;
1018 }
1019 $parents = \%p;
1020 $linear_refs = \@l;
1021 }
b22d4497
EW
1022 }
1023 }
5eec27e3
TR
1024
1025 if ($old_head) {
1026 my $new_head = command_oneline(qw/rev-parse HEAD/);
1027 my $new_is_symbolic = eval {
1028 command_oneline(qw/symbolic-ref -q HEAD/);
1029 };
1030 if ($new_is_symbolic) {
1031 print "dcommitted the branch ", $head, "\n";
1032 } else {
1033 print "dcommitted on a detached HEAD because you gave ",
1034 "a revision argument.\n",
1035 "The rewritten commit is: ", $new_head, "\n";
1036 }
1037 command(['checkout', $old_head], STDERR => 0);
1038 }
1039
3157dd9e 1040 unlink $gs->{index};
b22d4497
EW
1041}
1042
5de70efb
FR
1043sub cmd_branch {
1044 my ($branch_name, $head) = @_;
1045
1046 unless (defined $branch_name && length $branch_name) {
1047 die(($_tag ? "tag" : "branch") . " name required\n");
1048 }
1049 $head ||= 'HEAD';
1050
150d38c4 1051 my (undef, $rev, undef, $gs) = working_head_info($head);
12a296bc 1052 my $src = $gs->full_pushurl;
5de70efb 1053
a0fbc87c 1054 my $remote = Git::SVN::read_all_remotes()->{$gs->{repo_id}};
62244069
MB
1055 my $allglobs = $remote->{ $_tag ? 'tags' : 'branches' };
1056 my $glob;
1057 if ($#{$allglobs} == 0) {
1058 $glob = $allglobs->[0];
1059 } else {
1060 unless(defined $_branch_dest) {
1061 die "Multiple ",
1062 $_tag ? "tag" : "branch",
1063 " paths defined for Subversion repository.\n",
1064 "You must specify where you want to create the ",
1065 $_tag ? "tag" : "branch",
1066 " with the --destination argument.\n";
1067 }
1068 foreach my $g (@{$allglobs}) {
72827aa4
JN
1069 # Git::SVN::Editor could probably be moved to Git.pm..
1070 my $re = Git::SVN::Editor::glob2pat($g->{path}->{left});
f7050599 1071 if ($_branch_dest =~ /$re/) {
62244069
MB
1072 $glob = $g;
1073 last;
1074 }
1075 }
1076 unless (defined $glob) {
eaa14ff8
EW
1077 my $dest_re = qr/\b\Q$_branch_dest\E\b/;
1078 foreach my $g (@{$allglobs}) {
1079 $g->{path}->{left} =~ /$dest_re/ or next;
1080 if (defined $glob) {
1081 die "Ambiguous destination: ",
1082 $_branch_dest, "\nmatches both '",
1083 $glob->{path}->{left}, "' and '",
1084 $g->{path}->{left}, "'\n";
1085 }
1086 $glob = $g;
1087 }
1088 unless (defined $glob) {
1089 die "Unknown ",
1090 $_tag ? "tag" : "branch",
1091 " destination $_branch_dest\n";
1092 }
62244069
MB
1093 }
1094 }
5de70efb 1095 my ($lft, $rgt) = @{ $glob->{path} }{qw/left right/};
99bacd6c
IM
1096 my $url;
1097 if (defined $_commit_url) {
1098 $url = $_commit_url;
1099 } else {
1100 $url = eval { command_oneline('config', '--get',
1101 "svn-remote.$gs->{repo_id}.commiturl") };
1102 if (!$url) {
12a296bc 1103 $url = $remote->{pushurl} || $remote->{url};
99bacd6c
IM
1104 }
1105 }
1106 my $dst = join '/', $url, $lft, $branch_name, ($rgt || ());
5de70efb 1107
a83b91e7
IM
1108 if ($dst =~ /^https:/ && $src =~ /^http:/) {
1109 $src=~s/^http:/https:/;
1110 }
1111
d32fad2b 1112 ::_req_svn();
1113
5de70efb
FR
1114 my $ctx = SVN::Client->new(
1115 auth => Git::SVN::Ra::_auth_providers(),
1116 log_msg => sub {
1117 ${ $_[0] } = defined $_message
1118 ? $_message
1119 : 'Create ' . ($_tag ? 'tag ' : 'branch ' )
1120 . $branch_name;
1121 },
1122 );
1123
1124 eval {
1125 $ctx->ls($dst, 'HEAD', 0);
1126 } and die "branch ${branch_name} already exists\n";
1127
1128 print "Copying ${src} at r${rev} to ${dst}...\n";
1129 $ctx->copy($src, $rev, $dst)
1130 unless $_dry_run;
1131
1132 $gs->fetch_all;
1133}
1134
26e60160 1135sub cmd_find_rev {
ea14e6c5
MAL
1136 my $revision_or_hash = shift or die "SVN or git revision required ",
1137 "as a command-line argument\n";
26e60160
AR
1138 my $result;
1139 if ($revision_or_hash =~ /^r\d+$/) {
b3cb7e45
AR
1140 my $head = shift;
1141 $head ||= 'HEAD';
1142 my @refs;
63c56022 1143 my (undef, undef, $uuid, $gs) = working_head_info($head, \@refs);
b3cb7e45
AR
1144 unless ($gs) {
1145 die "Unable to determine upstream SVN information from ",
1146 "$head history\n";
26e60160 1147 }
b3cb7e45 1148 my $desired_revision = substr($revision_or_hash, 1);
63c56022 1149 $result = $gs->rev_map_get($desired_revision, $uuid);
26e60160
AR
1150 } else {
1151 my (undef, $rev, undef) = cmt_metadata($revision_or_hash);
1152 $result = $rev;
1153 }
1154 print "$result\n" if $result;
1155}
1156
55f9d7a7
MH
1157sub auto_create_empty_directories {
1158 my ($gs) = @_;
1159 my $var = eval { command_oneline('config', '--get', '--bool',
1160 "svn-remote.$gs->{repo_id}.automkdirs") };
1161 # By default, create empty directories by consulting the unhandled log,
1162 # but allow setting it to 'false' to skip it.
1163 return !($var && $var eq 'false');
1164}
1165
905f8b7d
EW
1166sub cmd_rebase {
1167 command_noisy(qw/update-index --refresh/);
13c823fb
EW
1168 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
1169 unless ($gs) {
905f8b7d
EW
1170 die "Unable to determine upstream SVN information from ",
1171 "working tree history\n";
1172 }
7d45e146
SF
1173 if ($_dry_run) {
1174 print "Remote Branch: " . $gs->refname . "\n";
1175 print "SVN URL: " . $url . "\n";
1176 return;
1177 }
905f8b7d
EW
1178 if (command(qw/diff-index HEAD --/)) {
1179 print STDERR "Cannot rebase with uncommited changes:\n";
1180 command_noisy('status');
1181 exit 1;
1182 }
dee41f3e 1183 unless ($_local) {
cec0d5a3
SG
1184 # rebase will checkout for us, so no need to do it explicitly
1185 $_no_checkout = 'true';
dee41f3e
EW
1186 $_fetch_all ? $gs->fetch_all : $gs->fetch;
1187 }
905f8b7d 1188 command_noisy(rebase_cmd(), $gs->refname);
55f9d7a7
MH
1189 if (auto_create_empty_directories($gs)) {
1190 $gs->mkemptydirs;
1191 }
905f8b7d
EW
1192}
1193
5969cbe1 1194sub cmd_show_ignore {
13c823fb
EW
1195 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
1196 $gs ||= Git::SVN->new;
5969cbe1 1197 my $r = (defined $_revision ? $_revision : $gs->ra->get_latest_revnum);
01bdab84
BS
1198 $gs->prop_walk($gs->{path}, $r, sub {
1199 my ($gs, $path, $props) = @_;
1200 print STDOUT "\n# $path\n";
1201 my $s = $props->{'svn:ignore'} or return;
1202 $s =~ s/[\r\n]+/\n/g;
a7d72544 1203 $s =~ s/^\n+//;
01bdab84
BS
1204 chomp $s;
1205 $s =~ s#^#$path#gm;
1206 print STDOUT "$s\n";
1207 });
a5e0cedc
EW
1208}
1209
2d879792
VK
1210sub cmd_show_externals {
1211 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
1212 $gs ||= Git::SVN->new;
1213 my $r = (defined $_revision ? $_revision : $gs->ra->get_latest_revnum);
1214 $gs->prop_walk($gs->{path}, $r, sub {
1215 my ($gs, $path, $props) = @_;
1216 print STDOUT "\n# $path\n";
1217 my $s = $props->{'svn:externals'} or return;
1218 $s =~ s/[\r\n]+/\n/g;
1219 chomp $s;
1220 $s =~ s#^#$path#gm;
1221 print STDOUT "$s\n";
1222 });
1223}
1224
d05ddec5
BS
1225sub cmd_create_ignore {
1226 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
1227 $gs ||= Git::SVN->new;
1228 my $r = (defined $_revision ? $_revision : $gs->ra->get_latest_revnum);
1229 $gs->prop_walk($gs->{path}, $r, sub {
1230 my ($gs, $path, $props) = @_;
1231 # $path is of the form /path/to/dir/
7d9fd459
BG
1232 $path = '.' . $path;
1233 # SVN can have attributes on empty directories,
1234 # which git won't track
1235 mkpath([$path]) unless -d $path;
1236 my $ignore = $path . '.gitignore';
d05ddec5
BS
1237 my $s = $props->{'svn:ignore'} or return;
1238 open(GITIGNORE, '>', $ignore)
207f1a75 1239 or fatal("Failed to open `$ignore' for writing: $!");
d05ddec5 1240 $s =~ s/[\r\n]+/\n/g;
a7d72544 1241 $s =~ s/^\n+//;
d05ddec5
BS
1242 chomp $s;
1243 # Prefix all patterns so that the ignore doesn't apply
1244 # to sub-directories.
1245 $s =~ s#^#/#gm;
1246 print GITIGNORE "$s\n";
1247 close(GITIGNORE)
207f1a75 1248 or fatal("Failed to close `$ignore': $!");
c4c66b26 1249 command_noisy('add', '-f', $ignore);
d05ddec5
BS
1250 });
1251}
1252
6111b934
EW
1253sub cmd_mkdirs {
1254 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
1255 $gs ||= Git::SVN->new;
1256 $gs->mkemptydirs($_revision);
1257}
1258
b2b3ada7
DK
1259sub canonicalize_path {
1260 my ($path) = @_;
e6fefa92
DK
1261 my $dot_slash_added = 0;
1262 if (substr($path, 0, 1) ne "/") {
1263 $path = "./" . $path;
1264 $dot_slash_added = 1;
1265 }
b2b3ada7
DK
1266 # File::Spec->canonpath doesn't collapse x/../y into y (for a
1267 # good reason), so let's do this manually.
1268 $path =~ s#/+#/#g;
1269 $path =~ s#/\.(?:/|$)#/#g;
1270 $path =~ s#/[^/]+/\.\.##g;
1271 $path =~ s#/$##g;
e6fefa92 1272 $path =~ s#^\./## if $dot_slash_added;
2fe403e7
GP
1273 $path =~ s#^/##;
1274 $path =~ s#^\.$##;
b2b3ada7
DK
1275 return $path;
1276}
1277
50ff2366
UD
1278sub canonicalize_url {
1279 my ($url) = @_;
1280 $url =~ s#^([^:]+://[^/]*/)(.*)$#$1 . canonicalize_path($2)#e;
1281 return $url;
1282}
1283
15153451
BS
1284# get_svnprops(PATH)
1285# ------------------
51e057cf 1286# Helper for cmd_propget and cmd_proplist below.
15153451
BS
1287sub get_svnprops {
1288 my $path = shift;
1289 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
1290 $gs ||= Git::SVN->new;
1291
1292 # prefix THE PATH by the sub-directory from which the user
1293 # invoked us.
1294 $path = $cmd_dir_prefix . $path;
207f1a75 1295 fatal("No such file or directory: $path") unless -e $path;
15153451
BS
1296 my $is_dir = -d $path ? 1 : 0;
1297 $path = $gs->{path} . '/' . $path;
1298
1299 # canonicalize the path (otherwise libsvn will abort or fail to
1300 # find the file)
b2b3ada7 1301 $path = canonicalize_path($path);
15153451
BS
1302
1303 my $r = (defined $_revision ? $_revision : $gs->ra->get_latest_revnum);
1304 my $props;
1305 if ($is_dir) {
1306 (undef, undef, $props) = $gs->ra->get_dir($path, $r);
1307 }
1308 else {
1309 (undef, $props) = $gs->ra->get_file($path, $r, undef);
1310 }
1311 return $props;
1312}
1313
1314# cmd_propget (PROP, PATH)
1315# ------------------------
1316# Print the SVN property PROP for PATH.
1317sub cmd_propget {
1318 my ($prop, $path) = @_;
1319 $path = '.' if not defined $path;
1320 usage(1) if not defined $prop;
1321 my $props = get_svnprops($path);
1322 if (not defined $props->{$prop}) {
207f1a75 1323 fatal("`$path' does not have a `$prop' SVN property.");
15153451
BS
1324 }
1325 print $props->{$prop} . "\n";
1326}
1327
51e057cf
BS
1328# cmd_proplist (PATH)
1329# -------------------
1330# Print the list of SVN properties for PATH.
1331sub cmd_proplist {
1332 my $path = shift;
1333 $path = '.' if not defined $path;
1334 my $props = get_svnprops($path);
1335 print "Properties on '$path':\n";
1336 foreach (sort keys %{$props}) {
1337 print " $_\n";
1338 }
1339}
1340
8164b652 1341sub cmd_multi_init {
9d55b41a 1342 my $url = shift;
62244069 1343 unless (defined $_trunk || @_branches || @_tags) {
98327e58 1344 usage(1);
9d55b41a 1345 }
dc431666 1346
8164b652 1347 $_prefix = '' unless defined $_prefix;
dadc6d2a 1348 if (defined $url) {
50ff2366 1349 $url = canonicalize_url($url);
dadc6d2a
EW
1350 init_subdir(@_);
1351 }
f30603fc 1352 do_git_init_db();
98327e58 1353 if (defined $_trunk) {
b4b33600 1354 $_trunk =~ s#^/+##;
6f5748e1 1355 my $trunk_ref = 'refs/remotes/' . $_prefix . 'trunk';
706587fc
EW
1356 # try both old-style and new-style lookups:
1357 my $gs_trunk = eval { Git::SVN->new($trunk_ref) };
8164b652 1358 unless ($gs_trunk) {
706587fc
EW
1359 my ($trunk_url, $trunk_path) =
1360 complete_svn_url($url, $_trunk);
1361 $gs_trunk = Git::SVN->init($trunk_url, $trunk_path,
1362 undef, $trunk_ref);
98327e58 1363 }
c35b96e7 1364 }
62244069 1365 return unless @_branches || @_tags;
e7db67e6 1366 my $ra = $url ? Git::SVN::Ra->new($url) : undef;
62244069
MB
1367 foreach my $path (@_branches) {
1368 complete_url_ls_init($ra, $path, '--branches/-b', $_prefix);
1369 }
1370 foreach my $path (@_tags) {
1371 complete_url_ls_init($ra, $path, '--tags/-t', $_prefix.'tags/');
1372 }
9d55b41a
EW
1373}
1374
1c8443b0 1375sub cmd_multi_fetch {
4d0157d6 1376 $Git::SVN::no_reuse_existing = undef;
0af9c9f9
EW
1377 my $remotes = Git::SVN::read_all_remotes();
1378 foreach my $repo_id (sort keys %$remotes) {
db03cd24 1379 if ($remotes->{$repo_id}->{url}) {
4bb9ed04
EW
1380 Git::SVN::fetch_all($repo_id, $remotes);
1381 }
9d55b41a 1382 }
9d55b41a
EW
1383}
1384
44320b9e
EW
1385# this command is special because it requires no metadata
1386sub cmd_commit_diff {
1387 my ($ta, $tb, $url) = @_;
1388 my $usage = "Usage: $0 commit-diff -r<revision> ".
207f1a75 1389 "<tree-ish> <tree-ish> [<URL>]";
44320b9e 1390 fatal($usage) if (!defined $ta || !defined $tb);
d72ab8c8 1391 my $svn_path = '';
44320b9e
EW
1392 if (!defined $url) {
1393 my $gs = eval { Git::SVN->new };
1394 if (!$gs) {
1395 fatal("Needed URL or usable git-svn --id in ",
1396 "the command-line\n", $usage);
1397 }
1398 $url = $gs->{url};
d3a840dc 1399 $svn_path = $gs->{path};
44320b9e
EW
1400 }
1401 unless (defined $_revision) {
1402 fatal("-r|--revision is a required argument\n", $usage);
1403 }
1404 if (defined $_message && defined $_file) {
1405 fatal("Both --message/-m and --file/-F specified ",
1406 "for the commit message.\n",
207f1a75 1407 "I have no idea what you mean");
44320b9e
EW
1408 }
1409 if (defined $_file) {
1410 $_message = file_to_s($_file);
1411 } else {
1412 $_message ||= get_commit_entry($tb)->{log};
1413 }
1414 my $ra ||= Git::SVN::Ra->new($url);
1415 my $r = $_revision;
1416 if ($r eq 'HEAD') {
1417 $r = $ra->get_latest_revnum;
1418 } elsif ($r !~ /^\d+$/) {
1419 die "revision argument: $r not understood by git-svn\n";
1420 }
61395354
EW
1421 my %ed_opts = ( r => $r,
1422 log => $_message,
1423 ra => $ra,
1424 tree_a => $ta,
1425 tree_b => $tb,
1426 editor_cb => sub { print "Committed r$_[0]\n" },
1427 svn_path => $svn_path );
72827aa4 1428 if (!Git::SVN::Editor->new(\%ed_opts)->apply_diff) {
44320b9e
EW
1429 print "No changes\n$ta == $tb\n";
1430 }
44320b9e
EW
1431}
1432
05427b91
TR
1433sub escape_uri_only {
1434 my ($uri) = @_;
1435 my @tmp;
1436 foreach (split m{/}, $uri) {
6a004d3f 1437 s/([^~\w.%+-]|%(?![a-fA-F0-9]{2}))/sprintf("%%%02X",ord($1))/eg;
05427b91
TR
1438 push @tmp, $_;
1439 }
1440 join('/', @tmp);
1441}
1442
1443sub escape_url {
1444 my ($url) = @_;
1445 if ($url =~ m#^([^:]+)://([^/]*)(.*)$#) {
1446 my ($scheme, $domain, $uri) = ($1, $2, escape_uri_only($3));
1447 $url = "$scheme://$domain$uri";
1448 }
1449 $url;
1450}
1451
e6fefa92 1452sub cmd_info {
bd2d4f96 1453 my $path = canonicalize_path(defined($_[0]) ? $_[0] : ".");
edde9112 1454 my $fullpath = canonicalize_path($cmd_dir_prefix . $path);
bd2d4f96 1455 if (exists $_[1]) {
e6fefa92
DK
1456 die "Too many arguments specified\n";
1457 }
1458
1459 my ($file_type, $diff_status) = find_file_type_and_diff_status($path);
1460
1461 if (!$file_type && !$diff_status) {
2cf3e3ac
TR
1462 print STDERR "svn: '$path' is not under version control\n";
1463 exit 1;
e6fefa92
DK
1464 }
1465
1466 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
1467 unless ($gs) {
1468 die "Unable to determine upstream SVN information from ",
1469 "working tree history\n";
1470 }
bd2d4f96
EW
1471
1472 # canonicalize_path() will return "" to make libsvn 1.5.x happy,
1473 $path = "." if $path eq "";
1474
edde9112 1475 my $full_url = $url . ($fullpath eq "" ? "" : "/$fullpath");
e6fefa92 1476
8b014d71 1477 if ($_url) {
05427b91 1478 print escape_url($full_url), "\n";
8b014d71
DK
1479 return;
1480 }
1481
e6fefa92
DK
1482 my $result = "Path: $path\n";
1483 $result .= "Name: " . basename($path) . "\n" if $file_type ne "dir";
05427b91 1484 $result .= "URL: " . escape_url($full_url) . "\n";
e6fefa92 1485
a5460eb7
EW
1486 eval {
1487 my $repos_root = $gs->repos_root;
1488 Git::SVN::remove_username($repos_root);
05427b91 1489 $result .= "Repository Root: " . escape_url($repos_root) . "\n";
a5460eb7
EW
1490 };
1491 if ($@) {
1492 $result .= "Repository Root: (offline)\n";
1493 }
b91a8a3e 1494 ::_req_svn();
22ba47f5 1495 $result .= "Repository UUID: $uuid\n" unless $diff_status eq "A" &&
f760c903 1496 (::compare_svn_version('1.5.4') <= 0 || $file_type ne "dir");
e6fefa92
DK
1497 $result .= "Revision: " . ($diff_status eq "A" ? 0 : $rev) . "\n";
1498
1499 $result .= "Node Kind: " .
1500 ($file_type eq "dir" ? "directory" : "file") . "\n";
1501
1502 my $schedule = $diff_status eq "A"
1503 ? "add"
1504 : ($diff_status eq "D" ? "delete" : "normal");
1505 $result .= "Schedule: $schedule\n";
1506
1507 if ($diff_status eq "A") {
1508 print $result, "\n";
1509 return;
1510 }
1511
1512 my ($lc_author, $lc_rev, $lc_date_utc);
edde9112 1513 my @args = Git::SVN::Log::git_svn_log_cmd($rev, $rev, "--", $fullpath);
e6fefa92
DK
1514 my $log = command_output_pipe(@args);
1515 my $esc_color = qr/(?:\033\[(?:(?:\d+;)*\d*)?m)*/;
1516 while (<$log>) {
1517 if (/^${esc_color}author (.+) <[^>]+> (\d+) ([\-\+]?\d+)$/o) {
1518 $lc_author = $1;
1519 $lc_date_utc = Git::SVN::Log::parse_git_date($2, $3);
1520 } elsif (/^${esc_color} (git-svn-id:.+)$/o) {
1521 (undef, $lc_rev, undef) = ::extract_metadata($1);
1522 }
1523 }
1524 close $log;
1525
1526 Git::SVN::Log::set_local_timezone();
1527
1528 $result .= "Last Changed Author: $lc_author\n";
1529 $result .= "Last Changed Rev: $lc_rev\n";
1530 $result .= "Last Changed Date: " .
1531 Git::SVN::Log::format_svn_date($lc_date_utc) . "\n";
1532
1533 if ($file_type ne "dir") {
1534 my $text_last_updated_date =
1535 ($diff_status eq "D" ? $lc_date_utc : (stat $path)[9]);
1536 $result .=
1537 "Text Last Updated: " .
1538 Git::SVN::Log::format_svn_date($text_last_updated_date) .
1539 "\n";
1540 my $checksum;
1541 if ($diff_status eq "D") {
1542 my ($fh, $ctx) =
1543 command_output_pipe(qw(cat-file blob), "HEAD:$path");
1544 if ($file_type eq "link") {
1545 my $file_name = <$fh>;
8d7c4fad 1546 $checksum = md5sum("link $file_name");
e6fefa92 1547 } else {
8d7c4fad 1548 $checksum = md5sum($fh);
e6fefa92
DK
1549 }
1550 command_close_pipe($fh, $ctx);
1551 } elsif ($file_type eq "link") {
1552 my $file_name =
1553 command(qw(cat-file blob), "HEAD:$path");
1554 $checksum =
8d7c4fad 1555 md5sum("link " . $file_name);
e6fefa92
DK
1556 } else {
1557 open FILE, "<", $path or die $!;
8d7c4fad 1558 $checksum = md5sum(\*FILE);
e6fefa92
DK
1559 close FILE or die $!;
1560 }
1561 $result .= "Checksum: " . $checksum . "\n";
1562 }
1563
1564 print $result, "\n";
1565}
1566
195643f2
BJ
1567sub cmd_reset {
1568 my $target = shift || $_revision or die "SVN revision required\n";
1569 $target = $1 if $target =~ /^r(\d+)$/;
1570 $target =~ /^\d+$/ or die "Numeric SVN revision expected\n";
1571 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
1572 unless ($gs) {
1573 die "Unable to determine upstream SVN information from ".
1574 "history\n";
1575 }
1576 my ($r, $c) = $gs->find_rev_before($target, not $_fetch_parent);
70ee0b77 1577 die "Cannot find SVN revision $target\n" unless defined($c);
195643f2
BJ
1578 $gs->rev_map_set($r, $c, 'reset', $uuid);
1579 print "r$r = $c ($gs->{ref_id})\n";
1580}
1581
2da9ee08
RZ
1582sub cmd_gc {
1583 if (!$can_compress) {
1584 warn "Compress::Zlib could not be found; unhandled.log " .
1585 "files will not be compressed.\n";
1586 }
1587 find({ wanted => \&gc_directory, no_chdir => 1}, "$ENV{GIT_DIR}/svn");
1588}
1589
3397f9df
EW
1590########################### utility functions #########################
1591
905f8b7d
EW
1592sub rebase_cmd {
1593 my @cmd = qw/rebase/;
1594 push @cmd, '-v' if $_verbose;
1595 push @cmd, qw/--merge/ if $_merge;
1596 push @cmd, "--strategy=$_strategy" if $_strategy;
b64e1f58 1597 push @cmd, "--preserve-merges" if $_preserve_merges;
905f8b7d
EW
1598 @cmd;
1599}
1600
1e889ef3
EW
1601sub post_fetch_checkout {
1602 return if $_no_checkout;
1603 my $gs = $Git::SVN::_head or return;
1604 return if verify_ref('refs/heads/master^0');
1605
b186a261
EW
1606 # look for "trunk" ref if it exists
1607 my $remote = Git::SVN::read_all_remotes()->{$gs->{repo_id}};
1608 my $fetch = $remote->{fetch};
1609 if ($fetch) {
1610 foreach my $p (keys %$fetch) {
1611 basename($fetch->{$p}) eq 'trunk' or next;
1612 $gs = Git::SVN->new($fetch->{$p}, $gs->{repo_id}, $p);
1613 last;
1614 }
1615 }
1616
1e889ef3
EW
1617 my $valid_head = verify_ref('HEAD^0');
1618 command_noisy(qw(update-ref refs/heads/master), $gs->refname);
1619 return if ($valid_head || !verify_ref('HEAD^0'));
1620
1621 return if $ENV{GIT_DIR} !~ m#^(?:.*/)?\.git$#;
1622 my $index = $ENV{GIT_INDEX_FILE} || "$ENV{GIT_DIR}/index";
1623 return if -f $index;
1624
7ae3df8c 1625 return if command_oneline(qw/rev-parse --is-inside-work-tree/) eq 'false';
1e889ef3
EW
1626 return if command_oneline(qw/rev-parse --is-inside-git-dir/) eq 'true';
1627 command_noisy(qw/read-tree -m -u -v HEAD HEAD/);
1628 print STDERR "Checked out HEAD:\n ",
1629 $gs->full_url, " r", $gs->last_rev, "\n";
55f9d7a7
MH
1630 if (auto_create_empty_directories($gs)) {
1631 $gs->mkemptydirs($gs->last_rev);
1632 }
1e889ef3
EW
1633}
1634
98327e58
EW
1635sub complete_svn_url {
1636 my ($url, $path) = @_;
1637 $path =~ s#/+$##;
98327e58 1638 if ($path !~ m#^[a-z\+]+://#) {
98327e58
EW
1639 if (!defined $url || $url !~ m#^[a-z\+]+://#) {
1640 fatal("E: '$path' is not a complete URL ",
207f1a75 1641 "and a separate URL is not specified");
98327e58 1642 }
706587fc 1643 return ($url, $path);
98327e58 1644 }
706587fc 1645 return ($path, '');
98327e58
EW
1646}
1647
9d55b41a 1648sub complete_url_ls_init {
706587fc
EW
1649 my ($ra, $repo_path, $switch, $pfx) = @_;
1650 unless ($repo_path) {
9d55b41a
EW
1651 print STDERR "W: $switch not specified\n";
1652 return;
1653 }
706587fc
EW
1654 $repo_path =~ s#/+$##;
1655 if ($repo_path =~ m#^[a-z\+]+://#) {
1656 $ra = Git::SVN::Ra->new($repo_path);
1657 $repo_path = '';
e7db67e6 1658 } else {
706587fc 1659 $repo_path =~ s#^/+##;
e7db67e6 1660 unless ($ra) {
706587fc 1661 fatal("E: '$repo_path' is not a complete URL ",
207f1a75 1662 "and a separate URL is not specified");
8164b652 1663 }
e7db67e6 1664 }
706587fc 1665 my $url = $ra->{url};
b4d57e5e
EW
1666 my $gs = Git::SVN->init($url, undef, undef, undef, 1);
1667 my $k = "svn-remote.$gs->{repo_id}.url";
1668 my $orig_url = eval { command_oneline(qw/config --get/, $k) };
1669 if ($orig_url && ($orig_url ne $gs->{url})) {
1670 die "$k already set: $orig_url\n",
1671 "wanted to set to: $gs->{url}\n";
88cf4107 1672 }
b4d57e5e 1673 command_oneline('config', $k, $gs->{url}) unless $orig_url;
0b2af457 1674 my $remote_path = "$gs->{path}/$repo_path";
5268f9ed 1675 $remote_path =~ s{%([0-9A-F]{2})}{chr hex($1)}ieg;
b4d57e5e
EW
1676 $remote_path =~ s#/+#/#g;
1677 $remote_path =~ s#^/##g;
ed0b9d43 1678 $remote_path .= "/*" if $remote_path !~ /\*/;
b4d57e5e
EW
1679 my ($n) = ($switch =~ /^--(\w+)/);
1680 if (length $pfx && $pfx !~ m#/$#) {
1681 die "--prefix='$pfx' must have a trailing slash '/'\n";
9d55b41a 1682 }
570d35c2 1683 command_noisy('config',
62244069 1684 '--add',
570d35c2
MG
1685 "svn-remote.$gs->{repo_id}.$n",
1686 "$remote_path:refs/remotes/$pfx*" .
1687 ('/*' x (($remote_path =~ tr/*/*/) - 1)) );
9d55b41a
EW
1688}
1689
aef4e921
EW
1690sub verify_ref {
1691 my ($ref) = @_;
2c5c1d53
EW
1692 eval { command_oneline([ 'rev-parse', '--verify', $ref ],
1693 { STDERR => 0 }); };
aef4e921
EW
1694}
1695
a5e0cedc 1696sub get_tree_from_treeish {
cf52b8f0 1697 my ($treeish) = @_;
44320b9e 1698 # $treeish can be a symbolic ref, too:
aef4e921 1699 my $type = command_oneline(qw/cat-file -t/, $treeish);
cf52b8f0
EW
1700 my $expected;
1701 while ($type eq 'tag') {
aef4e921 1702 ($treeish, $type) = command(qw/cat-file tag/, $treeish);
cf52b8f0
EW
1703 }
1704 if ($type eq 'commit') {
aef4e921
EW
1705 $expected = (grep /^tree /, command(qw/cat-file commit/,
1706 $treeish))[0];
44320b9e 1707 ($expected) = ($expected =~ /^tree ($sha1)$/o);
cf52b8f0
EW
1708 die "Unable to get tree from $treeish\n" unless $expected;
1709 } elsif ($type eq 'tree') {
1710 $expected = $treeish;
1711 } else {
1712 die "$treeish is a $type, expected tree, tag or commit\n";
1713 }
a5e0cedc
EW
1714 return $expected;
1715}
1716
44320b9e
EW
1717sub get_commit_entry {
1718 my ($treeish) = shift;
1719 my %log_entry = ( log => '', tree => get_tree_from_treeish($treeish) );
1720 my $commit_editmsg = "$ENV{GIT_DIR}/COMMIT_EDITMSG";
1721 my $commit_msg = "$ENV{GIT_DIR}/COMMIT_MSG";
1722 open my $log_fh, '>', $commit_editmsg or croak $!;
3397f9df 1723
44320b9e 1724 my $type = command_oneline(qw/cat-file -t/, $treeish);
4ad4515d 1725 if ($type eq 'commit' || $type eq 'tag') {
aef4e921 1726 my ($msg_fh, $ctx) = command_output_pipe('cat-file',
44320b9e 1727 $type, $treeish);
3397f9df 1728 my $in_msg = 0;
6aa9ba14
AP
1729 my $author;
1730 my $saw_from = 0;
328eb9b3 1731 my $msgbuf = "";
3397f9df
EW
1732 while (<$msg_fh>) {
1733 if (!$in_msg) {
1734 $in_msg = 1 if (/^\s*$/);
6aa9ba14 1735 $author = $1 if (/^author (.*>)/);
df746c5a 1736 } elsif (/^git-svn-id: /) {
44320b9e
EW
1737 # skip this for now, we regenerate the
1738 # correct one on re-fetch anyways
1739 # TODO: set *:merge properties or like...
3397f9df 1740 } else {
6aa9ba14
AP
1741 if (/^From:/ || /^Signed-off-by:/) {
1742 $saw_from = 1;
1743 }
328eb9b3 1744 $msgbuf .= $_;
3397f9df
EW
1745 }
1746 }
328eb9b3 1747 $msgbuf =~ s/\s+$//s;
6aa9ba14
AP
1748 if ($Git::SVN::_add_author_from && defined($author)
1749 && !$saw_from) {
328eb9b3 1750 $msgbuf .= "\n\nFrom: $author";
6aa9ba14 1751 }
328eb9b3 1752 print $log_fh $msgbuf or croak $!;
aef4e921 1753 command_close_pipe($msg_fh, $ctx);
3397f9df 1754 }
44320b9e 1755 close $log_fh or croak $!;
3397f9df
EW
1756
1757 if ($_edit || ($type eq 'tree')) {
b4479f07
JN
1758 chomp(my $editor = command_oneline(qw(var GIT_EDITOR)));
1759 system('sh', '-c', $editor.' "$@"', $editor, $commit_editmsg);
3397f9df 1760 }
44320b9e 1761 rename $commit_editmsg, $commit_msg or croak $!;
16fc08e2 1762 {
b510df8a 1763 require Encode;
16fc08e2
EW
1764 # SVN requires messages to be UTF-8 when entering the repo
1765 local $/;
1766 open $log_fh, '<', $commit_msg or croak $!;
1767 binmode $log_fh;
1768 chomp($log_entry{log} = <$log_fh>);
1769
b510df8a
EW
1770 my $enc = Git::config('i18n.commitencoding') || 'UTF-8';
1771 my $msg = $log_entry{log};
1772
1773 eval { $msg = Encode::decode($enc, $msg, 1) };
1774 if ($@) {
1775 die "Could not decode as $enc:\n", $msg,
1776 "\nPerhaps you need to set i18n.commitencoding\n";
16fc08e2 1777 }
b510df8a
EW
1778
1779 eval { $msg = Encode::encode('UTF-8', $msg, 1) };
1780 die "Could not encode as UTF-8:\n$msg\n" if $@;
1781
1782 $log_entry{log} = $msg;
1783
16fc08e2
EW
1784 close $log_fh or croak $!;
1785 }
44320b9e
EW
1786 unlink $commit_msg;
1787 \%log_entry;
a5e0cedc
EW
1788}
1789
3397f9df
EW
1790sub s_to_file {
1791 my ($str, $file, $mode) = @_;
1792 open my $fd,'>',$file or croak $!;
1793 print $fd $str,"\n" or croak $!;
1794 close $fd or croak $!;
1795 chmod ($mode &~ umask, $file) if (defined $mode);
1796}
1797
1798sub file_to_s {
1799 my $file = shift;
1800 open my $fd,'<',$file or croak "$!: file: $file\n";
1801 local $/;
1802 my $ret = <$fd>;
1803 close $fd or croak $!;
1804 $ret =~ s/\s*$//s;
1805 return $ret;
1806}
1807
eeb0abe0
EW
1808# '<svn username> = real-name <email address>' mapping based on git-svnimport:
1809sub load_authors {
1810 open my $authors, '<', $_authors or die "Can't open $_authors $!\n";
f8c9d1d2 1811 my $log = $cmd eq 'log';
eeb0abe0
EW
1812 while (<$authors>) {
1813 chomp;
575d025c 1814 next unless /^(.+?|\(no author\))\s*=\s*(.+?)\s*<(.+)>\s*$/;
eeb0abe0 1815 my ($user, $name, $email) = ($1, $2, $3);
f8c9d1d2
EW
1816 if ($log) {
1817 $Git::SVN::Log::rusers{"$name <$email>"} = $user;
1818 } else {
1819 $users{$user} = [$name, $email];
1820 }
79bb8d88
EW
1821 }
1822 close $authors or croak $!;
1823}
1824
e0d10e1c 1825# convert GetOpt::Long specs for use by git-config
1a30582b 1826sub read_git_config {
b8c92cad 1827 my $opts = shift;
97ae0911 1828 my @config_only;
b8c92cad 1829 foreach my $o (keys %$opts) {
97ae0911
EW
1830 # if we have mixedCase and a long option-only, then
1831 # it's a config-only variable that we don't need for
1832 # the command-line.
1833 push @config_only, $o if ($o =~ /[A-Z]/ && $o =~ /^[a-z]+$/i);
b8c92cad 1834 my $v = $opts->{$o};
97ae0911 1835 my ($key) = ($o =~ /^([a-zA-Z\-]+)/);
b8c92cad 1836 $key =~ s/-//g;
225f1d0c 1837 my $arg = 'git config';
b8c92cad
EW
1838 $arg .= ' --int' if ($o =~ /[:=]i$/);
1839 $arg .= ' --bool' if ($o !~ /[:=][sfi]$/);
1840 if (ref $v eq 'ARRAY') {
1841 chomp(my @tmp = `$arg --get-all svn.$key`);
1842 @$v = @tmp if @tmp;
1843 } else {
1844 chomp(my $tmp = `$arg --get svn.$key`);
7774284a 1845 if ($tmp && !($arg =~ / --bool/ && $tmp eq 'false')) {
b8c92cad
EW
1846 $$v = $tmp;
1847 }
1848 }
1849 }
97ae0911 1850 delete @$opts{@config_only} if @config_only;
b8c92cad
EW
1851}
1852
79bb8d88 1853sub extract_metadata {
c1927a85 1854 my $id = shift or return (undef, undef, undef);
3dfab993 1855 my ($url, $rev, $uuid) = ($id =~ /^\s*git-svn-id:\s+(.*)\@(\d+)
b3e95936 1856 \s([a-f\d\-]+)$/ix);
e70dc780 1857 if (!defined $rev || !$uuid || !$url) {
79bb8d88 1858 # some of the original repositories I made had
82e5a82f 1859 # identifiers like this:
b3e95936 1860 ($rev, $uuid) = ($id =~/^\s*git-svn-id:\s(\d+)\@([a-f\d\-]+)/i);
79bb8d88
EW
1861 }
1862 return ($url, $rev, $uuid);
1863}
1864
c1927a85
EW
1865sub cmt_metadata {
1866 return extract_metadata((grep(/^git-svn-id: /,
aef4e921 1867 command(qw/cat-file commit/, shift)))[-1]);
c1927a85
EW
1868}
1869
6ea42032
BB
1870sub cmt_sha2rev_batch {
1871 my %s2r;
1872 my ($pid, $in, $out, $ctx) = command_bidi_pipe(qw/cat-file --batch/);
1873 my $list = shift;
1874
1875 foreach my $sha (@{$list}) {
1876 my $first = 1;
1877 my $size = 0;
1878 print $out $sha, "\n";
1879
1880 while (my $line = <$in>) {
1881 if ($first && $line =~ /^[[:xdigit:]]{40}\smissing$/) {
1882 last;
1883 } elsif ($first &&
1884 $line =~ /^[[:xdigit:]]{40}\scommit\s(\d+)$/) {
1885 $first = 0;
1886 $size = $1;
1887 next;
1888 } elsif ($line =~ /^(git-svn-id: )/) {
1889 my (undef, $rev, undef) =
1890 extract_metadata($line);
1891 $s2r{$sha} = $rev;
1892 }
1893
1894 $size -= length($line);
1895 last if ($size == 0);
1896 }
1897 }
1898
1899 command_close_bidi_pipe($pid, $in, $out, $ctx);
1900
1901 return \%s2r;
1902}
1903
905f8b7d
EW
1904sub working_head_info {
1905 my ($head, $refs) = @_;
83cf21f9 1906 my @args = qw/rev-list --first-parent --pretty=medium/;
05b4df31 1907 my ($fh, $ctx) = command_output_pipe(@args, $head);
3dfab993 1908 my $hash;
40cb8f8f 1909 my %max;
3dfab993
SV
1910 while (<$fh>) {
1911 if ( m{^commit ($::sha1)$} ) {
1912 unshift @$refs, $hash if $hash and $refs;
1913 $hash = $1;
1914 next;
1915 }
1916 next unless s{^\s*(git-svn-id:)}{$1};
1917 my ($url, $rev, $uuid) = extract_metadata($_);
13c823fb 1918 if (defined $url && defined $rev) {
40cb8f8f 1919 next if $max{$url} and $max{$url} < $rev;
13c823fb 1920 if (my $gs = Git::SVN->find_by_url($url)) {
63c56022 1921 my $c = $gs->rev_map_get($rev, $uuid);
b03c7a63 1922 if ($c && $c eq $hash) {
13c823fb
EW
1923 close $fh; # break the pipe
1924 return ($url, $rev, $uuid, $gs);
40cb8f8f 1925 } else {
060610c5 1926 $max{$url} ||= $gs->rev_map_max;
13c823fb
EW
1927 }
1928 }
1929 }
905f8b7d 1930 }
13c823fb
EW
1931 command_close_pipe($fh, $ctx);
1932 (undef, undef, undef, undef);
905f8b7d
EW
1933}
1934
733a65aa
EW
1935sub read_commit_parents {
1936 my ($parents, $c) = @_;
7b02b85a
EW
1937 chomp(my $p = command_oneline(qw/rev-list --parents -1/, $c));
1938 $p =~ s/^($c)\s*// or die "rev-list --parents -1 $c failed!\n";
1939 @{$parents->{$c}} = split(/ /, $p);
733a65aa
EW
1940}
1941
1942sub linearize_history {
1943 my ($gs, $refs) = @_;
1944 my %parents;
1945 foreach my $c (@$refs) {
1946 read_commit_parents(\%parents, $c);
1947 }
1948
1949 my @linear_refs;
1950 my %skip = ();
1951 my $last_svn_commit = $gs->last_commit;
1952 foreach my $c (reverse @$refs) {
1953 next if $c eq $last_svn_commit;
1954 last if $skip{$c};
1955
1956 unshift @linear_refs, $c;
1957 $skip{$c} = 1;
1958
1959 # we only want the first parent to diff against for linear
1960 # history, we save the rest to inject when we finalize the
1961 # svn commit
1962 my $fp_a = verify_ref("$c~1");
1963 my $fp_b = shift @{$parents{$c}} if $parents{$c};
1964 if (!$fp_a || !$fp_b) {
1965 die "Commit $c\n",
1966 "has no parent commit, and therefore ",
1967 "nothing to diff against.\n",
1968 "You should be working from a repository ",
1969 "originally created by git-svn\n";
1970 }
1971 if ($fp_a ne $fp_b) {
1972 die "$c~1 = $fp_a, however parsing commit $c ",
1973 "revealed that:\n$c~1 = $fp_b\nBUG!\n";
1974 }
1975
1976 foreach my $p (@{$parents{$c}}) {
1977 $skip{$p} = 1;
1978 }
1979 }
1980 (\@linear_refs, \%parents);
1981}
1982
e6fefa92
DK
1983sub find_file_type_and_diff_status {
1984 my ($path) = @_;
107cee50 1985 return ('dir', '') if $path eq '';
e6fefa92
DK
1986
1987 my $diff_output =
1988 command_oneline(qw(diff --cached --name-status --), $path) || "";
1989 my $diff_status = (split(' ', $diff_output))[0] || "";
1990
1991 my $ls_tree = command_oneline(qw(ls-tree HEAD), $path) || "";
1992
1993 return (undef, undef) if !$diff_status && !$ls_tree;
1994
1995 if ($diff_status eq "A") {
1996 return ("link", $diff_status) if -l $path;
1997 return ("dir", $diff_status) if -d $path;
1998 return ("file", $diff_status);
1999 }
2000
2001 my $mode = (split(' ', $ls_tree))[0] || "";
2002
2003 return ("link", $diff_status) if $mode eq "120000";
2004 return ("dir", $diff_status) if $mode eq "040000";
2005 return ("file", $diff_status);
2006}
2007
b2b3ada7
DK
2008sub md5sum {
2009 my $arg = shift;
2010 my $ref = ref $arg;
2011 my $md5 = Digest::MD5->new();
0b19138b 2012 if ($ref eq 'GLOB' || $ref eq 'IO::File' || $ref eq 'File::Temp') {
b2b3ada7
DK
2013 $md5->addfile($arg) or croak $!;
2014 } elsif ($ref eq 'SCALAR') {
2015 $md5->add($$arg) or croak $!;
2016 } elsif (!$ref) {
2017 $md5->add($arg) or croak $!;
2018 } else {
2019 ::fatal "Can't provide MD5 hash for unknown ref type: '", $ref, "'";
2020 }
2021 return $md5->hexdigest();
2022}
2023
2da9ee08
RZ
2024sub gc_directory {
2025 if ($can_compress && -f $_ && basename($_) eq "unhandled.log") {
2026 my $out_filename = $_ . ".gz";
2027 open my $in_fh, "<", $_ or die "Unable to open $_: $!\n";
2028 binmode $in_fh;
2029 my $gz = Compress::Zlib::gzopen($out_filename, "ab") or
2030 die "Unable to open $out_filename: $!\n";
2031
2032 my $res;
2033 while ($res = sysread($in_fh, my $str, 1024)) {
2034 $gz->gzwrite($str) or
2035 die "Unable to write: ".$gz->gzerror()."!\n";
2036 }
2037 unlink $_ or die "unlink $File::Find::name: $!\n";
2038 } elsif (-f $_ && basename($_) eq "index") {
2039 unlink $_ or die "unlink $_: $!\n";
2040 }
2041}
2042
9b981fc6
EW
2043package Git::SVN;
2044use strict;
2045use warnings;
060610c5
EW
2046use Fcntl qw/:DEFAULT :seek/;
2047use constant rev_map_fmt => 'NH40';
ecc712dd 2048use vars qw/$default_repo_id $default_ref_id $_no_metadata $_follow_parent
62e349d2 2049 $_repack $_repack_flags $_use_svm_props $_head
70ae04e4 2050 $_use_svnsync_props $no_reuse_existing $_minimize_url
e82f0d73 2051 $_use_log_author $_add_author_from $_localtime/;
9b981fc6
EW
2052use Carp qw/croak/;
2053use File::Path qw/mkpath/;
373274f9 2054use File::Copy qw/copy/;
9b981fc6 2055use IPC::Open3;
6aa17fc6 2056use Time::Local;
7d944c33 2057use Memoize; # core since 5.8.0, Jul 2002
8bff7c53 2058use Memoize::Storable;
037a98cd 2059use POSIX qw(:signal_h);
9b981fc6 2060
94bc914c
KW
2061my ($_gc_nr, $_gc_period);
2062
9b981fc6
EW
2063# properties that we do not log:
2064my %SKIP_PROP;
2065BEGIN {
2066 %SKIP_PROP = map { $_ => 1 } qw/svn:wc:ra_dav:version-url
2067 svn:special svn:executable
2068 svn:entry:committed-rev
2069 svn:entry:last-author
2070 svn:entry:uuid
2071 svn:entry:committed-date/;
91b03282
EW
2072
2073 # some options are read globally, but can be overridden locally
2074 # per [svn-remote "..."] section. Command-line options will *NOT*
2075 # override options set in an [svn-remote "..."] section
c5f71ad0
SV
2076 no strict 'refs';
2077 for my $option (qw/follow_parent no_metadata use_svm_props
2078 use_svnsync_props/) {
2079 my $key = $option;
91b03282 2080 $key =~ tr/_//d;
c5f71ad0
SV
2081 my $prop = "-$option";
2082 *$option = sub {
2083 my ($self) = @_;
2084 return $self->{$prop} if exists $self->{$prop};
2085 my $k = "svn-remote.$self->{repo_id}.$key";
2086 eval { command_oneline(qw/config --get/, $k) };
2087 if ($@) {
2088 $self->{$prop} = ${"Git::SVN::_$option"};
91b03282 2089 } else {
c5f71ad0
SV
2090 my $v = command_oneline(qw/config --bool/,$k);
2091 $self->{$prop} = $v eq 'false' ? 0 : 1;
91b03282 2092 }
c5f71ad0
SV
2093 return $self->{$prop};
2094 }
91b03282 2095 }
9b981fc6
EW
2096}
2097
0b19138b 2098
321b1842
EW
2099my (%LOCKFILES, %INDEX_FILES);
2100END {
2101 unlink keys %LOCKFILES if %LOCKFILES;
2102 unlink keys %INDEX_FILES if %INDEX_FILES;
2103}
373274f9 2104
4bb9ed04
EW
2105sub resolve_local_globs {
2106 my ($url, $fetch, $glob_spec) = @_;
2107 return unless defined $glob_spec;
2108 my $ref = $glob_spec->{ref};
2109 my $path = $glob_spec->{path};
6f5748e1
AB
2110 foreach (command(qw#for-each-ref --format=%(refname) refs/#)) {
2111 next unless m#^$ref->{regex}$#;
4bb9ed04 2112 my $p = $1;
bf655fd7
RE
2113 my $pathname = desanitize_refname($path->full_path($p));
2114 my $refname = desanitize_refname($ref->full_path($p));
4bb9ed04
EW
2115 if (my $existing = $fetch->{$pathname}) {
2116 if ($existing ne $refname) {
2117 die "Refspec conflict:\n",
6f5748e1
AB
2118 "existing: $existing\n",
2119 " globbed: $refname\n";
4bb9ed04 2120 }
6f5748e1 2121 my $u = (::cmt_metadata("$refname"))[0];
4e9f6cc7 2122 $u =~ s!^\Q$url\E(/|$)!! or die
6f5748e1 2123 "$refname: '$url' not found in '$u'\n";
4bb9ed04
EW
2124 if ($pathname ne $u) {
2125 warn "W: Refspec glob conflict ",
6f5748e1 2126 "(ref: $refname):\n",
4bb9ed04
EW
2127 "expected path: $pathname\n",
2128 " real path: $u\n",
2129 "Continuing ahead with $u\n";
2130 next;
2131 }
2132 } else {
4bb9ed04
EW
2133 $fetch->{$pathname} = $refname;
2134 }
2135 }
2136}
2137
e98671e5
EW
2138sub parse_revision_argument {
2139 my ($base, $head) = @_;
2140 if (!defined $::_revision || $::_revision eq 'BASE:HEAD') {
2141 return ($base, $head);
2142 }
2143 return ($1, $2) if ($::_revision =~ /^(\d+):(\d+)$/);
2144 return ($::_revision, $::_revision) if ($::_revision =~ /^\d+$/);
2145 return ($head, $head) if ($::_revision eq 'HEAD');
2146 return ($base, $1) if ($::_revision =~ /^BASE:(\d+)$/);
2147 return ($1, $head) if ($::_revision =~ /^(\d+):HEAD$/);
2148 die "revision argument: $::_revision not understood by git-svn\n";
2149}
2150
0af9c9f9 2151sub fetch_all {
4bb9ed04 2152 my ($repo_id, $remotes) = @_;
905f8b7d
EW
2153 if (ref $repo_id) {
2154 my $gs = $repo_id;
2155 $repo_id = undef;
2156 $repo_id = $gs->{repo_id};
2157 }
2158 $remotes ||= read_all_remotes();
7447b4bc
EW
2159 my $remote = $remotes->{$repo_id} or
2160 die "[svn-remote \"$repo_id\"] unknown\n";
e518192f 2161 my $fetch = $remote->{fetch};
7447b4bc 2162 my $url = $remote->{url} or die "svn-remote.$repo_id.url not defined\n";
e518192f 2163 my (@gs, @globs);
0af9c9f9 2164 my $ra = Git::SVN::Ra->new($url);
26a62d57 2165 my $uuid = $ra->get_uuid;
0af9c9f9 2166 my $head = $ra->get_latest_revnum;
577e9fca
EW
2167
2168 # ignore errors, $head revision may not even exist anymore
2169 eval { $ra->get_log("", $head, 0, 1, 0, 1, sub { $head = $_[1] }) };
2170 warn "W: $@\n" if $@;
2171
28710f74 2172 my $base = defined $fetch ? $head : 0;
e518192f
EW
2173
2174 # read the max revs for wildcard expansion (branches/*, tags/*)
2175 foreach my $t (qw/branches tags/) {
2176 defined $remote->{$t} or next;
62244069
MB
2177 push @globs, @{$remote->{$t}};
2178
93f2689c
EW
2179 my $max_rev = eval { tmp_config(qw/--int --get/,
2180 "svn-remote.$repo_id.${t}-maxRev") };
2181 if (defined $max_rev && ($max_rev < $base)) {
2182 $base = $max_rev;
d6d3346b
EW
2183 } elsif (!defined $max_rev) {
2184 $base = 0;
e518192f
EW
2185 }
2186 }
2187
db03cd24
EW
2188 if ($fetch) {
2189 foreach my $p (sort keys %$fetch) {
2190 my $gs = Git::SVN->new($fetch->{$p}, $repo_id, $p);
060610c5 2191 my $lr = $gs->rev_map_max;
db03cd24
EW
2192 if (defined $lr) {
2193 $base = $lr if ($lr < $base);
2194 }
2195 push @gs, $gs;
0af9c9f9 2196 }
0af9c9f9 2197 }
e98671e5
EW
2198
2199 ($base, $head) = parse_revision_argument($base, $head);
e518192f 2200 $ra->gs_fetch_loop_common($base, $head, \@gs, \@globs);
0af9c9f9
EW
2201}
2202
47e39c55
EW
2203sub read_all_remotes {
2204 my $r = {};
63c56022
JA
2205 my $use_svm_props = eval { command_oneline(qw/config --bool
2206 svn.useSvmProps/) };
2207 $use_svm_props = $use_svm_props eq 'true' if $use_svm_props;
ffd5c8e4 2208 my $svn_refspec = qr{\s*(.*?)\s*:\s*(.+?)\s*};
8b8fc068 2209 foreach (grep { s/^svn-remote\.// } command(qw/config -l/)) {
6f5748e1
AB
2210 if (m!^(.+)\.fetch=$svn_refspec$!) {
2211 my ($remote, $local_ref, $remote_ref) = ($1, $2, $3);
2212 die("svn-remote.$remote: remote ref '$remote_ref' "
2213 . "must start with 'refs/'\n")
2214 unless $remote_ref =~ m{^refs/};
46cb16fb 2215 $local_ref = uri_decode($local_ref);
46cf98ba 2216 $r->{$remote}->{fetch}->{$local_ref} = $remote_ref;
63c56022
JA
2217 $r->{$remote}->{svm} = {} if $use_svm_props;
2218 } elsif (m!^(.+)\.usesvmprops=\s*(.*)\s*$!) {
2219 $r->{$1}->{svm} = {};
47e39c55
EW
2220 } elsif (m!^(.+)\.url=\s*(.*)\s*$!) {
2221 $r->{$1}->{url} = $2;
12a296bc
AS
2222 } elsif (m!^(.+)\.pushurl=\s*(.*)\s*$!) {
2223 $r->{$1}->{pushurl} = $2;
cdb51a13
MO
2224 } elsif (m!^(.+)\.ignore-refs=\s*(.*)\s*$!) {
2225 $r->{$1}->{ignore_refs_regex} = $2;
6f5748e1
AB
2226 } elsif (m!^(.+)\.(branches|tags)=$svn_refspec$!) {
2227 my ($remote, $t, $local_ref, $remote_ref) =
2228 ($1, $2, $3, $4);
2229 die("svn-remote.$remote: remote ref '$remote_ref' ($t) "
2230 . "must start with 'refs/'\n")
2231 unless $remote_ref =~ m{^refs/};
46cb16fb 2232 $local_ref = uri_decode($local_ref);
62244069 2233 my $rs = {
6f5748e1
AB
2234 t => $t,
2235 remote => $remote,
07576208
JS
2236 path => Git::SVN::GlobSpec->new($local_ref, 1),
2237 ref => Git::SVN::GlobSpec->new($remote_ref, 0) };
4bb9ed04
EW
2238 if (length($rs->{ref}->{right}) != 0) {
2239 die "The '*' glob character must be the last ",
6f5748e1 2240 "character of '$remote_ref'\n";
4bb9ed04 2241 }
6f5748e1 2242 push @{ $r->{$remote}->{$t} }, $rs;
47e39c55
EW
2243 }
2244 }
63c56022
JA
2245
2246 map {
2247 if (defined $r->{$_}->{svm}) {
2248 my $svm;
2249 eval {
2250 my $section = "svn-remote.$_";
2251 $svm = {
2252 source => tmp_config('--get',
2253 "$section.svm-source"),
2254 replace => tmp_config('--get',
2255 "$section.svm-replace"),
2256 }
2257 };
2258 $r->{$_}->{svm} = $svm;
2259 }
2260 } keys %$r;
2261
cdb51a13
MO
2262 foreach my $remote (keys %$r) {
2263 foreach ( grep { defined $_ }
2264 map { $r->{$remote}->{$_} } qw(branches tags) ) {
2265 foreach my $rs ( @$_ ) {
2266 $rs->{ignore_refs_regex} =
2267 $r->{$remote}->{ignore_refs_regex};
2268 }
2269 }
2270 }
2271
47e39c55
EW
2272 $r;
2273}
2274
ecc712dd 2275sub init_vars {
94bc914c 2276 $_gc_nr = $_gc_period = 1000;
af788a6e
KW
2277 if (defined $_repack || defined $_repack_flags) {
2278 warn "Repack options are obsolete; they have no effect.\n";
2279 }
ecc712dd
EW
2280}
2281
b805b44a 2282sub verify_remotes_sanity {
536c4b09 2283 return unless -d $ENV{GIT_DIR};
b805b44a
EW
2284 my %seen;
2285 foreach (command(qw/config -l/)) {
2286 if (m!^svn-remote\.(?:.+)\.fetch=.*:refs/remotes/(\S+)\s*$!) {
2287 if ($seen{$1}) {
2288 die "Remote ref refs/remote/$1 is tracked by",
2289 "\n \"$_\"\nand\n \"$seen{$1}\"\n",
2290 "Please resolve this ambiguity in ",
2291 "your git configuration file before ",
2292 "continuing\n";
2293 }
2294 $seen{$1} = $_;
2295 }
2296 }
2297}
2298
e6434f87
EW
2299sub find_existing_remote {
2300 my ($url, $remotes) = @_;
befc9adc 2301 return undef if $no_reuse_existing;
e6434f87
EW
2302 my $existing;
2303 foreach my $repo_id (keys %$remotes) {
2304 my $u = $remotes->{$repo_id}->{url} or next;
2305 next if $u ne $url;
2306 $existing = $repo_id;
2307 last;
2308 }
2309 $existing;
2310}
b805b44a 2311
e6434f87 2312sub init_remote_config {
d8115c51 2313 my ($self, $url, $no_write) = @_;
e6434f87
EW
2314 $url =~ s!/+$!!; # strip trailing slash
2315 my $r = read_all_remotes();
2316 my $existing = find_existing_remote($url, $r);
2317 if ($existing) {
e518192f
EW
2318 unless ($no_write) {
2319 print STDERR "Using existing ",
2320 "[svn-remote \"$existing\"]\n";
2321 }
e6434f87 2322 $self->{repo_id} = $existing;
4a1bb4c3 2323 } elsif ($_minimize_url) {
e6434f87
EW
2324 my $min_url = Git::SVN::Ra->new($url)->minimize_url;
2325 $existing = find_existing_remote($min_url, $r);
2326 if ($existing) {
e518192f
EW
2327 unless ($no_write) {
2328 print STDERR "Using existing ",
2329 "[svn-remote \"$existing\"]\n";
2330 }
e6434f87
EW
2331 $self->{repo_id} = $existing;
2332 }
2333 if ($min_url ne $url) {
e518192f
EW
2334 unless ($no_write) {
2335 print STDERR "Using higher level of URL: ",
2336 "$url => $min_url\n";
2337 }
e6434f87
EW
2338 my $old_path = $self->{path};
2339 $self->{path} = $url;
4e9f6cc7 2340 $self->{path} =~ s!^\Q$min_url\E(/|$)!!;
e6434f87
EW
2341 if (length $old_path) {
2342 $self->{path} .= "/$old_path";
2343 }
2344 $url = $min_url;
2345 }
2346 }
2347 my $orig_url;
2348 if (!$existing) {
b805b44a 2349 # verify that we aren't overwriting anything:
e6434f87 2350 $orig_url = eval {
706587fc 2351 command_oneline('config', '--get',
e6434f87 2352 "svn-remote.$self->{repo_id}.url")
706587fc 2353 };
b805b44a 2354 if ($orig_url && ($orig_url ne $url)) {
e6434f87 2355 die "svn-remote.$self->{repo_id}.url already set: ",
b805b44a
EW
2356 "$orig_url\nwanted to set to: $url\n";
2357 }
9b981fc6 2358 }
e6434f87 2359 my ($xrepo_id, $xpath) = find_ref($self->refname);
6f5748e1 2360 if (!$no_write && defined $xpath) {
e6434f87 2361 die "svn-remote.$xrepo_id.fetch already set to track ",
6f5748e1 2362 "$xpath:", $self->refname, "\n";
e6434f87 2363 }
d8115c51
EW
2364 unless ($no_write) {
2365 command_noisy('config',
2366 "svn-remote.$self->{repo_id}.url", $url);
46cf98ba 2367 $self->{path} =~ s{^/}{};
5268f9ed 2368 $self->{path} =~ s{%([0-9A-F]{2})}{chr hex($1)}ieg;
d8115c51
EW
2369 command_noisy('config', '--add',
2370 "svn-remote.$self->{repo_id}.fetch",
2371 "$self->{path}:".$self->refname);
2372 }
9b981fc6 2373 $self->{url} = $url;
e6434f87
EW
2374}
2375
a8ae2623
EW
2376sub find_by_url { # repos_root and, path are optional
2377 my ($class, $full_url, $repos_root, $path) = @_;
56973d20 2378
1a97a506 2379 return undef unless defined $full_url;
56973d20
AR
2380 remove_username($full_url);
2381 remove_username($repos_root) if defined $repos_root;
a8ae2623
EW
2382 my $remotes = read_all_remotes();
2383 if (defined $full_url && defined $repos_root && !defined $path) {
2384 $path = $full_url;
2385 $path =~ s#^\Q$repos_root\E(?:/|$)##;
2386 }
2387 foreach my $repo_id (keys %$remotes) {
2388 my $u = $remotes->{$repo_id}->{url} or next;
56973d20 2389 remove_username($u);
a8ae2623
EW
2390 next if defined $repos_root && $repos_root ne $u;
2391
2392 my $fetch = $remotes->{$repo_id}->{fetch} || {};
62244069
MB
2393 foreach my $t (qw/branches tags/) {
2394 foreach my $globspec (@{$remotes->{$repo_id}->{$t}}) {
2395 resolve_local_globs($u, $fetch, $globspec);
2396 }
a8ae2623
EW
2397 }
2398 my $p = $path;
0bb91d9a 2399 my $rwr = rewrite_root({repo_id => $repo_id});
63c56022
JA
2400 my $svm = $remotes->{$repo_id}->{svm}
2401 if defined $remotes->{$repo_id}->{svm};
a8ae2623
EW
2402 unless (defined $p) {
2403 $p = $full_url;
0bb91d9a 2404 my $z = $u;
63c56022 2405 my $prefix = '';
0bb91d9a
JG
2406 if ($rwr) {
2407 $z = $rwr;
1b7e543a 2408 remove_username($z);
63c56022
JA
2409 } elsif (defined $svm) {
2410 $z = $svm->{source};
2411 $prefix = $svm->{replace};
2412 $prefix =~ s#^\Q$u\E(?:/|$)##;
2413 $prefix =~ s#/$##;
0bb91d9a 2414 }
63c56022 2415 $p =~ s#^\Q$z\E(?:/|$)#$prefix# or next;
a8ae2623
EW
2416 }
2417 foreach my $f (keys %$fetch) {
2418 next if $f ne $p;
2419 return Git::SVN->new($fetch->{$f}, $repo_id, $f);
2420 }
2421 }
2422 undef;
2423}
2424
e6434f87 2425sub init {
d8115c51 2426 my ($class, $url, $path, $repo_id, $ref_id, $no_write) = @_;
e6434f87
EW
2427 my $self = _new($class, $repo_id, $ref_id, $path);
2428 if (defined $url) {
d8115c51 2429 $self->init_remote_config($url, $no_write);
e6434f87 2430 }
9b981fc6
EW
2431 $self;
2432}
2433
706587fc
EW
2434sub find_ref {
2435 my ($ref_id) = @_;
2436 foreach (command(qw/config -l/)) {
2437 next unless m!^svn-remote\.(.+)\.fetch=
ffd5c8e4 2438 \s*(.*?)\s*:\s*(.+?)\s*$!x;
706587fc
EW
2439 my ($repo_id, $path, $ref) = ($1, $2, $3);
2440 if ($ref eq $ref_id) {
2441 $path = '' if ($path =~ m#^\./?#);
2442 return ($repo_id, $path);
2443 }
2444 }
2445 (undef, undef, undef);
2446}
2447
9b981fc6 2448sub new {
706587fc
EW
2449 my ($class, $ref_id, $repo_id, $path) = @_;
2450 if (defined $ref_id && !defined $repo_id && !defined $path) {
2451 ($repo_id, $path) = find_ref($ref_id);
2452 if (!defined $repo_id) {
2453 die "Could not find a \"svn-remote.*.fetch\" key ",
2454 "in the repository configuration matching: ",
6f5748e1 2455 "$ref_id\n";
706587fc
EW
2456 }
2457 }
2458 my $self = _new($class, $repo_id, $ref_id, $path);
8b8fc068
EW
2459 if (!defined $self->{path} || !length $self->{path}) {
2460 my $fetch = command_oneline('config', '--get',
2461 "svn-remote.$repo_id.fetch",
6f5748e1 2462 ":$ref_id\$") or
8b8fc068 2463 die "Failed to read \"svn-remote.$repo_id.fetch\" ",
6f5748e1 2464 "\":$ref_id\$\" in config\n";
8b8fc068
EW
2465 ($self->{path}, undef) = split(/\s*:\s*/, $fetch);
2466 }
b1a954a3
EW
2467 $self->{path} =~ s{/+}{/}g;
2468 $self->{path} =~ s{\A/}{};
2469 $self->{path} =~ s{/\z}{};
706587fc
EW
2470 $self->{url} = command_oneline('config', '--get',
2471 "svn-remote.$repo_id.url") or
2472 die "Failed to read \"svn-remote.$repo_id.url\" in config\n";
12a296bc
AS
2473 $self->{pushurl} = eval { command_oneline('config', '--get',
2474 "svn-remote.$repo_id.pushurl") };
d6d3346b 2475 $self->rebuild;
9b981fc6
EW
2476 $self;
2477}
2478
bf655fd7 2479sub refname {
6f5748e1 2480 my ($refname) = $_[0]->{ref_id} ;
bf655fd7
RE
2481
2482 # It cannot end with a slash /, we'll throw up on this because
2483 # SVN can't have directories with a slash in their name, either:
2484 if ($refname =~ m{/$}) {
2485 die "ref: '$refname' ends with a trailing slash, this is ",
2486 "not permitted by git nor Subversion\n";
2487 }
2488
2489 # It cannot have ASCII control character space, tilde ~, caret ^,
2490 # colon :, question-mark ?, asterisk *, space, or open bracket [
2491 # anywhere.
2492 #
2493 # Additionally, % must be escaped because it is used for escaping
2494 # and we want our escaped refname to be reversible
2495 $refname =~ s{([ \%~\^:\?\*\[\t])}{uc sprintf('%%%02x',ord($1))}eg;
2496
2497 # no slash-separated component can begin with a dot .
2498 # /.* becomes /%2E*
2499 $refname =~ s{/\.}{/%2E}g;
2500
2501 # It cannot have two consecutive dots .. anywhere
2502 # .. becomes %2E%2E
2503 $refname =~ s{\.\.}{%2E%2E}g;
2504
73d41955
TS
2505 # trailing dots and .lock are not allowed
2506 # .$ becomes %2E and .lock becomes %2Elock
2507 $refname =~ s{\.(?=$|lock$)}{%2E};
2508
2509 # the sequence @{ is used to access the reflog
2510 # @{ becomes %40{
2511 $refname =~ s{\@\{}{%40\{}g;
2512
bf655fd7
RE
2513 return $refname;
2514}
2515
2516sub desanitize_refname {
2517 my ($refname) = @_;
2518 $refname =~ s{%(?:([0-9A-F]{2}))}{chr hex($1)}eg;
2519 return $refname;
2520}
9b981fc6 2521
26a62d57
EW
2522sub svm_uuid {
2523 my ($self) = @_;
2524 return $self->{svm}->{uuid} if $self->svm;
2525 $self->ra;
2526 unless ($self->{svm}) {
2527 die "SVM UUID not cached, and reading remotely failed\n";
2528 }
2529 $self->{svm}->{uuid};
2530}
8a49ee97 2531
26a62d57
EW
2532sub svm {
2533 my ($self) = @_;
2534 return $self->{svm} if $self->{svm};
2535 my $svm;
8a49ee97
EW
2536 # see if we have it in our config, first:
2537 eval {
26a62d57
EW
2538 my $section = "svn-remote.$self->{repo_id}";
2539 $svm = {
93f2689c
EW
2540 source => tmp_config('--get', "$section.svm-source"),
2541 uuid => tmp_config('--get', "$section.svm-uuid"),
befc9adc 2542 replace => tmp_config('--get', "$section.svm-replace"),
8a49ee97
EW
2543 }
2544 };
befc9adc
EW
2545 if ($svm && $svm->{source} && $svm->{uuid} && $svm->{replace}) {
2546 $self->{svm} = $svm;
2547 }
26a62d57
EW
2548 $self->{svm};
2549}
2550
2551sub _set_svm_vars {
2552 my ($self, $ra) = @_;
db03cd24
EW
2553 return $ra if $self->svm;
2554
2555 my @err = ( "useSvmProps set, but failed to read SVM properties\n",
befc9adc 2556 "(svm:source, svm:uuid) ",
db03cd24
EW
2557 "from the following URLs:\n" );
2558 sub read_svm_props {
befc9adc
EW
2559 my ($self, $ra, $path, $r) = @_;
2560 my $props = ($ra->get_dir($path, $r))[2];
db03cd24 2561 my $src = $props->{'svm:source'};
db03cd24 2562 my $uuid = $props->{'svm:uuid'};
befc9adc 2563 return undef if (!$src || !$uuid);
26a62d57 2564
befc9adc 2565 chomp($src, $uuid);
26a62d57 2566
b3e95936 2567 $uuid =~ m{^[0-9a-f\-]{30,}$}i
db03cd24 2568 or die "doesn't look right - svm:uuid is '$uuid'\n";
befc9adc
EW
2569
2570 # the '!' is used to mark the repos_root!/relative/path
2571 $src =~ s{/?!/?}{/};
db03cd24 2572 $src =~ s{/+$}{}; # no trailing slashes please
befc9adc 2573 # username is of no interest
8a49ee97 2574 $src =~ s{(^[a-z\+]*://)[^/@]*@}{$1};
8a49ee97 2575
befc9adc
EW
2576 my $replace = $ra->{url};
2577 $replace .= "/$path" if length $path;
2578
db03cd24 2579 my $section = "svn-remote.$self->{repo_id}";
befc9adc
EW
2580 tmp_config("$section.svm-source", $src);
2581 tmp_config("$section.svm-replace", $replace);
2582 tmp_config("$section.svm-uuid", $uuid);
2583 $self->{svm} = {
2584 source => $src,
2585 uuid => $uuid,
2586 replace => $replace
2587 };
db03cd24
EW
2588 }
2589
2590 my $r = $ra->get_latest_revnum;
2591 my $path = $self->{path};
befc9adc 2592 my %tried;
db03cd24 2593 while (length $path) {
befc9adc
EW
2594 unless ($tried{"$self->{url}/$path"}) {
2595 return $ra if $self->read_svm_props($ra, $path, $r);
2596 $tried{"$self->{url}/$path"} = 1;
db03cd24 2597 }
befc9adc 2598 $path =~ s#/?[^/]+$##;
8a49ee97 2599 }
befc9adc
EW
2600 die "Path: '$path' should be ''\n" if $path ne '';
2601 return $ra if $self->read_svm_props($ra, $path, $r);
2602 $tried{"$self->{url}/$path"} = 1;
db03cd24
EW
2603
2604 if ($ra->{repos_root} eq $self->{url}) {
befc9adc 2605 die @err, (map { " $_\n" } keys %tried), "\n";
db03cd24
EW
2606 }
2607
2608 # nope, make sure we're connected to the repository root:
2609 my $ok;
2610 my @tried_b;
2611 $path = $ra->{svn_path};
db03cd24
EW
2612 $ra = Git::SVN::Ra->new($ra->{repos_root});
2613 while (length $path) {
befc9adc
EW
2614 unless ($tried{"$ra->{url}/$path"}) {
2615 $ok = $self->read_svm_props($ra, $path, $r);
2616 last if $ok;
2617 $tried{"$ra->{url}/$path"} = 1;
2618 }
2619 $path =~ s#/?[^/]+$##;
db03cd24 2620 }
befc9adc
EW
2621 die "Path: '$path' should be ''\n" if $path ne '';
2622 $ok ||= $self->read_svm_props($ra, $path, $r);
2623 $tried{"$ra->{url}/$path"} = 1;
db03cd24 2624 if (!$ok) {
befc9adc 2625 die @err, (map { " $_\n" } keys %tried), "\n";
db03cd24
EW
2626 }
2627 Git::SVN::Ra->new($self->{url});
8a49ee97
EW
2628}
2629
62e349d2
EW
2630sub svnsync {
2631 my ($self) = @_;
2632 return $self->{svnsync} if $self->{svnsync};
2633
2634 if ($self->no_metadata) {
2635 die "Can't have both 'noMetadata' and ",
2636 "'useSvnsyncProps' options set!\n";
2637 }
2638 if ($self->rewrite_root) {
2639 die "Can't have both 'useSvnsyncProps' and 'rewriteRoot' ",
2640 "options set!\n";
2641 }
3e18ce1a
JS
2642 if ($self->rewrite_uuid) {
2643 die "Can't have both 'useSvnsyncProps' and 'rewriteUUID' ",
2644 "options set!\n";
2645 }
62e349d2
EW
2646
2647 my $svnsync;
2648 # see if we have it in our config, first:
2649 eval {
2650 my $section = "svn-remote.$self->{repo_id}";
98fa5b68
EW
2651
2652 my $url = tmp_config('--get', "$section.svnsync-url");
2653 ($url) = ($url =~ m{^([a-z\+]+://\S+)$}) or
2654 die "doesn't look right - svn:sync-from-url is '$url'\n";
2655
2656 my $uuid = tmp_config('--get', "$section.svnsync-uuid");
b3e95936 2657 ($uuid) = ($uuid =~ m{^([0-9a-f\-]{30,})$}i) or
98fa5b68
EW
2658 die "doesn't look right - svn:sync-from-uuid is '$uuid'\n";
2659
2660 $svnsync = { url => $url, uuid => $uuid }
62e349d2
EW
2661 };
2662 if ($svnsync && $svnsync->{url} && $svnsync->{uuid}) {
2663 return $self->{svnsync} = $svnsync;
2664 }
2665
2666 my $err = "useSvnsyncProps set, but failed to read " .
2667 "svnsync property: svn:sync-from-";
2668 my $rp = $self->ra->rev_proplist(0);
2669
2670 my $url = $rp->{'svn:sync-from-url'} or die $err . "url\n";
98fa5b68 2671 ($url) = ($url =~ m{^([a-z\+]+://\S+)$}) or
62e349d2
EW
2672 die "doesn't look right - svn:sync-from-url is '$url'\n";
2673
2674 my $uuid = $rp->{'svn:sync-from-uuid'} or die $err . "uuid\n";
b3e95936 2675 ($uuid) = ($uuid =~ m{^([0-9a-f\-]{30,})$}i) or
62e349d2
EW
2676 die "doesn't look right - svn:sync-from-uuid is '$uuid'\n";
2677
2678 my $section = "svn-remote.$self->{repo_id}";
2679 tmp_config('--add', "$section.svnsync-uuid", $uuid);
2680 tmp_config('--add', "$section.svnsync-url", $url);
2681 return $self->{svnsync} = { url => $url, uuid => $uuid };
2682}
2683
26a62d57
EW
2684# this allows us to memoize our SVN::Ra UUID locally and avoid a
2685# remote lookup (useful for 'git svn log').
2686sub ra_uuid {
2687 my ($self) = @_;
2688 unless ($self->{ra_uuid}) {
2689 my $key = "svn-remote.$self->{repo_id}.uuid";
2690 my $uuid = eval { tmp_config('--get', $key) };
b3e95936 2691 if (!$@ && $uuid && $uuid =~ /^([a-f\d\-]{30,})$/i) {
26a62d57
EW
2692 $self->{ra_uuid} = $uuid;
2693 } else {
2694 die "ra_uuid called without URL\n" unless $self->{url};
2695 $self->{ra_uuid} = $self->ra->get_uuid;
2696 tmp_config('--add', $key, $self->{ra_uuid});
2697 }
2698 }
2699 $self->{ra_uuid};
2700}
2701
a5460eb7
EW
2702sub _set_repos_root {
2703 my ($self, $repos_root) = @_;
2704 my $k = "svn-remote.$self->{repo_id}.reposRoot";
2705 $repos_root ||= $self->ra->{repos_root};
2706 tmp_config($k, $repos_root);
2707 $repos_root;
2708}
2709
2710sub repos_root {
2711 my ($self) = @_;
2712 my $k = "svn-remote.$self->{repo_id}.reposRoot";
2713 eval { tmp_config('--get', $k) } || $self->_set_repos_root;
2714}
2715
9b981fc6
EW
2716sub ra {
2717 my ($self) = shift;
8a49ee97 2718 my $ra = Git::SVN::Ra->new($self->{url});
a5460eb7 2719 $self->_set_repos_root($ra->{repos_root});
91b03282
EW
2720 if ($self->use_svm_props && !$self->{svm}) {
2721 if ($self->no_metadata) {
97ae0911
EW
2722 die "Can't have both 'noMetadata' and ",
2723 "'useSvmProps' options set!\n";
62e349d2
EW
2724 } elsif ($self->use_svnsync_props) {
2725 die "Can't have both 'useSvnsyncProps' and ",
2726 "'useSvmProps' options set!\n";
91b03282 2727 }
26a62d57 2728 $ra = $self->_set_svm_vars($ra);
8a49ee97
EW
2729 $self->{-want_revprops} = 1;
2730 }
2731 $ra;
9b981fc6
EW
2732}
2733
01bdab84
BS
2734# prop_walk(PATH, REV, SUB)
2735# -------------------------
2736# Recursively traverse PATH at revision REV and invoke SUB for each
2737# directory that contains a SVN property. SUB will be invoked as
2738# follows: &SUB(gs, path, props); where `gs' is this instance of
2739# Git::SVN, `path' the path to the directory where the properties
2740# `props' were found. The `path' will be relative to point of checkout,
2741# that is, if url://repo/trunk is the current Git branch, and that
2742# directory contains a sub-directory `d', SUB will be invoked with `/d/'
2743# as `path' (note the trailing `/').
2744sub prop_walk {
2745 my ($self, $path, $rev, $sub) = @_;
2746
35cda061 2747 $path =~ s#^/##;
01bdab84
BS
2748 my ($dirent, undef, $props) = $self->ra->get_dir($path, $rev);
2749 $path =~ s#^/*#/#g;
9b981fc6 2750 my $p = $path;
01bdab84
BS
2751 # Strip the irrelevant part of the path.
2752 $p =~ s#^/+\Q$self->{path}\E(/|$)#/#;
2753 # Ensure the path is terminated by a `/'.
2754 $p =~ s#/*$#/#;
2755
2756 # The properties contain all the internal SVN stuff nobody
2757 # (usually) cares about.
2758 my $interesting_props = 0;
2759 foreach (keys %{$props}) {
2760 # If it doesn't start with `svn:', it must be a
2761 # user-defined property.
2762 ++$interesting_props and next if $_ !~ /^svn:/;
2763 # FIXME: Fragile, if SVN adds new public properties,
2764 # this needs to be updated.
2765 ++$interesting_props if /^svn:(?:ignore|keywords|executable
2766 |eol-style|mime-type
2767 |externals|needs-lock)$/x;
2768 }
2769 &$sub($self, $p, $props) if $interesting_props;
2770
9b981fc6 2771 foreach (sort keys %$dirent) {
0dc03d6a 2772 next if $dirent->{$_}->{kind} != $SVN::Node::dir;
b7166cce 2773 $self->prop_walk($self->{path} . $p . $_, $rev, $sub);
9b981fc6
EW
2774 }
2775}
2776
3ebe8df7
EW
2777sub last_rev { ($_[0]->last_rev_commit)[0] }
2778sub last_commit { ($_[0]->last_rev_commit)[1] }
2779
9b981fc6
EW
2780# returns the newest SVN revision number and newest commit SHA1
2781sub last_rev_commit {
2782 my ($self) = @_;
2783 if (defined $self->{last_rev} && defined $self->{last_commit}) {
2784 return ($self->{last_rev}, $self->{last_commit});
2785 }
d2866f9e 2786 my $c = ::verify_ref($self->refname.'^0');
91b03282 2787 if ($c && !$self->use_svm_props && !$self->no_metadata) {
d2866f9e 2788 my $rev = (::cmt_metadata($c))[1];
9b981fc6
EW
2789 if (defined $rev) {
2790 ($self->{last_rev}, $self->{last_commit}) = ($rev, $c);
2791 return ($rev, $c);
2792 }
2793 }
060610c5
EW
2794 my $map_path = $self->map_path;
2795 unless (-e $map_path) {
26a62d57
EW
2796 ($self->{last_rev}, $self->{last_commit}) = (undef, undef);
2797 return (undef, undef);
2798 }
66ab84b9 2799 my ($rev, $commit) = $self->rev_map_max(1);
060610c5
EW
2800 ($self->{last_rev}, $self->{last_commit}) = ($rev, $commit);
2801 return ($rev, $commit);
9b981fc6
EW
2802}
2803
3ebe8df7
EW
2804sub get_fetch_range {
2805 my ($self, $min, $max) = @_;
2806 $max ||= $self->ra->get_latest_revnum;
060610c5 2807 $min ||= $self->rev_map_max;
3ebe8df7 2808 (++$min, $max);
9b981fc6
EW
2809}
2810
8a49ee97 2811sub tmp_config {
93f2689c 2812 my (@args) = @_;
b7e5348c
EW
2813 my $old_def_config = "$ENV{GIT_DIR}/svn/config";
2814 my $config = "$ENV{GIT_DIR}/svn/.metadata";
38570a47 2815 if (! -f $config && -f $old_def_config) {
b7e5348c
EW
2816 rename $old_def_config, $config or
2817 die "Failed rename $old_def_config => $config: $!\n";
2818 }
8a49ee97 2819 my $old_config = $ENV{GIT_CONFIG};
93f2689c 2820 $ENV{GIT_CONFIG} = $config;
8a49ee97 2821 $@ = undef;
b4d57e5e
EW
2822 my @ret = eval {
2823 unless (-f $config) {
2824 mkfile($config);
2825 open my $fh, '>', $config or
2826 die "Can't open $config: $!\n";
2827 print $fh "; This file is used internally by ",
2828 "git-svn\n" or die
2829 "Couldn't write to $config: $!\n";
2830 print $fh "; You should not have to edit it\n" or
2831 die "Couldn't write to $config: $!\n";
2832 close $fh or die "Couldn't close $config: $!\n";
2833 }
2834 command('config', @args);
2835 };
8a49ee97
EW
2836 my $err = $@;
2837 if (defined $old_config) {
2838 $ENV{GIT_CONFIG} = $old_config;
2839 } else {
2840 delete $ENV{GIT_CONFIG};
2841 }
2842 die $err if $err;
2843 wantarray ? @ret : $ret[0];
2844}
2845
9b981fc6
EW
2846sub tmp_index_do {
2847 my ($self, $sub) = @_;
2848 my $old_index = $ENV{GIT_INDEX_FILE};
2849 $ENV{GIT_INDEX_FILE} = $self->{index};
8a49ee97 2850 $@ = undef;
b4d57e5e
EW
2851 my @ret = eval {
2852 my ($dir, $base) = ($self->{index} =~ m#^(.*?)/?([^/]+)$#);
2853 mkpath([$dir]) unless -d $dir;
2854 &$sub;
2855 };
8a49ee97
EW
2856 my $err = $@;
2857 if (defined $old_index) {
9b981fc6
EW
2858 $ENV{GIT_INDEX_FILE} = $old_index;
2859 } else {
2860 delete $ENV{GIT_INDEX_FILE};
2861 }
8a49ee97 2862 die $err if $err;
9b981fc6
EW
2863 wantarray ? @ret : $ret[0];
2864}
2865
2866sub assert_index_clean {
2867 my ($self, $treeish) = @_;
2868
2869 $self->tmp_index_do(sub {
2870 command_noisy('read-tree', $treeish) unless -e $self->{index};
2871 my $x = command_oneline('write-tree');
2872 my ($y) = (command(qw/cat-file commit/, $treeish) =~
2873 /^tree ($::sha1)/mo);
e8d120bd
EW
2874 return if $y eq $x;
2875
2876 warn "Index mismatch: $y != $x\nrereading $treeish\n";
2877 unlink $self->{index} or die "unlink $self->{index}: $!\n";
2878 command_noisy('read-tree', $treeish);
9b981fc6
EW
2879 $x = command_oneline('write-tree');
2880 if ($y ne $x) {
2881 ::fatal "trees ($treeish) $y != $x\n",
207f1a75 2882 "Something is seriously wrong...";
9b981fc6
EW
2883 }
2884 });
2885}
2886
2887sub get_commit_parents {
0af9c9f9 2888 my ($self, $log_entry) = @_;
9b981fc6 2889 my (%seen, @ret, @tmp);
0af9c9f9
EW
2890 # legacy support for 'set-tree'; this is only used by set_tree_cb:
2891 if (my $ip = $self->{inject_parents}) {
2892 if (my $commit = delete $ip->{$log_entry->{revision}}) {
2893 push @tmp, $commit;
9b981fc6
EW
2894 }
2895 }
d2866f9e 2896 if (my $cur = ::verify_ref($self->refname.'^0')) {
9b981fc6
EW
2897 push @tmp, $cur;
2898 }
733a65aa
EW
2899 if (my $ipd = $self->{inject_parents_dcommit}) {
2900 if (my $commit = delete $ipd->{$log_entry->{revision}}) {
2901 push @tmp, @$commit;
2902 }
2903 }
44320b9e 2904 push @tmp, $_ foreach (@{$log_entry->{parents}}, @tmp);
9b981fc6
EW
2905 while (my $p = shift @tmp) {
2906 next if $seen{$p};
2907 $seen{$p} = 1;
2908 push @ret, $p;
9b981fc6
EW
2909 }
2910 @ret;
2911}
2912
aea736cc
EW
2913sub rewrite_root {
2914 my ($self) = @_;
2915 return $self->{-rewrite_root} if exists $self->{-rewrite_root};
2916 my $k = "svn-remote.$self->{repo_id}.rewriteRoot";
2917 my $rwr = eval { command_oneline(qw/config --get/, $k) };
2918 if ($rwr) {
2919 $rwr =~ s#/+$##;
2920 if ($rwr !~ m#^[a-z\+]+://#) {
2921 die "$rwr is not a valid URL (key: $k)\n";
2922 }
2923 }
2924 $self->{-rewrite_root} = $rwr;
2925}
2926
3e18ce1a
JS
2927sub rewrite_uuid {
2928 my ($self) = @_;
2929 return $self->{-rewrite_uuid} if exists $self->{-rewrite_uuid};
2930 my $k = "svn-remote.$self->{repo_id}.rewriteUUID";
2931 my $rwid = eval { command_oneline(qw/config --get/, $k) };
2932 if ($rwid) {
2933 $rwid =~ s#/+$##;
2934 if ($rwid !~ m#^[a-f0-9]{8}-(?:[a-f0-9]{4}-){3}[a-f0-9]{12}$#) {
2935 die "$rwid is not a valid UUID (key: $k)\n";
2936 }
2937 }
2938 $self->{-rewrite_uuid} = $rwid;
2939}
2940
aea736cc
EW
2941sub metadata_url {
2942 my ($self) = @_;
2943 ($self->rewrite_root || $self->{url}) .
2944 (length $self->{path} ? '/' . $self->{path} : '');
2945}
2946
706587fc 2947sub full_url {
9b981fc6 2948 my ($self) = @_;
5d3b7cd5 2949 $self->{url} . (length $self->{path} ? '/' . $self->{path} : '');
9b981fc6
EW
2950}
2951
12a296bc
AS
2952sub full_pushurl {
2953 my ($self) = @_;
2954 if ($self->{pushurl}) {
2955 return $self->{pushurl} . (length $self->{path} ? '/' .
2956 $self->{path} : '');
2957 } else {
2958 return $self->full_url;
2959 }
2960}
ad94802a
EW
2961
2962sub set_commit_header_env {
2963 my ($log_entry) = @_;
2964 my %env;
2965 foreach my $ned (qw/NAME EMAIL DATE/) {
2966 foreach my $ac (qw/AUTHOR COMMITTER/) {
2967 $env{"GIT_${ac}_${ned}"} = $ENV{"GIT_${ac}_${ned}"};
2968 }
9b981fc6 2969 }
ad94802a 2970
70ae04e4
AW
2971 $ENV{GIT_AUTHOR_NAME} = $log_entry->{name};
2972 $ENV{GIT_AUTHOR_EMAIL} = $log_entry->{email};
44320b9e 2973 $ENV{GIT_AUTHOR_DATE} = $ENV{GIT_COMMITTER_DATE} = $log_entry->{date};
9b981fc6 2974
70ae04e4
AW
2975 $ENV{GIT_COMMITTER_NAME} = (defined $log_entry->{commit_name})
2976 ? $log_entry->{commit_name}
2977 : $log_entry->{name};
2978 $ENV{GIT_COMMITTER_EMAIL} = (defined $log_entry->{commit_email})
2979 ? $log_entry->{commit_email}
2980 : $log_entry->{email};
ad94802a
EW
2981 \%env;
2982}
70ae04e4 2983
ad94802a
EW
2984sub restore_commit_header_env {
2985 my ($env) = @_;
2986 foreach my $ned (qw/NAME EMAIL DATE/) {
2987 foreach my $ac (qw/AUTHOR COMMITTER/) {
2988 my $k = "GIT_${ac}_${ned}";
2989 if (defined $env->{$k}) {
2990 $ENV{$k} = $env->{$k};
2991 } else {
2992 delete $ENV{$k};
2993 }
2994 }
2995 }
2996}
2997
94bc914c
KW
2998sub gc {
2999 command_noisy('gc', '--auto');
3000};
3001
ad94802a
EW
3002sub do_git_commit {
3003 my ($self, $log_entry) = @_;
3004 my $lr = $self->last_rev;
3005 if (defined $lr && $lr >= $log_entry->{revision}) {
3006 die "Last fetched revision of ", $self->refname,
3007 " was r$lr, but we are about to fetch: ",
3008 "r$log_entry->{revision}!\n";
3009 }
3010 if (my $c = $self->rev_map_get($log_entry->{revision})) {
3011 croak "$log_entry->{revision} = $c already exists! ",
3012 "Why are we refetching it?\n";
3013 }
3014 my $old_env = set_commit_header_env($log_entry);
44320b9e 3015 my $tree = $log_entry->{tree};
9b981fc6
EW
3016 if (!defined $tree) {
3017 $tree = $self->tmp_index_do(sub {
3018 command_oneline('write-tree') });
3019 }
3020 die "Tree is not a valid sha1: $tree\n" if $tree !~ /^$::sha1$/o;
3021
e855bfc0 3022 my @exec = ('git', 'commit-tree', $tree);
0af9c9f9 3023 foreach ($self->get_commit_parents($log_entry)) {
9b981fc6
EW
3024 push @exec, '-p', $_;
3025 }
3026 defined(my $pid = open3(my $msg_fh, my $out_fh, '>&STDERR', @exec))
3027 or croak $!;
16fc08e2
EW
3028 binmode $msg_fh;
3029
3030 # we always get UTF-8 from SVN, but we may want our commits in
3031 # a different encoding.
3032 if (my $enc = Git::config('i18n.commitencoding')) {
3033 require Encode;
3034 Encode::from_to($log_entry->{log}, 'UTF-8', $enc);
3035 }
44320b9e 3036 print $msg_fh $log_entry->{log} or croak $!;
ad94802a 3037 restore_commit_header_env($old_env);
91b03282 3038 unless ($self->no_metadata) {
8a49ee97
EW
3039 print $msg_fh "\ngit-svn-id: $log_entry->{metadata}\n"
3040 or croak $!;
9760adcc 3041 }
9b981fc6
EW
3042 $msg_fh->flush == 0 or croak $!;
3043 close $msg_fh or croak $!;
3044 chomp(my $commit = do { local $/; <$out_fh> });
3045 close $out_fh or croak $!;
3046 waitpid $pid, 0;
3047 croak $? if $?;
3048 if ($commit !~ /^$::sha1$/o) {
3049 die "Failed to commit, invalid sha1: $commit\n";
3050 }
3051
060610c5 3052 $self->rev_map_set($log_entry->{revision}, $commit, 1);
9b981fc6 3053
44320b9e 3054 $self->{last_rev} = $log_entry->{revision};
9b981fc6 3055 $self->{last_commit} = $commit;
49750f30 3056 print "r$log_entry->{revision}" unless $::_q > 1;
8a49ee97 3057 if (defined $log_entry->{svm_revision}) {
49750f30 3058 print " (\@$log_entry->{svm_revision})" unless $::_q > 1;
060610c5 3059 $self->rev_map_set($log_entry->{svm_revision}, $commit,
26a62d57 3060 0, $self->svm_uuid);
8a49ee97 3061 }
49750f30 3062 print " = $commit ($self->{ref_id})\n" unless $::_q > 1;
94bc914c
KW
3063 if (--$_gc_nr == 0) {
3064 $_gc_nr = $_gc_period;
3065 gc();
3066 }
9b981fc6
EW
3067 return $commit;
3068}
3069
fbcc1737
EW
3070sub match_paths {
3071 my ($self, $paths, $r) = @_;
4e9f6cc7 3072 return 1 if $self->{path} eq '';
d542aedb
EW
3073 if (my $path = $paths->{"/$self->{path}"}) {
3074 return ($path->{action} eq 'D') ? 0 : 1;
3075 }
0b2af457 3076 $self->{path_regex} ||= qr/^\/\Q$self->{path}\E\//;
fbcc1737
EW
3077 if (grep /$self->{path_regex}/, keys %$paths) {
3078 return 1;
3079 }
3080 my $c = '';
3081 foreach (split m#/#, $self->{path}) {
3082 $c .= "/$_";
74a81227
EW
3083 next unless ($paths->{$c} &&
3084 ($paths->{$c}->{action} =~ /^[AR]$/));
e518192f
EW
3085 if ($self->ra->check_path($self->{path}, $r) ==
3086 $SVN::Node::dir) {
fbcc1737
EW
3087 return 1;
3088 }
3089 }
3090 return 0;
3091}
3092
15710b6f
EW
3093sub find_parent_branch {
3094 my ($self, $paths, $rev) = @_;
91b03282 3095 return undef unless $self->follow_parent;
e5a0b240 3096 unless (defined $paths) {
c7eba716
EW
3097 my $err_handler = $SVN::Error::handler;
3098 $SVN::Error::handler = \&Git::SVN::Ra::skip_unknown_revs;
3c49a035
MN
3099 $self->ra->get_log([$self->{path}], $rev, $rev, 0, 1, 1,
3100 sub { $paths = $_[0] });
c7eba716 3101 $SVN::Error::handler = $err_handler;
e5a0b240
EW
3102 }
3103 return undef unless defined $paths;
15710b6f
EW
3104
3105 # look for a parent from another branch:
0b2af457 3106 my @b_path_components = split m#/#, $self->{path};
7f578c55
EW
3107 my @a_path_components;
3108 my $i;
3109 while (@b_path_components) {
3110 $i = $paths->{'/'.join('/', @b_path_components)};
74a81227 3111 last if $i && defined $i->{copyfrom_path};
7f578c55
EW
3112 unshift(@a_path_components, pop(@b_path_components));
3113 }
74a81227
EW
3114 return undef unless defined $i && defined $i->{copyfrom_path};
3115 my $branch_from = $i->{copyfrom_path};
7f578c55
EW
3116 if (@a_path_components) {
3117 print STDERR "branch_from: $branch_from => ";
3118 $branch_from .= '/'.join('/', @a_path_components);
3119 print STDERR $branch_from, "\n";
3120 }
3ebe8df7 3121 my $r = $i->{copyfrom_rev};
15710b6f
EW
3122 my $repos_root = $self->ra->{repos_root};
3123 my $url = $self->ra->{url};
0b2af457 3124 my $new_url = $url . $branch_from;
15710b6f 3125 print STDERR "Found possible branch point: ",
85886162
SA
3126 "$new_url => ", $self->full_url, ", $r\n"
3127 unless $::_q > 1;
15710b6f 3128 $branch_from =~ s#^/##;
0b2af457 3129 my $gs = $self->other_gs($new_url, $url,
8e3f9b17 3130 $branch_from, $r, $self->{ref_id});
15710b6f 3131 my ($r0, $parent) = $gs->find_rev_before($r, 1);
553589f7
DM
3132 {
3133 my ($base, $head);
3134 if (!defined $r0 || !defined $parent) {
3135 ($base, $head) = parse_revision_argument(0, $r);
3136 } else {
3137 if ($r0 < $r) {
3138 $gs->ra->get_log([$gs->{path}], $r0 + 1, $r, 1,
3139 0, 1, sub { $base = $_[1] - 1 });
3140 }
3141 }
3142 if (defined $base && $base <= $r) {
d627de6b
EW
3143 $gs->fetch($base, $r);
3144 }
553589f7 3145 ($r0, $parent) = $gs->find_rev_before($r, 1);
15710b6f 3146 }
ef70de96 3147 if (defined $r0 && defined $parent) {
85886162
SA
3148 print STDERR "Found branch parent: ($self->{ref_id}) $parent\n"
3149 unless $::_q > 1;
15710b6f
EW
3150 my $ed;
3151 if ($self->ra->can_do_switch) {
2e5e2480 3152 $self->assert_index_clean($parent);
85886162
SA
3153 print STDERR "Following parent with do_switch\n"
3154 unless $::_q > 1;
15710b6f 3155 # do_switch works with svn/trunk >= r22312, but that
2b27f6c8 3156 # is not included with SVN 1.4.3 (the latest version
15710b6f 3157 # at the moment), so we can't rely on it
83c2fcff 3158 $self->{last_rev} = $r0;
15710b6f 3159 $self->{last_commit} = $parent;
72827aa4 3160 $ed = Git::SVN::Fetcher->new($self, $gs->{path});
8a603774 3161 $gs->ra->gs_do_switch($r0, $rev, $gs,
15710b6f
EW
3162 $self->full_url, $ed)
3163 or die "SVN connection failed somewhere...\n";
9ff74e95
SW
3164 } elsif ($self->ra->trees_match($new_url, $r0,
3165 $self->full_url, $rev)) {
3166 print STDERR "Trees match:\n",
3167 " $new_url\@$r0\n",
3168 " ${\$self->full_url}\@$rev\n",
85886162
SA
3169 "Following parent with no changes\n"
3170 unless $::_q > 1;
9ff74e95
SW
3171 $self->tmp_index_do(sub {
3172 command_noisy('read-tree', $parent);
3173 });
3174 $self->{last_commit} = $parent;
15710b6f 3175 } else {
85886162
SA
3176 print STDERR "Following parent with do_update\n"
3177 unless $::_q > 1;
72827aa4 3178 $ed = Git::SVN::Fetcher->new($self);
8a603774 3179 $self->ra->gs_do_update($rev, $rev, $self, $ed)
15710b6f
EW
3180 or die "SVN connection failed somewhere...\n";
3181 }
85886162 3182 print STDERR "Successfully followed parent\n" unless $::_q > 1;
15710b6f
EW
3183 return $self->make_log_entry($rev, [$parent], $ed);
3184 }
15710b6f
EW
3185 return undef;
3186}
3187
9b981fc6 3188sub do_fetch {
706587fc 3189 my ($self, $paths, $rev) = @_;
15710b6f 3190 my $ed;
9b981fc6 3191 my ($last_rev, @parents);
b9dffd8c
EW
3192 if (my $lc = $self->last_commit) {
3193 # we can have a branch that was deleted, then re-added
3194 # under the same name but copied from another path, in
3195 # which case we'll have multiple parents (we don't
3196 # want to break the original ref, nor lose copypath info):
3197 if (my $log_entry = $self->find_parent_branch($paths, $rev)) {
3198 push @{$log_entry->{parents}}, $lc;
3199 return $log_entry;
3200 }
72827aa4 3201 $ed = Git::SVN::Fetcher->new($self);
9b981fc6 3202 $last_rev = $self->{last_rev};
b9dffd8c
EW
3203 $ed->{c} = $lc;
3204 @parents = ($lc);
9b981fc6
EW
3205 } else {
3206 $last_rev = $rev;
15710b6f
EW
3207 if (my $log_entry = $self->find_parent_branch($paths, $rev)) {
3208 return $log_entry;
3209 }
72827aa4 3210 $ed = Git::SVN::Fetcher->new($self);
9b981fc6 3211 }
8a603774 3212 unless ($self->ra->gs_do_update($last_rev, $rev, $self, $ed)) {
9b981fc6
EW
3213 die "SVN connection failed somewhere...\n";
3214 }
3215 $self->make_log_entry($rev, \@parents, $ed);
3216}
3217
6111b934
EW
3218sub mkemptydirs {
3219 my ($self, $r) = @_;
a5b80d92
EW
3220
3221 sub scan {
3222 my ($r, $empty_dirs, $line) = @_;
3223 if (defined $r && $line =~ /^r(\d+)$/) {
3224 return 0 if $1 > $r;
3225 } elsif ($line =~ /^ \+empty_dir: (.+)$/) {
3226 $empty_dirs->{$1} = 1;
3227 } elsif ($line =~ /^ \-empty_dir: (.+)$/) {
3228 my @d = grep {m[^\Q$1\E(/|$)]} (keys %$empty_dirs);
3229 delete @$empty_dirs{@d};
3230 }
3231 1; # continue
3232 };
3233
6111b934 3234 my %empty_dirs = ();
a5b80d92
EW
3235 my $gz_file = "$self->{dir}/unhandled.log.gz";
3236 if (-f $gz_file) {
3237 if (!$can_compress) {
3238 warn "Compress::Zlib could not be found; ",
3239 "empty directories in $gz_file will not be read\n";
3240 } else {
3241 my $gz = Compress::Zlib::gzopen($gz_file, "rb") or
3242 die "Unable to open $gz_file: $!\n";
3243 my $line;
3244 while ($gz->gzreadline($line) > 0) {
3245 scan($r, \%empty_dirs, $line) or last;
3246 }
3247 $gz->gzclose;
3248 }
3249 }
6111b934 3250
a5b80d92
EW
3251 if (open my $fh, '<', "$self->{dir}/unhandled.log") {
3252 binmode $fh or croak "binmode: $!";
3253 while (<$fh>) {
3254 scan($r, \%empty_dirs, $_) or last;
6111b934 3255 }
a5b80d92 3256 close $fh;
6111b934 3257 }
9be30eed
EW
3258
3259 my $strip = qr/\A\Q$self->{path}\E(?:\/|$)/;
6111b934
EW
3260 foreach my $d (sort keys %empty_dirs) {
3261 $d = uri_decode($d);
9be30eed 3262 $d =~ s/$strip//;
7c42e390 3263 next unless length($d);
6111b934 3264 next if -d $d;
7c42e390 3265 if (-e $d) {
6111b934
EW
3266 warn "$d exists but is not a directory\n";
3267 } else {
3268 print "creating empty directory: $d\n";
3269 mkpath([$d]);
3270 }
3271 }
3272}
3273
97f6987a
EW
3274sub get_untracked {
3275 my ($self, $ed) = @_;
3276 my @out;
3277 my $h = $ed->{empty};
9b981fc6
EW
3278 foreach (sort keys %$h) {
3279 my $act = $h->{$_} ? '+empty_dir' : '-empty_dir';
97f6987a 3280 push @out, " $act: " . uri_encode($_);
9b981fc6
EW
3281 warn "W: $act: $_\n";
3282 }
3283 foreach my $t (qw/dir_prop file_prop/) {
97f6987a 3284 $h = $ed->{$t} or next;
9b981fc6
EW
3285 foreach my $path (sort keys %$h) {
3286 my $ppath = $path eq '' ? '.' : $path;
3287 foreach my $prop (sort keys %{$h->{$path}}) {
1ce255dc 3288 next if $SKIP_PROP{$prop};
9b981fc6 3289 my $v = $h->{$path}->{$prop};
97f6987a
EW
3290 my $t_ppath_prop = "$t: " .
3291 uri_encode($ppath) . ' ' .
3292 uri_encode($prop);
9b981fc6 3293 if (defined $v) {
97f6987a
EW
3294 push @out, " +$t_ppath_prop " .
3295 uri_encode($v);
9b981fc6 3296 } else {
97f6987a 3297 push @out, " -$t_ppath_prop";
9b981fc6
EW
3298 }
3299 }
3300 }
3301 }
3302 foreach my $t (qw/absent_file absent_directory/) {
97f6987a 3303 $h = $ed->{$t} or next;
9b981fc6
EW
3304 foreach my $parent (sort keys %$h) {
3305 foreach my $path (sort @{$h->{$parent}}) {
97f6987a
EW
3306 push @out, " $t: " .
3307 uri_encode("$parent/$path");
9b981fc6
EW
3308 warn "W: $t: $parent/$path ",
3309 "Insufficient permissions?\n";
3310 }
3311 }
3312 }
97f6987a 3313 \@out;
9b981fc6
EW
3314}
3315
6aa17fc6
WYC
3316sub get_tz {
3317 # some systmes don't handle or mishandle %z, so be creative.
3318 my $t = shift || time;
3319 my $gm = timelocal(gmtime($t));
3320 my $sign = qw( + + - )[ $t <=> $gm ];
3321 return sprintf("%s%02d%02d", $sign, (gmtime(abs($t - $gm)))[2,1]);
3322}
3323
e82f0d73
PH
3324# parse_svn_date(DATE)
3325# --------------------
3326# Given a date (in UTC) from Subversion, return a string in the format
3327# "<TZ Offset> <local date/time>" that Git will use.
3328#
3329# By default the parsed date will be in UTC; if $Git::SVN::_localtime
3330# is true we'll convert it to the local timezone instead.
1c8443b0
EW
3331sub parse_svn_date {
3332 my $date = shift || return '+0000 1970-01-01 00:00:00';
3333 my ($Y,$m,$d,$H,$M,$S) = ($date =~ /^(\d{4})\-(\d\d)\-(\d\d)T
b94ead75 3334 (\d\d)\:(\d\d)\:(\d\d)\.\d*Z$/x) or
1c8443b0 3335 croak "Unable to parse date: $date\n";
e82f0d73
PH
3336 my $parsed_date; # Set next.
3337
3338 if ($Git::SVN::_localtime) {
3339 # Translate the Subversion datetime to an epoch time.
3340 # Begin by switching ourselves to $date's timezone, UTC.
3341 my $old_env_TZ = $ENV{TZ};
3342 $ENV{TZ} = 'UTC';
3343
3344 my $epoch_in_UTC =
3345 POSIX::strftime('%s', $S, $M, $H, $d, $m - 1, $Y - 1900);
3346
3347 # Determine our local timezone (including DST) at the
3348 # time of $epoch_in_UTC. $Git::SVN::Log::TZ stored the
3349 # value of TZ, if any, at the time we were run.
3350 if (defined $Git::SVN::Log::TZ) {
3351 $ENV{TZ} = $Git::SVN::Log::TZ;
3352 } else {
3353 delete $ENV{TZ};
3354 }
3355
6aa17fc6 3356 my $our_TZ = get_tz();
e82f0d73
PH
3357
3358 # This converts $epoch_in_UTC into our local timezone.
3359 my ($sec, $min, $hour, $mday, $mon, $year,
3360 $wday, $yday, $isdst) = localtime($epoch_in_UTC);
3361
3362 $parsed_date = sprintf('%s %04d-%02d-%02d %02d:%02d:%02d',
3363 $our_TZ, $year + 1900, $mon + 1,
3364 $mday, $hour, $min, $sec);
3365
3366 # Reset us to the timezone in effect when we entered
3367 # this routine.
3368 if (defined $old_env_TZ) {
3369 $ENV{TZ} = $old_env_TZ;
3370 } else {
3371 delete $ENV{TZ};
3372 }
3373 } else {
3374 $parsed_date = "+0000 $Y-$m-$d $H:$M:$S";
3375 }
3376
3377 return $parsed_date;
1c8443b0
EW
3378}
3379
8e3f9b17 3380sub other_gs {
0b2af457 3381 my ($self, $new_url, $url,
8e3f9b17 3382 $branch_from, $r, $old_ref_id) = @_;
0b2af457 3383 my $gs = Git::SVN->find_by_url($new_url, $url, $branch_from);
8e3f9b17
SV
3384 unless ($gs) {
3385 my $ref_id = $old_ref_id;
54fb7f9b 3386 $ref_id =~ s/\@\d+-*$//;
8e3f9b17
SV
3387 $ref_id .= "\@$r";
3388 # just grow a tail if we're not unique enough :x
3389 $ref_id .= '-' while find_ref($ref_id);
8e3f9b17
SV
3390 my ($u, $p, $repo_id) = ($new_url, '', $ref_id);
3391 if ($u =~ s#^\Q$url\E(/|$)##) {
3392 $p = $u;
3393 $u = $url;
3394 $repo_id = $self->{repo_id};
3395 }
3235b705
DK
3396 while (1) {
3397 # It is possible to tag two different subdirectories at
3398 # the same revision. If the url for an existing ref
3399 # does not match, we must either find a ref with a
3400 # matching url or create a new ref by growing a tail.
3401 $gs = Git::SVN->init($u, $p, $repo_id, $ref_id, 1);
3402 my (undef, $max_commit) = $gs->rev_map_max(1);
3403 last if (!$max_commit);
3404 my ($url) = ::cmt_metadata($max_commit);
85f022e9 3405 last if ($url eq $gs->metadata_url);
3235b705
DK
3406 $ref_id .= '-';
3407 }
3408 print STDERR "Initializing parent: $ref_id\n" unless $::_q > 1;
8e3f9b17
SV
3409 }
3410 $gs
3411}
3412
36db1edd
ML
3413sub call_authors_prog {
3414 my ($orig_author) = @_;
d3d7d47e 3415 $orig_author = command_oneline('rev-parse', '--sq-quote', $orig_author);
36db1edd
ML
3416 my $author = `$::_authors_prog $orig_author`;
3417 if ($? != 0) {
3418 die "$::_authors_prog failed with exit code $?\n"
3419 }
3420 if ($author =~ /^\s*(.+?)\s*<(.*)>\s*$/) {
3421 my ($name, $email) = ($1, $2);
3422 $email = undef if length $2 == 0;
3423 return [$name, $email];
3424 } else {
3425 die "Author: $orig_author: $::_authors_prog returned "
3426 . "invalid author format: $author\n";
3427 }
3428}
3429
1c8443b0
EW
3430sub check_author {
3431 my ($author) = @_;
3432 if (!defined $author || length $author == 0) {
3433 $author = '(no author)';
36db1edd
ML
3434 }
3435 if (!defined $::users{$author}) {
3436 if (defined $::_authors_prog) {
3437 $::users{$author} = call_authors_prog($author);
3438 } elsif (defined $::_authors) {
3439 die "Author: $author not defined in $::_authors file\n";
3440 }
1c8443b0
EW
3441 }
3442 $author;
3443}
3444
f1264bd6
SV
3445sub find_extra_svk_parents {
3446 my ($self, $ed, $tickets, $parents) = @_;
3447 # aha! svk:merge property changed...
3448 my @tickets = split "\n", $tickets;
3449 my @known_parents;
3450 for my $ticket ( @tickets ) {
3451 my ($uuid, $path, $rev) = split /:/, $ticket;
3452 if ( $uuid eq $self->ra_uuid ) {
bf60fff8 3453 my $url = $self->{url};
f1264bd6
SV
3454 my $repos_root = $url;
3455 my $branch_from = $path;
3456 $branch_from =~ s{^/}{};
3457 my $gs = $self->other_gs($repos_root."/".$branch_from,
3458 $url,
3459 $branch_from,
3460 $rev,
3461 $self->{ref_id});
3462 if ( my $commit = $gs->rev_map_get($rev, $uuid) ) {
3463 # wahey! we found it, but it might be
3464 # an old one (!)
e9e4c8b7 3465 push @known_parents, [ $rev, $commit ];
f1264bd6
SV
3466 }
3467 }
3468 }
e9e4c8b7
AV
3469 # Ordering matters; highest-numbered commit merge tickets
3470 # first, as they may account for later merge ticket additions
3471 # or changes.
3472 @known_parents = map {$_->[1]} sort {$b->[0] <=> $a->[0]} @known_parents;
f1264bd6
SV
3473 for my $parent ( @known_parents ) {
3474 my @cmd = ('rev-list', $parent, map { "^$_" } @$parents );
3475 my ($msg_fh, $ctx) = command_output_pipe(@cmd);
3476 my $new;
3477 while ( <$msg_fh> ) {
3478 $new=1;last;
3479 }
3480 command_close_pipe($msg_fh, $ctx);
3481 if ( $new ) {
3482 print STDERR
3483 "Found merge parent (svk:merge ticket): $parent\n";
3484 push @$parents, $parent;
3485 }
3486 }
3487}
3488
7d944c33
SV
3489sub lookup_svn_merge {
3490 my $uuid = shift;
3491 my $url = shift;
3492 my $merge = shift;
3493
3494 my ($source, $revs) = split ":", $merge;
3495 my $path = $source;
3496 $path =~ s{^/}{};
3497 my $gs = Git::SVN->find_by_url($url.$source, $url, $path);
3498 if ( !$gs ) {
3499 warn "Couldn't find revmap for $url$source\n";
3500 return;
3501 }
3502 my @ranges = split ",", $revs;
3503 my ($tip, $tip_commit);
3504 my @merged_commit_ranges;
3505 # find the tip
3506 for my $range ( @ranges ) {
3507 my ($bottom, $top) = split "-", $range;
3508 $top ||= $bottom;
33973a5b
SV
3509 my $bottom_commit = $gs->find_rev_after( $bottom, 1, $top );
3510 my $top_commit = $gs->find_rev_before( $top, 1, $bottom );
7d944c33
SV
3511
3512 unless ($top_commit and $bottom_commit) {
3513 warn "W:unknown path/rev in svn:mergeinfo "
3514 ."dirprop: $source:$range\n";
3515 next;
3516 }
3517
124b70a2
MH
3518 if (scalar(command('rev-parse', "$bottom_commit^@"))) {
3519 push @merged_commit_ranges,
3520 "$bottom_commit^..$top_commit";
3521 } else {
3522 push @merged_commit_ranges, "$top_commit";
3523 }
7d944c33
SV
3524
3525 if ( !defined $tip or $top > $tip ) {
3526 $tip = $top;
3527 $tip_commit = $top_commit;
3528 }
3529 }
3530 return ($tip_commit, @merged_commit_ranges);
3531}
7a955a53
SV
3532
3533sub _rev_list {
3534 my ($msg_fh, $ctx) = command_output_pipe(
3535 "rev-list", @_,
3536 );
3537 my @rv;
3538 while ( <$msg_fh> ) {
3539 chomp;
3540 push @rv, $_;
3541 }
3542 command_close_pipe($msg_fh, $ctx);
3543 @rv;
3544}
3545
3546sub check_cherry_pick {
3547 my $base = shift;
3548 my $tip = shift;
a3c75056 3549 my $parents = shift;
7a955a53
SV
3550 my @ranges = @_;
3551 my %commits = map { $_ => 1 }
eabd73a3 3552 _rev_list("--no-merges", $tip, "--not", $base, @$parents, "--");
7a955a53 3553 for my $range ( @ranges ) {
eabd73a3 3554 delete @commits{_rev_list($range, "--")};
7a955a53 3555 }
1cef6500
AM
3556 for my $commit (keys %commits) {
3557 if (has_no_changes($commit)) {
3558 delete $commits{$commit};
3559 }
3560 }
7a955a53
SV
3561 return (keys %commits);
3562}
3563
1cef6500
AM
3564sub has_no_changes {
3565 my $commit = shift;
3566
3567 my @revs = split / /, command_oneline(
3568 qw(rev-list --parents -1 -m), $commit);
3569
3570 # Commits with no parents, e.g. the start of a partial branch,
3571 # have changes by definition.
3572 return 1 if (@revs < 2);
3573
3574 # Commits with multiple parents, e.g a merge, have no changes
3575 # by definition.
3576 return 0 if (@revs > 2);
3577
3578 return (command_oneline("rev-parse", "$commit^{tree}") eq
3579 command_oneline("rev-parse", "$commit~1^{tree}"));
3580}
3581
8bff7c53
AM
3582# The GIT_DIR environment variable is not always set until after the command
3583# line arguments are processed, so we can't memoize in a BEGIN block.
3584{
3585 my $memoized = 0;
3586
3587 sub memoize_svn_mergeinfo_functions {
3588 return if $memoized;
3589 $memoized = 1;
3590
3591 my $cache_path = "$ENV{GIT_DIR}/svn/.caches/";
3592 mkpath([$cache_path]) unless -d $cache_path;
3593
3594 tie my %lookup_svn_merge_cache => 'Memoize::Storable',
3595 "$cache_path/lookup_svn_merge.db", 'nstore';
3596 memoize 'lookup_svn_merge',
3597 SCALAR_CACHE => 'FAULT',
3598 LIST_CACHE => ['HASH' => \%lookup_svn_merge_cache],
3599 ;
3600
3601 tie my %check_cherry_pick_cache => 'Memoize::Storable',
3602 "$cache_path/check_cherry_pick.db", 'nstore';
3603 memoize 'check_cherry_pick',
3604 SCALAR_CACHE => 'FAULT',
3605 LIST_CACHE => ['HASH' => \%check_cherry_pick_cache],
3606 ;
3607
3608 tie my %has_no_changes_cache => 'Memoize::Storable',
3609 "$cache_path/has_no_changes.db", 'nstore';
3610 memoize 'has_no_changes',
3611 SCALAR_CACHE => ['HASH' => \%has_no_changes_cache],
3612 LIST_CACHE => 'FAULT',
3613 ;
3614 }
8ac3a667
SV
3615
3616 sub unmemoize_svn_mergeinfo_functions {
3617 return if not $memoized;
3618 $memoized = 0;
3619
3620 Memoize::unmemoize 'lookup_svn_merge';
3621 Memoize::unmemoize 'check_cherry_pick';
3622 Memoize::unmemoize 'has_no_changes';
3623 }
f5549afd
JK
3624
3625 Memoize::memoize 'Git::SVN::repos_root';
8ac3a667
SV
3626}
3627
3628END {
3629 # Force cache writeout explicitly instead of waiting for
3630 # global destruction to avoid segfault in Storable:
3631 # http://rt.cpan.org/Public/Bug/Display.html?id=36087
3632 unmemoize_svn_mergeinfo_functions();
7d944c33
SV
3633}
3634
ea020cbd
SV
3635sub parents_exclude {
3636 my $parents = shift;
3637 my @commits = @_;
3638 return unless @commits;
3639
3640 my @excluded;
3641 my $excluded;
3642 do {
3643 my @cmd = ('rev-list', "-1", @commits, "--not", @$parents );
3644 $excluded = command_oneline(@cmd);
3645 if ( $excluded ) {
3646 my @new;
3647 my $found;
3648 for my $commit ( @commits ) {
3649 if ( $commit eq $excluded ) {
3650 push @excluded, $commit;
3651 $found++;
3652 last;
3653 }
3654 else {
3655 push @new, $commit;
3656 }
3657 }
3658 die "saw commit '$excluded' in rev-list output, "
3659 ."but we didn't ask for that commit (wanted: @commits --not @$parents)"
3660 unless $found;
3661 @commits = @new;
3662 }
3663 }
3664 while ($excluded and @commits);
3665
3666 return @excluded;
3667}
3668
3669
dff589ef
SV
3670# note: this function should only be called if the various dirprops
3671# have actually changed
3672sub find_extra_svn_parents {
3673 my ($self, $ed, $mergeinfo, $parents) = @_;
3674 # aha! svk:merge property changed...
3675
8bff7c53
AM
3676 memoize_svn_mergeinfo_functions();
3677
dff589ef
SV
3678 # We first search for merged tips which are not in our
3679 # history. Then, we figure out which git revisions are in
3680 # that tip, but not this revision. If all of those revisions
3681 # are now marked as merge, we can add the tip as a parent.
3682 my @merges = split "\n", $mergeinfo;
3683 my @merge_tips;
bf60fff8 3684 my $url = $self->{url};
7d944c33 3685 my $uuid = $self->ra_uuid;
ea020cbd 3686 my %ranges;
dff589ef 3687 for my $merge ( @merges ) {
7d944c33
SV
3688 my ($tip_commit, @ranges) =
3689 lookup_svn_merge( $uuid, $url, $merge );
dff589ef
SV
3690 unless (!$tip_commit or
3691 grep { $_ eq $tip_commit } @$parents ) {
3692 push @merge_tips, $tip_commit;
ea020cbd 3693 $ranges{$tip_commit} = \@ranges;
dff589ef
SV
3694 } else {
3695 push @merge_tips, undef;
3696 }
3697 }
ea020cbd
SV
3698
3699 my %excluded = map { $_ => 1 }
3700 parents_exclude($parents, grep { defined } @merge_tips);
3701
3702 # check merge tips for new parents
3703 my @new_parents;
dff589ef
SV
3704 for my $merge_tip ( @merge_tips ) {
3705 my $spec = shift @merges;
ea020cbd
SV
3706 next unless $merge_tip and $excluded{$merge_tip};
3707
3708 my $ranges = $ranges{$merge_tip};
3709
7a955a53 3710 # check out 'new' tips
41c01693
AM
3711 my $merge_base;
3712 eval {
3713 $merge_base = command_oneline(
3714 "merge-base",
3715 @$parents, $merge_tip,
3716 );
3717 };
3718 if ($@) {
3719 die "An error occurred during merge-base"
3720 unless $@->isa("Git::Error::Command");
3721
3722 warn "W: Cannot find common ancestor between ".
3723 "@$parents and $merge_tip. Ignoring merge info.\n";
3724 next;
3725 }
7a955a53
SV
3726
3727 # double check that there are no missing non-merge commits
3728 my (@incomplete) = check_cherry_pick(
3729 $merge_base, $merge_tip,
a3c75056 3730 $parents,
7a955a53
SV
3731 @$ranges,
3732 );
3733
3734 if ( @incomplete ) {
3735 warn "W:svn cherry-pick ignored ($spec) - missing "
3736 .@incomplete." commit(s) (eg $incomplete[0])\n";
3737 } else {
3738 warn
3739 "Found merge parent (svn:mergeinfo prop): ",
3740 $merge_tip, "\n";
3741 push @new_parents, $merge_tip;
3742 }
3743 }
3744
3745 # cater for merges which merge commits from multiple branches
3746 if ( @new_parents > 1 ) {
3747 for ( my $i = 0; $i <= $#new_parents; $i++ ) {
3748 for ( my $j = 0; $j <= $#new_parents; $j++ ) {
3749 next if $i == $j;
3750 next unless $new_parents[$i];
3751 next unless $new_parents[$j];
3752 my $revs = command_oneline(
0fe19753
EW
3753 "rev-list", "-1",
3754 "$new_parents[$i]..$new_parents[$j]",
7a955a53
SV
3755 );
3756 if ( !$revs ) {
6a2009e7 3757 undef($new_parents[$j]);
7a955a53 3758 }
dff589ef
SV
3759 }
3760 }
3761 }
7a955a53 3762 push @$parents, grep { defined } @new_parents;
dff589ef
SV
3763}
3764
9b981fc6 3765sub make_log_entry {
97f6987a
EW
3766 my ($self, $rev, $parents, $ed) = @_;
3767 my $untracked = $self->get_untracked($ed);
3768
f1264bd6
SV
3769 my @parents = @$parents;
3770 my $ps = $ed->{path_strip} || "";
3771 for my $path ( grep { m/$ps/ } %{$ed->{dir_prop}} ) {
3772 my $props = $ed->{dir_prop}{$path};
3773 if ( $props->{"svk:merge"} ) {
3774 $self->find_extra_svk_parents
3775 ($ed, $props->{"svk:merge"}, \@parents);
3776 }
dff589ef
SV
3777 if ( $props->{"svn:mergeinfo"} ) {
3778 $self->find_extra_svn_parents
3779 ($ed,
3780 $props->{"svn:mergeinfo"},
3781 \@parents);
3782 }
f1264bd6
SV
3783 }
3784
9b981fc6 3785 open my $un, '>>', "$self->{dir}/unhandled.log" or croak $!;
97f6987a
EW
3786 print $un "r$rev\n" or croak $!;
3787 print $un $_, "\n" foreach @$untracked;
f1264bd6 3788 my %log_entry = ( parents => \@parents, revision => $rev,
97f6987a 3789 log => '');
fbcc1737 3790
8a49ee97 3791 my $headrev;
fbcc1737 3792 my $logged = delete $self->{logged_rev_props};
8a49ee97 3793 if (!$logged || $self->{-want_revprops}) {
fbcc1737
EW
3794 my $rp = $self->ra->rev_proplist($rev);
3795 foreach (sort keys %$rp) {
3796 my $v = $rp->{$_};
3797 if (/^svn:(author|date|log)$/) {
3798 $log_entry{$1} = $v;
8a49ee97
EW
3799 } elsif ($_ eq 'svm:headrev') {
3800 $headrev = $v;
fbcc1737
EW
3801 } else {
3802 print $un " rev_prop: ", uri_encode($_), ' ',
3803 uri_encode($v), "\n";
3804 }
9b981fc6 3805 }
fbcc1737
EW
3806 } else {
3807 map { $log_entry{$_} = $logged->{$_} } keys %$logged;
9b981fc6
EW
3808 }
3809 close $un or croak $!;
97f6987a 3810
9b981fc6 3811 $log_entry{date} = parse_svn_date($log_entry{date});
9b981fc6 3812 $log_entry{log} .= "\n";
db03cd24
EW
3813 my $author = $log_entry{author} = check_author($log_entry{author});
3814 my ($name, $email) = defined $::users{$author} ? @{$::users{$author}}
70ae04e4
AW
3815 : ($author, undef);
3816
3817 my ($commit_name, $commit_email) = ($name, $email);
3818 if ($_use_log_author) {
5ff6aae8
AW
3819 my $name_field;
3820 if ($log_entry{log} =~ /From:\s+(.*\S)\s*\n/i) {
3821 $name_field = $1;
3822 } elsif ($log_entry{log} =~ /Signed-off-by:\s+(.*\S)\s*\n/i) {
3823 $name_field = $1;
3824 }
3825 if (!defined $name_field) {
abfa533d
SB
3826 if (!defined $email) {
3827 $email = $name;
3828 }
5ff6aae8 3829 } elsif ($name_field =~ /(.*?)\s+<(.*)>/) {
70ae04e4 3830 ($name, $email) = ($1, $2);
5ff6aae8
AW
3831 } elsif ($name_field =~ /(.*)@/) {
3832 ($name, $email) = ($1, $name_field);
3833 } else {
abfa533d 3834 ($name, $email) = ($name_field, $name_field);
70ae04e4
AW
3835 }
3836 }
91b03282 3837 if (defined $headrev && $self->use_svm_props) {
aea736cc
EW
3838 if ($self->rewrite_root) {
3839 die "Can't have both 'useSvmProps' and 'rewriteRoot' ",
3840 "options set!\n";
3841 }
3e18ce1a
JS
3842 if ($self->rewrite_uuid) {
3843 die "Can't have both 'useSvmProps' and 'rewriteUUID' ",
3844 "options set!\n";
3845 }
b3e95936 3846 my ($uuid, $r) = $headrev =~ m{^([a-f\d\-]{30,}):(\d+)$}i;
befc9adc
EW
3847 # we don't want "SVM: initializing mirror for junk" ...
3848 return undef if $r == 0;
3849 my $svm = $self->svm;
3850 if ($uuid ne $svm->{uuid}) {
8a49ee97 3851 die "UUID mismatch on SVM path:\n",
befc9adc 3852 "expected: $svm->{uuid}\n",
8a49ee97
EW
3853 " got: $uuid\n";
3854 }
befc9adc
EW
3855 my $full_url = $self->full_url;
3856 $full_url =~ s#^\Q$svm->{replace}\E(/|$)#$svm->{source}$1# or
3857 die "Failed to replace '$svm->{replace}' with ",
3858 "'$svm->{source}' in $full_url\n";
18ea92bd
SV
3859 # throw away username for storing in records
3860 remove_username($full_url);
8a49ee97
EW
3861 $log_entry{metadata} = "$full_url\@$r $uuid";
3862 $log_entry{svm_revision} = $r;
70ae04e4
AW
3863 $email ||= "$author\@$uuid";
3864 $commit_email ||= "$author\@$uuid";
62e349d2
EW
3865 } elsif ($self->use_svnsync_props) {
3866 my $full_url = $self->svnsync->{url};
3867 $full_url .= "/$self->{path}" if length $self->{path};
ce118739 3868 remove_username($full_url);
62e349d2
EW
3869 my $uuid = $self->svnsync->{uuid};
3870 $log_entry{metadata} = "$full_url\@$rev $uuid";
70ae04e4
AW
3871 $email ||= "$author\@$uuid";
3872 $commit_email ||= "$author\@$uuid";
8a49ee97 3873 } else {
ce118739
AR
3874 my $url = $self->metadata_url;
3875 remove_username($url);
3e18ce1a
JS
3876 my $uuid = $self->rewrite_uuid || $self->ra->get_uuid;
3877 $log_entry{metadata} = "$url\@$rev " . $uuid;
3878 $email ||= "$author\@" . $uuid;
3879 $commit_email ||= "$author\@" . $uuid;
8a49ee97 3880 }
db03cd24
EW
3881 $log_entry{name} = $name;
3882 $log_entry{email} = $email;
70ae04e4
AW
3883 $log_entry{commit_name} = $commit_name;
3884 $log_entry{commit_email} = $commit_email;
9b981fc6
EW
3885 \%log_entry;
3886}
3887
3888sub fetch {
3ebe8df7 3889 my ($self, $min_rev, $max_rev, @parents) = @_;
9b981fc6 3890 my ($last_rev, $last_commit) = $self->last_rev_commit;
3ebe8df7 3891 my ($base, $head) = $self->get_fetch_range($min_rev, $max_rev);
e518192f 3892 $self->ra->gs_fetch_loop_common($base, $head, [$self]);
9b981fc6
EW
3893}
3894
3895sub set_tree_cb {
3896 my ($self, $log_entry, $tree, $rev, $date, $author) = @_;
490f49ea
EW
3897 $self->{inject_parents} = { $rev => $tree };
3898 $self->fetch(undef, undef);
9b981fc6
EW
3899}
3900
3901sub set_tree {
3902 my ($self, $tree) = (shift, shift);
1ce255dc 3903 my $log_entry = ::get_commit_entry($tree);
9b981fc6 3904 unless ($self->{last_rev}) {
0a1a1c86 3905 ::fatal("Must have an existing revision to commit");
9b981fc6 3906 }
61395354
EW
3907 my %ed_opts = ( r => $self->{last_rev},
3908 log => $log_entry->{log},
3909 ra => $self->ra,
3910 tree_a => $self->{last_commit},
3911 tree_b => $tree,
3912 editor_cb => sub {
3913 $self->set_tree_cb($log_entry, $tree, @_) },
3914 svn_path => $self->{path} );
72827aa4 3915 if (!Git::SVN::Editor->new(\%ed_opts)->apply_diff) {
9b981fc6
EW
3916 print "No changes\nr$self->{last_rev} = $tree\n";
3917 }
9b981fc6
EW
3918}
3919
060610c5
EW
3920sub rebuild_from_rev_db {
3921 my ($self, $path) = @_;
3922 my $r = -1;
3923 open my $fh, '<', $path or croak "open: $!";
4f7ec797 3924 binmode $fh or croak "binmode: $!";
060610c5
EW
3925 while (<$fh>) {
3926 length($_) == 41 or croak "inconsistent size in ($_) != 41";
3927 chomp($_);
3928 ++$r;
3929 next if $_ eq ('0' x 40);
3930 $self->rev_map_set($r, $_);
3931 print "r$r = $_\n";
3932 }
3933 close $fh or croak "close: $!";
3934 unlink $path or croak "unlink: $!";
3935}
3936
f0ecca10
EW
3937sub rebuild {
3938 my ($self) = @_;
060610c5 3939 my $map_path = $self->map_path;
2beec897 3940 my $partial = (-e $map_path && ! -z $map_path);
d6d3346b 3941 return unless ::verify_ref($self->refname.'^0');
2beec897 3942 if (!$partial && ($self->use_svm_props || $self->no_metadata)) {
060610c5
EW
3943 my $rev_db = $self->rev_db_path;
3944 $self->rebuild_from_rev_db($rev_db);
3945 if ($self->use_svm_props) {
3946 my $svm_rev_db = $self->rev_db_path($self->svm_uuid);
3947 $self->rebuild_from_rev_db($svm_rev_db);
3948 }
3949 $self->unlink_rev_db_symlink;
26a62d57
EW
3950 return;
3951 }
2beec897
DM
3952 print "Rebuilding $map_path ...\n" if (!$partial);
3953 my ($base_rev, $head) = ($partial ? $self->rev_map_max_norebuild(1) :
3954 (undef, undef));
060610c5 3955 my ($log, $ctx) =
b380e3a7 3956 command_output_pipe(qw/rev-list --pretty=raw --reverse/,
2beec897
DM
3957 ($head ? "$head.." : "") . $self->refname,
3958 '--');
74b1e123
JK
3959 my $metadata_url = $self->metadata_url;
3960 remove_username($metadata_url);
3e18ce1a 3961 my $svn_uuid = $self->rewrite_uuid || $self->ra_uuid;
3dfab993
SV
3962 my $c;
3963 while (<$log>) {
3964 if ( m{^commit ($::sha1)$} ) {
3965 $c = $1;
3966 next;
3967 }
3968 next unless s{^\s*(git-svn-id:)}{$1};
3969 my ($url, $rev, $uuid) = ::extract_metadata($_);
18ea92bd 3970 remove_username($url);
f0ecca10
EW
3971
3972 # ignore merges (from set-tree)
3973 next if (!defined $rev || !$uuid);
3974
3975 # if we merged or otherwise started elsewhere, this is
3976 # how we break out of it
060610c5 3977 if (($uuid ne $svn_uuid) ||
74b1e123 3978 ($metadata_url && $url && ($url ne $metadata_url))) {
f0ecca10
EW
3979 next;
3980 }
2beec897
DM
3981 if ($partial && $head) {
3982 print "Partial-rebuilding $map_path ...\n";
3983 print "Currently at $base_rev = $head\n";
3984 $head = undef;
3985 }
f0ecca10 3986
060610c5 3987 $self->rev_map_set($rev, $c);
f0ecca10
EW
3988 print "r$rev = $c\n";
3989 }
3dfab993 3990 command_close_pipe($log, $ctx);
2beec897 3991 print "Done rebuilding $map_path\n" if (!$partial || !$head);
060610c5
EW
3992 my $rev_db_path = $self->rev_db_path;
3993 if (-f $self->rev_db_path) {
3994 unlink $self->rev_db_path or croak "unlink: $!";
3995 }
3996 $self->unlink_rev_db_symlink;
f0ecca10
EW
3997}
3998
060610c5 3999# rev_map:
9b981fc6
EW
4000# Tie::File seems to be prone to offset errors if revisions get sparse,
4001# it's not that fast, either. Tie::File is also not in Perl 5.6. So
4002# one of my favorite modules is out :< Next up would be one of the DBM
060610c5
EW
4003# modules, but I'm not sure which is most portable...
4004#
4005# This is the replacement for the rev_db format, which was too big
4006# and inefficient for large repositories with a lot of sparse history
4007# (mainly tags)
4008#
4009# The format is this:
4010# - 24 bytes for every record,
4011# * 4 bytes for the integer representing an SVN revision number
4012# * 20 bytes representing the sha1 of a git commit
4013# - No empty padding records like the old format
66ab84b9 4014# (except the last record, which can be overwritten)
060610c5
EW
4015# - new records are written append-only since SVN revision numbers
4016# increase monotonically
4017# - lookups on SVN revision number are done via a binary search
66ab84b9
EW
4018# - Piping the file to xxd -c24 is a good way of dumping it for
4019# viewing or editing (piped back through xxd -r), should the need
4020# ever arise.
4021# - The last record can be padding revision with an all-zero sha1
4022# This is used to optimize fetch performance when using multiple
4023# "fetch" directives in .git/config
060610c5 4024#
97ae0911 4025# These files are disposable unless noMetadata or useSvmProps is set
9b981fc6 4026
060610c5 4027sub _rev_map_set {
26a62d57 4028 my ($fh, $rev, $commit) = @_;
060610c5 4029
4f7ec797 4030 binmode $fh or croak "binmode: $!";
060610c5
EW
4031 my $size = (stat($fh))[7];
4032 ($size % 24) == 0 or croak "inconsistent size: $size";
4033
66ab84b9 4034 my $wr_offset = 0;
060610c5
EW
4035 if ($size > 0) {
4036 sysseek($fh, -24, SEEK_END) or croak "seek: $!";
4037 my $read = sysread($fh, my $buf, 24) or croak "read: $!";
4038 $read == 24 or croak "read only $read bytes (!= 24)";
4039 my ($last_rev, $last_commit) = unpack(rev_map_fmt, $buf);
66ab84b9
EW
4040 if ($last_commit eq ('0' x40)) {
4041 if ($size >= 48) {
4042 sysseek($fh, -48, SEEK_END) or croak "seek: $!";
4043 $read = sysread($fh, $buf, 24) or
4044 croak "read: $!";
4045 $read == 24 or
4046 croak "read only $read bytes (!= 24)";
4047 ($last_rev, $last_commit) =
4048 unpack(rev_map_fmt, $buf);
4049 if ($last_commit eq ('0' x40)) {
4050 croak "inconsistent .rev_map\n";
4051 }
4052 }
4053 if ($last_rev >= $rev) {
4054 croak "last_rev is higher!: $last_rev >= $rev";
4055 }
4056 $wr_offset = -24;
26a62d57
EW
4057 }
4058 }
66ab84b9 4059 sysseek($fh, $wr_offset, SEEK_END) or croak "seek: $!";
060610c5
EW
4060 syswrite($fh, pack(rev_map_fmt, $rev, $commit), 24) == 24 or
4061 croak "write: $!";
26a62d57
EW
4062}
4063
195643f2
BJ
4064sub _rev_map_reset {
4065 my ($fh, $rev, $commit) = @_;
4066 my $c = _rev_map_get($fh, $rev);
4067 $c eq $commit or die "_rev_map_reset(@_) commit $c does not match!\n";
4068 my $offset = sysseek($fh, 0, SEEK_CUR) or croak "seek: $!";
4069 truncate $fh, $offset or croak "truncate: $!";
4070}
4071
26a62d57
EW
4072sub mkfile {
4073 my ($path) = @_;
4074 unless (-e $path) {
4075 my ($dir, $base) = ($path =~ m#^(.*?)/?([^/]+)$#);
4076 mkpath([$dir]) unless -d $dir;
4077 open my $fh, '>>', $path or die "Couldn't create $path: $!\n";
4078 close $fh or die "Couldn't close (create) $path: $!\n";
4079 }
4080}
4081
060610c5 4082sub rev_map_set {
26a62d57 4083 my ($self, $rev, $commit, $update_ref, $uuid) = @_;
70ee0b77 4084 defined $commit or die "missing arg3\n";
26a62d57 4085 length $commit == 40 or die "arg3 must be a full SHA1 hexsum\n";
060610c5 4086 my $db = $self->map_path($uuid);
26a62d57 4087 my $db_lock = "$db.lock";
037a98cd 4088 my $sigmask;
195643f2 4089 $update_ref ||= 0;
373274f9 4090 if ($update_ref) {
037a98cd
RK
4091 $sigmask = POSIX::SigSet->new();
4092 my $signew = POSIX::SigSet->new(SIGINT, SIGHUP, SIGTERM,
8c3a534c 4093 SIGALRM, SIGUSR1, SIGUSR2);
037a98cd
RK
4094 sigprocmask(SIG_BLOCK, $signew, $sigmask) or
4095 croak "Can't block signals: $!";
373274f9 4096 }
26a62d57
EW
4097 mkfile($db);
4098
373274f9 4099 $LOCKFILES{$db_lock} = 1;
97ae0911 4100 my $sync;
97ae0911
EW
4101 # both of these options make our .rev_db file very, very important
4102 # and we can't afford to lose it because rebuild() won't work
4103 if ($self->use_svm_props || $self->no_metadata) {
4104 $sync = 1;
060610c5 4105 copy($db, $db_lock) or die "rev_map_set(@_): ",
26a62d57 4106 "Failed to copy: ",
373274f9
EW
4107 "$db => $db_lock ($!)\n";
4108 } else {
060610c5 4109 rename $db, $db_lock or die "rev_map_set(@_): ",
26a62d57 4110 "Failed to rename: ",
373274f9
EW
4111 "$db => $db_lock ($!)\n";
4112 }
060610c5 4113
66ab84b9 4114 sysopen(my $fh, $db_lock, O_RDWR | O_CREAT)
060610c5 4115 or croak "Couldn't open $db_lock: $!\n";
195643f2
BJ
4116 $update_ref eq 'reset' ? _rev_map_reset($fh, $rev, $commit) :
4117 _rev_map_set($fh, $rev, $commit);
97ae0911
EW
4118 if ($sync) {
4119 $fh->flush or die "Couldn't flush $db_lock: $!\n";
4120 $fh->sync or die "Couldn't sync $db_lock: $!\n";
4121 }
9b981fc6 4122 close $fh or croak $!;
373274f9 4123 if ($update_ref) {
1e889ef3 4124 $_head = $self;
195643f2
BJ
4125 my $note = "";
4126 $note = " ($update_ref)" if ($update_ref !~ /^\d*$/);
4127 command_noisy('update-ref', '-m', "r$rev$note",
373274f9
EW
4128 $self->refname, $commit);
4129 }
060610c5 4130 rename $db_lock, $db or die "rev_map_set(@_): ", "Failed to rename: ",
373274f9
EW
4131 "$db_lock => $db ($!)\n";
4132 delete $LOCKFILES{$db_lock};
4133 if ($update_ref) {
037a98cd
RK
4134 sigprocmask(SIG_SETMASK, $sigmask) or
4135 croak "Can't restore signal mask: $!";
373274f9 4136 }
9b981fc6
EW
4137}
4138
66ab84b9
EW
4139# If want_commit, this will return an array of (rev, commit) where
4140# commit _must_ be a valid commit in the archive.
4141# Otherwise, it'll return the max revision (whether or not the
4142# commit is valid or just a 0x40 placeholder).
060610c5 4143sub rev_map_max {
66ab84b9 4144 my ($self, $want_commit) = @_;
d6d3346b 4145 $self->rebuild;
2beec897
DM
4146 my ($r, $c) = $self->rev_map_max_norebuild($want_commit);
4147 $want_commit ? ($r, $c) : $r;
4148}
4149
4150sub rev_map_max_norebuild {
4151 my ($self, $want_commit) = @_;
060610c5 4152 my $map_path = $self->map_path;
66ab84b9 4153 stat $map_path or return $want_commit ? (0, undef) : 0;
060610c5 4154 sysopen(my $fh, $map_path, O_RDONLY) or croak "open: $!";
4f7ec797 4155 binmode $fh or croak "binmode: $!";
060610c5
EW
4156 my $size = (stat($fh))[7];
4157 ($size % 24) == 0 or croak "inconsistent size: $size";
4158
4159 if ($size == 0) {
4160 close $fh or croak "close: $!";
66ab84b9 4161 return $want_commit ? (0, undef) : 0;
060610c5
EW
4162 }
4163
66ab84b9 4164 sysseek($fh, -24, SEEK_END) or croak "seek: $!";
060610c5 4165 sysread($fh, my $buf, 24) == 24 or croak "read: $!";
060610c5 4166 my ($r, $c) = unpack(rev_map_fmt, $buf);
66ab84b9
EW
4167 if ($want_commit && $c eq ('0' x40)) {
4168 if ($size < 48) {
4169 return $want_commit ? (0, undef) : 0;
4170 }
4171 sysseek($fh, -48, SEEK_END) or croak "seek: $!";
4172 sysread($fh, $buf, 24) == 24 or croak "read: $!";
4173 ($r, $c) = unpack(rev_map_fmt, $buf);
4174 if ($c eq ('0'x40)) {
4175 croak "Penultimate record is all-zeroes in $map_path";
4176 }
4177 }
4178 close $fh or croak "close: $!";
4179 $want_commit ? ($r, $c) : $r;
9c93fee5
EW
4180}
4181
060610c5 4182sub rev_map_get {
26a62d57 4183 my ($self, $rev, $uuid) = @_;
060610c5
EW
4184 my $map_path = $self->map_path($uuid);
4185 return undef unless -e $map_path;
4186
4187 sysopen(my $fh, $map_path, O_RDONLY) or croak "open: $!";
195643f2
BJ
4188 my $c = _rev_map_get($fh, $rev);
4189 close($fh) or croak "close: $!";
4190 $c
4191}
4192
4193sub _rev_map_get {
4194 my ($fh, $rev) = @_;
4195
4f7ec797 4196 binmode $fh or croak "binmode: $!";
060610c5
EW
4197 my $size = (stat($fh))[7];
4198 ($size % 24) == 0 or croak "inconsistent size: $size";
4199
4200 if ($size == 0) {
060610c5
EW
4201 return undef;
4202 }
4203
4204 my ($l, $u) = (0, $size - 24);
4205 my ($r, $c, $buf);
4206
4207 while ($l <= $u) {
4208 my $i = int(($l/24 + $u/24) / 2) * 24;
4209 sysseek($fh, $i, SEEK_SET) or croak "seek: $!";
4210 sysread($fh, my $buf, 24) == 24 or croak "read: $!";
c83f4e68 4211 my ($r, $c) = unpack(rev_map_fmt, $buf);
060610c5
EW
4212
4213 if ($r < $rev) {
4214 $l = $i + 24;
4215 } elsif ($r > $rev) {
4216 $u = $i - 24;
4217 } else { # $r == $rev
66ab84b9 4218 return $c eq ('0' x 40) ? undef : $c;
060610c5 4219 }
9b981fc6 4220 }
060610c5 4221 undef;
9b981fc6
EW
4222}
4223
111947ef
DK
4224# Finds the first svn revision that exists on (if $eq_ok is true) or
4225# before $rev for the current branch. It will not search any lower
4226# than $min_rev. Returns the git commit hash and svn revision number
4227# if found, else (undef, undef).
15710b6f 4228sub find_rev_before {
111947ef 4229 my ($self, $rev, $eq_ok, $min_rev) = @_;
15710b6f 4230 --$rev unless $eq_ok;
111947ef 4231 $min_rev ||= 1;
ca5e880e
BJ
4232 my $max_rev = $self->rev_map_max;
4233 $rev = $max_rev if ($rev > $max_rev);
111947ef 4234 while ($rev >= $min_rev) {
060610c5 4235 if (my $c = $self->rev_map_get($rev)) {
15710b6f
EW
4236 return ($rev, $c);
4237 }
4238 --$rev;
4239 }
4240 return (undef, undef);
4241}
4242
111947ef
DK
4243# Finds the first svn revision that exists on (if $eq_ok is true) or
4244# after $rev for the current branch. It will not search any higher
4245# than $max_rev. Returns the git commit hash and svn revision number
4246# if found, else (undef, undef).
4247sub find_rev_after {
4248 my ($self, $rev, $eq_ok, $max_rev) = @_;
4249 ++$rev unless $eq_ok;
060610c5 4250 $max_rev ||= $self->rev_map_max;
111947ef 4251 while ($rev <= $max_rev) {
060610c5 4252 if (my $c = $self->rev_map_get($rev)) {
111947ef
DK
4253 return ($rev, $c);
4254 }
4255 ++$rev;
4256 }
4257 return (undef, undef);
4258}
4259
9b981fc6 4260sub _new {
706587fc
EW
4261 my ($class, $repo_id, $ref_id, $path) = @_;
4262 unless (defined $repo_id && length $repo_id) {
4263 $repo_id = $Git::SVN::default_repo_id;
4264 }
4265 unless (defined $ref_id && length $ref_id) {
63de84ad 4266 $_prefix = '' unless defined($_prefix);
6f5748e1
AB
4267 $_[2] = $ref_id =
4268 "refs/remotes/$_prefix$Git::SVN::default_ref_id";
706587fc 4269 }
7829f20f 4270 $_[1] = $repo_id;
706587fc 4271 my $dir = "$ENV{GIT_DIR}/svn/$ref_id";
6f5748e1
AB
4272
4273 # Older repos imported by us used $GIT_DIR/svn/foo instead of
4274 # $GIT_DIR/svn/refs/remotes/foo when tracking refs/remotes/foo
4275 if ($ref_id =~ m{^refs/remotes/(.*)}) {
4276 my $old_dir = "$ENV{GIT_DIR}/svn/$1";
4277 if (-d $old_dir && ! -d $dir) {
4278 $dir = $old_dir;
4279 }
4280 }
4281
706587fc 4282 $_[3] = $path = '' unless (defined $path);
6f5748e1 4283 mkpath([$dir]);
26a62d57
EW
4284 bless {
4285 ref_id => $ref_id, dir => $dir, index => "$dir/index",
8a49ee97 4286 path => $path, config => "$ENV{GIT_DIR}/svn/config",
060610c5 4287 map_root => "$dir/.rev_map", repo_id => $repo_id }, $class;
26a62d57
EW
4288}
4289
060610c5
EW
4290# for read-only access of old .rev_db formats
4291sub unlink_rev_db_symlink {
4292 my ($self) = @_;
4293 my $link = $self->rev_db_path;
4294 $link =~ s/\.[\w-]+$// or croak "missing UUID at the end of $link";
4295 if (-l $link) {
4296 unlink $link or croak "unlink: $link failed!";
4297 }
4298}
4299
4300sub rev_db_path {
4301 my ($self, $uuid) = @_;
4302 my $db_path = $self->map_path($uuid);
4303 $db_path =~ s{/\.rev_map\.}{/\.rev_db\.}
4304 or croak "map_path: $db_path does not contain '/.rev_map.' !";
4305 $db_path;
4306}
4307
4308# the new replacement for .rev_db
4309sub map_path {
26a62d57
EW
4310 my ($self, $uuid) = @_;
4311 $uuid ||= $self->ra_uuid;
060610c5 4312 "$self->{map_root}.$uuid";
9b981fc6
EW
4313}
4314
1c8443b0
EW
4315sub uri_encode {
4316 my ($f) = @_;
4317 $f =~ s#([^a-zA-Z0-9\*!\:_\./\-])#uc sprintf("%%%02x",ord($1))#eg;
4318 $f
4319}
9b981fc6 4320
6111b934
EW
4321sub uri_decode {
4322 my ($f) = @_;
4323 $f =~ s#%([0-9a-fA-F]{2})#chr(hex($1))#eg;
4324 $f
4325}
4326
18ea92bd
SV
4327sub remove_username {
4328 $_[0] =~ s{^([^:]*://)[^@]+@}{$1};
4329}
4330
72827aa4 4331package Git::SVN::Editor;
24e22aa8 4332use vars qw/@ISA $_rmdir $_cp_similarity $_find_copies_harder $_rename_limit/;
a5e0cedc
EW
4333use strict;
4334use warnings;
4335use Carp qw/croak/;
4336use IO::File;
4337
4338sub new {
61395354
EW
4339 my ($class, $opts) = @_;
4340 foreach (qw/svn_path r ra tree_a tree_b log editor_cb/) {
4341 die "$_ required!\n" unless (defined $opts->{$_});
4342 }
4343
4344 my $pool = SVN::Pool->new;
4345 my $mods = generate_diff($opts->{tree_a}, $opts->{tree_b});
4346 my $types = check_diff_paths($opts->{ra}, $opts->{svn_path},
4347 $opts->{r}, $mods);
4348
4349 # $opts->{ra} functions should not be used after this:
4350 my @ce = $opts->{ra}->get_commit_editor($opts->{log},
4351 $opts->{editor_cb}, $pool);
4352 my $self = SVN::Delta::Editor->new(@ce, $pool);
a5e0cedc 4353 bless $self, $class;
61395354
EW
4354 foreach (qw/svn_path r tree_a tree_b/) {
4355 $self->{$_} = $opts->{$_};
a5e0cedc 4356 }
61395354
EW
4357 $self->{url} = $opts->{ra}->{url};
4358 $self->{mods} = $mods;
4359 $self->{types} = $types;
4360 $self->{pool} = $pool;
a5e0cedc
EW
4361 $self->{bat} = { '' => $self->open_root($self->{r}, $self->{pool}) };
4362 $self->{rm} = { };
d3a840dc
EW
4363 $self->{path_prefix} = length $self->{svn_path} ?
4364 "$self->{svn_path}/" : '';
128de657 4365 $self->{config} = $opts->{config};
6abd9332 4366 $self->{mergeinfo} = $opts->{mergeinfo};
a5e0cedc
EW
4367 return $self;
4368}
4369
61395354
EW
4370sub generate_diff {
4371 my ($tree_a, $tree_b) = @_;
4372 my @diff_tree = qw(diff-tree -z -r);
24e22aa8
EW
4373 if ($_cp_similarity) {
4374 push @diff_tree, "-C$_cp_similarity";
61395354
EW
4375 } else {
4376 push @diff_tree, '-C';
4377 }
24e22aa8
EW
4378 push @diff_tree, '--find-copies-harder' if $_find_copies_harder;
4379 push @diff_tree, "-l$_rename_limit" if defined $_rename_limit;
61395354
EW
4380 push @diff_tree, $tree_a, $tree_b;
4381 my ($diff_fh, $ctx) = command_output_pipe(@diff_tree);
4382 local $/ = "\0";
4383 my $state = 'meta';
4384 my @mods;
4385 while (<$diff_fh>) {
4386 chomp $_; # this gets rid of the trailing "\0"
4387 if ($state eq 'meta' && /^:(\d{6})\s(\d{6})\s
2d0c8acc 4388 ($::sha1)\s($::sha1)\s
61395354
EW
4389 ([MTCRAD])\d*$/xo) {
4390 push @mods, { mode_a => $1, mode_b => $2,
2d0c8acc
FW
4391 sha1_a => $3, sha1_b => $4,
4392 chg => $5 };
4393 if ($5 =~ /^(?:C|R)$/) {
61395354
EW
4394 $state = 'file_a';
4395 } else {
4396 $state = 'file_b';
4397 }
4398 } elsif ($state eq 'file_a') {
4399 my $x = $mods[$#mods] or croak "Empty array\n";
4400 if ($x->{chg} !~ /^(?:C|R)$/) {
4401 croak "Error parsing $_, $x->{chg}\n";
4402 }
4403 $x->{file_a} = $_;
4404 $state = 'file_b';
4405 } elsif ($state eq 'file_b') {
4406 my $x = $mods[$#mods] or croak "Empty array\n";
4407 if (exists $x->{file_a} && $x->{chg} !~ /^(?:C|R)$/) {
4408 croak "Error parsing $_, $x->{chg}\n";
4409 }
4410 if (!exists $x->{file_a} && $x->{chg} =~ /^(?:C|R)$/) {
4411 croak "Error parsing $_, $x->{chg}\n";
4412 }
4413 $x->{file_b} = $_;
4414 $state = 'meta';
4415 } else {
4416 croak "Error parsing $_\n";
4417 }
4418 }
4419 command_close_pipe($diff_fh, $ctx);
4420 \@mods;
4421}
4422
4423sub check_diff_paths {
4424 my ($ra, $pfx, $rev, $mods) = @_;
4425 my %types;
4426 $pfx .= '/' if length $pfx;
4427
4428 sub type_diff_paths {
4429 my ($ra, $types, $path, $rev) = @_;
4430 my @p = split m#/+#, $path;
4431 my $c = shift @p;
4432 unless (defined $types->{$c}) {
4433 $types->{$c} = $ra->check_path($c, $rev);
4434 }
4435 while (@p) {
4436 $c .= '/' . shift @p;
4437 next if defined $types->{$c};
4438 $types->{$c} = $ra->check_path($c, $rev);
4439 }
4440 }
4441
4442 foreach my $m (@$mods) {
4443 foreach my $f (qw/file_a file_b/) {
4444 next unless defined $m->{$f};
4445 my ($dir) = ($m->{$f} =~ m#^(.*?)/?(?:[^/]+)$#);
4446 if (length $pfx.$dir && ! defined $types{$dir}) {
4447 type_diff_paths($ra, \%types, $pfx.$dir, $rev);
4448 }
4449 }
4450 }
4451 \%types;
4452}
4453
a5e0cedc
EW
4454sub split_path {
4455 return ($_[0] =~ m#^(.*?)/?([^/]+)$#);
4456}
4457
4458sub repo_path {
d3a840dc 4459 my ($self, $path) = @_;
3713e222
DS
4460 if (my $enc = $self->{pathnameencoding}) {
4461 require Encode;
4462 Encode::from_to($path, $enc, 'UTF-8');
4463 }
d3a840dc 4464 $self->{path_prefix}.(defined $path ? $path : '');
a5e0cedc
EW
4465}
4466
4467sub url_path {
4468 my ($self, $path) = @_;
29633bb9 4469 if ($self->{url} =~ m#^https?://#) {
884cce5b 4470 $path =~ s!([^~a-zA-Z0-9_./-])!uc sprintf("%%%02x",ord($1))!eg;
29633bb9 4471 }
6e8548cc 4472 $self->{url} . '/' . $self->repo_path($path);
a5e0cedc
EW
4473}
4474
4475sub rmdirs {
61395354 4476 my ($self) = @_;
a5e0cedc
EW
4477 my $rm = $self->{rm};
4478 delete $rm->{''}; # we never delete the url we're tracking
4479 return unless %$rm;
4480
4481 foreach (keys %$rm) {
4482 my @d = split m#/#, $_;
4483 my $c = shift @d;
4484 $rm->{$c} = 1;
4485 while (@d) {
4486 $c .= '/' . shift @d;
4487 $rm->{$c} = 1;
4488 }
4489 }
4490 delete $rm->{$self->{svn_path}};
4491 delete $rm->{''}; # we never delete the url we're tracking
4492 return unless %$rm;
4493
61395354
EW
4494 my ($fh, $ctx) = command_output_pipe(qw/ls-tree --name-only -r -z/,
4495 $self->{tree_b});
a5e0cedc
EW
4496 local $/ = "\0";
4497 while (<$fh>) {
4498 chomp;
747fa12c 4499 my @dn = split m#/#, $_;
c07eee1f
EW
4500 while (pop @dn) {
4501 delete $rm->{join '/', @dn};
4502 }
4503 unless (%$rm) {
22600a25 4504 close $fh;
c07eee1f
EW
4505 return;
4506 }
a5e0cedc 4507 }
aef4e921 4508 command_close_pipe($fh, $ctx);
c07eee1f 4509
a5e0cedc
EW
4510 my ($r, $p, $bat) = ($self->{r}, $self->{pool}, $self->{bat});
4511 foreach my $d (sort { $b =~ tr#/#/# <=> $a =~ tr#/#/# } keys %$rm) {
4512 $self->close_directory($bat->{$d}, $p);
4513 my ($dn) = ($d =~ m#^(.*?)/?(?:[^/]+)$#);
44320b9e 4514 print "\tD+\t$d/\n" unless $::_q;
a5e0cedc
EW
4515 $self->SUPER::delete_entry($d, $r, $bat->{$dn}, $p);
4516 delete $bat->{$d};
4517 }
4518}
4519
4520sub open_or_add_dir {
379862ec 4521 my ($self, $full_path, $baton, $deletions) = @_;
6e8548cc
EW
4522 my $t = $self->{types}->{$full_path};
4523 if (!defined $t) {
4524 die "$full_path not known in r$self->{r} or we have a bug!\n";
4525 }
fd499bcc
ER
4526 {
4527 no warnings 'once';
4528 # SVN::Node::none and SVN::Node::file are used only once,
4529 # so we're shutting up Perl's warnings about them.
379862ec 4530 if ($t == $SVN::Node::none || defined($deletions->{$full_path})) {
fd499bcc
ER
4531 return $self->add_directory($full_path, $baton,
4532 undef, -1, $self->{pool});
4533 } elsif ($t == $SVN::Node::dir) {
4534 return $self->open_directory($full_path, $baton,
4535 $self->{r}, $self->{pool});
4536 } # no warnings 'once'
4537 print STDERR "$full_path already exists in repository at ",
4538 "r$self->{r} and it is not a directory (",
4539 ($t == $SVN::Node::file ? 'file' : 'unknown'),"/$t)\n";
4540 } # no warnings 'once'
a5e0cedc
EW
4541 exit 1;
4542}
4543
4544sub ensure_path {
379862ec 4545 my ($self, $path, $deletions) = @_;
a5e0cedc 4546 my $bat = $self->{bat};
6e8548cc
EW
4547 my $repo_path = $self->repo_path($path);
4548 return $bat->{''} unless (length $repo_path);
379862ec 4549
6e8548cc 4550 my @p = split m#/+#, $repo_path;
a5e0cedc 4551 my $c = shift @p;
379862ec 4552 $bat->{$c} ||= $self->open_or_add_dir($c, $bat->{''}, $deletions);
a5e0cedc
EW
4553 while (@p) {
4554 my $c0 = $c;
4555 $c .= '/' . shift @p;
379862ec 4556 $bat->{$c} ||= $self->open_or_add_dir($c, $bat->{$c0}, $deletions);
a5e0cedc
EW
4557 }
4558 return $bat->{$c};
4559}
4560
128de657
BK
4561# Subroutine to convert a globbing pattern to a regular expression.
4562# From perl cookbook.
4563sub glob2pat {
4564 my $globstr = shift;
4565 my %patmap = ('*' => '.*', '?' => '.', '[' => '[', ']' => ']');
4566 $globstr =~ s{(.)} { $patmap{$1} || "\Q$1" }ge;
4567 return '^' . $globstr . '$';
4568}
4569
4570sub check_autoprop {
4571 my ($self, $pattern, $properties, $file, $fbat) = @_;
4572 # Convert the globbing pattern to a regular expression.
4573 my $regex = glob2pat($pattern);
4574 # Check if the pattern matches the file name.
4575 if($file =~ m/($regex)/) {
4576 # Parse the list of properties to set.
4577 my @props = split(/;/, $properties);
4578 foreach my $prop (@props) {
4579 # Parse 'name=value' syntax and set the property.
4580 if ($prop =~ /([^=]+)=(.*)/) {
4581 my ($n,$v) = ($1,$2);
4582 for ($n, $v) {
4583 s/^\s+//; s/\s+$//;
4584 }
4585 $self->change_file_prop($fbat, $n, $v);
4586 }
4587 }
4588 }
4589}
4590
4591sub apply_autoprops {
4592 my ($self, $file, $fbat) = @_;
4593 my $conf_t = ${$self->{config}}{'config'};
4594 no warnings 'once';
4595 # Check [miscellany]/enable-auto-props in svn configuration.
4596 if (SVN::_Core::svn_config_get_bool(
4597 $conf_t,
4598 $SVN::_Core::SVN_CONFIG_SECTION_MISCELLANY,
4599 $SVN::_Core::SVN_CONFIG_OPTION_ENABLE_AUTO_PROPS,
4600 0)) {
4601 # Auto-props are enabled. Enumerate them to look for matches.
4602 my $callback = sub {
4603 $self->check_autoprop($_[0], $_[1], $file, $fbat);
4604 };
4605 SVN::_Core::svn_config_enumerate(
4606 $conf_t,
4607 $SVN::_Core::SVN_CONFIG_SECTION_AUTO_PROPS,
4608 $callback);
4609 }
4610}
4611
a5e0cedc 4612sub A {
379862ec 4613 my ($self, $m, $deletions) = @_;
a5e0cedc 4614 my ($dir, $file) = split_path($m->{file_b});
379862ec 4615 my $pbat = $self->ensure_path($dir, $deletions);
a5e0cedc
EW
4616 my $fbat = $self->add_file($self->repo_path($m->{file_b}), $pbat,
4617 undef, -1);
44320b9e 4618 print "\tA\t$m->{file_b}\n" unless $::_q;
128de657 4619 $self->apply_autoprops($file, $fbat);
a5e0cedc
EW
4620 $self->chg_file($fbat, $m);
4621 $self->close_file($fbat,undef,$self->{pool});
4622}
4623
4624sub C {
379862ec 4625 my ($self, $m, $deletions) = @_;
a5e0cedc 4626 my ($dir, $file) = split_path($m->{file_b});
379862ec 4627 my $pbat = $self->ensure_path($dir, $deletions);
a5e0cedc
EW
4628 my $fbat = $self->add_file($self->repo_path($m->{file_b}), $pbat,
4629 $self->url_path($m->{file_a}), $self->{r});
44320b9e 4630 print "\tC\t$m->{file_a} => $m->{file_b}\n" unless $::_q;
a5e0cedc
EW
4631 $self->chg_file($fbat, $m);
4632 $self->close_file($fbat,undef,$self->{pool});
4633}
4634
4635sub delete_entry {
4636 my ($self, $path, $pbat) = @_;
4637 my $rpath = $self->repo_path($path);
4638 my ($dir, $file) = split_path($rpath);
4639 $self->{rm}->{$dir} = 1;
4640 $self->SUPER::delete_entry($rpath, $self->{r}, $pbat, $self->{pool});
4641}
4642
4643sub R {
379862ec 4644 my ($self, $m, $deletions) = @_;
a5e0cedc 4645 my ($dir, $file) = split_path($m->{file_b});
379862ec 4646 my $pbat = $self->ensure_path($dir, $deletions);
a5e0cedc
EW
4647 my $fbat = $self->add_file($self->repo_path($m->{file_b}), $pbat,
4648 $self->url_path($m->{file_a}), $self->{r});
44320b9e 4649 print "\tR\t$m->{file_a} => $m->{file_b}\n" unless $::_q;
7c4d0219 4650 $self->apply_autoprops($file, $fbat);
a5e0cedc
EW
4651 $self->chg_file($fbat, $m);
4652 $self->close_file($fbat,undef,$self->{pool});
4653
4654 ($dir, $file) = split_path($m->{file_a});
379862ec 4655 $pbat = $self->ensure_path($dir, $deletions);
a5e0cedc
EW
4656 $self->delete_entry($m->{file_a}, $pbat);
4657}
4658
4659sub M {
379862ec 4660 my ($self, $m, $deletions) = @_;
a5e0cedc 4661 my ($dir, $file) = split_path($m->{file_b});
379862ec 4662 my $pbat = $self->ensure_path($dir, $deletions);
a5e0cedc
EW
4663 my $fbat = $self->open_file($self->repo_path($m->{file_b}),
4664 $pbat,$self->{r},$self->{pool});
44320b9e 4665 print "\t$m->{chg}\t$m->{file_b}\n" unless $::_q;
a5e0cedc
EW
4666 $self->chg_file($fbat, $m);
4667 $self->close_file($fbat,undef,$self->{pool});
4668}
4669
4670sub T { shift->M(@_) }
4671
4672sub change_file_prop {
4673 my ($self, $fbat, $pname, $pval) = @_;
4674 $self->SUPER::change_file_prop($fbat, $pname, $pval, $self->{pool});
4675}
4676
6abd9332
SW
4677sub change_dir_prop {
4678 my ($self, $pbat, $pname, $pval) = @_;
4679 $self->SUPER::change_dir_prop($pbat, $pname, $pval, $self->{pool});
4680}
4681
214a34d2
FW
4682sub _chg_file_get_blob ($$$$) {
4683 my ($self, $fbat, $m, $which) = @_;
1b3069a7 4684 my $fh = $::_repository->temp_acquire("git_blob_$which");
214a34d2 4685 if ($m->{"mode_$which"} =~ /^120/) {
a5e0cedc
EW
4686 print $fh 'link ' or croak $!;
4687 $self->change_file_prop($fbat,'svn:special','*');
214a34d2 4688 } elsif ($m->{mode_a} =~ /^120/ && $m->{"mode_$which"} !~ /^120/) {
a5e0cedc
EW
4689 $self->change_file_prop($fbat,'svn:special',undef);
4690 }
214a34d2
FW
4691 my $blob = $m->{"sha1_$which"};
4692 return ($fh,) if ($blob =~ /^0{40}$/);
4693 my $size = $::_repository->cat_blob($blob, $fh);
4694 croak "Failed to read object $blob" if ($size < 0);
a5e0cedc
EW
4695 $fh->flush == 0 or croak $!;
4696 seek $fh, 0, 0 or croak $!;
4697
8d7c4fad 4698 my $exp = ::md5sum($fh);
a5e0cedc 4699 seek $fh, 0, 0 or croak $!;
214a34d2
FW
4700 return ($fh, $exp);
4701}
a5e0cedc 4702
214a34d2
FW
4703sub chg_file {
4704 my ($self, $fbat, $m) = @_;
4705 if ($m->{mode_b} =~ /755$/ && $m->{mode_a} !~ /755$/) {
4706 $self->change_file_prop($fbat,'svn:executable','*');
4707 } elsif ($m->{mode_b} !~ /755$/ && $m->{mode_a} =~ /755$/) {
4708 $self->change_file_prop($fbat,'svn:executable',undef);
4709 }
8598db93
FW
4710 my ($fh_a, $exp_a) = _chg_file_get_blob $self, $fbat, $m, 'a';
4711 my ($fh_b, $exp_b) = _chg_file_get_blob $self, $fbat, $m, 'b';
f7197dff 4712 my $pool = SVN::Pool->new;
8598db93
FW
4713 my $atd = $self->apply_textdelta($fbat, $exp_a, $pool);
4714 if (-s $fh_a) {
4715 my $txstream = SVN::TxDelta::new ($fh_a, $fh_b, $pool);
991255c6
EW
4716 my $res = SVN::TxDelta::send_txstream($txstream, @$atd, $pool);
4717 if (defined $res) {
4718 die "Unexpected result from send_txstream: $res\n",
4719 "(SVN::Core::VERSION: $SVN::Core::VERSION)\n";
4720 }
8598db93
FW
4721 } else {
4722 my $got = SVN::TxDelta::send_stream($fh_b, @$atd, $pool);
4723 die "Checksum mismatch\nexpected: $exp_b\ngot: $got\n"
4724 if ($got ne $exp_b);
4725 }
4726 Git::temp_release($fh_b, 1);
4727 Git::temp_release($fh_a, 1);
f7197dff 4728 $pool->clear;
a5e0cedc
EW
4729}
4730
4731sub D {
379862ec 4732 my ($self, $m, $deletions) = @_;
a5e0cedc 4733 my ($dir, $file) = split_path($m->{file_b});
379862ec 4734 my $pbat = $self->ensure_path($dir, $deletions);
44320b9e 4735 print "\tD\t$m->{file_b}\n" unless $::_q;
a5e0cedc
EW
4736 $self->delete_entry($m->{file_b}, $pbat);
4737}
4738
4739sub close_edit {
4740 my ($self) = @_;
4741 my ($p,$bat) = ($self->{pool}, $self->{bat});
4742 foreach (sort { $b =~ tr#/#/# <=> $a =~ tr#/#/# } keys %$bat) {
6442754d 4743 next if $_ eq '';
a5e0cedc
EW
4744 $self->close_directory($bat->{$_}, $p);
4745 }
6442754d 4746 $self->close_directory($bat->{''}, $p);
a5e0cedc
EW
4747 $self->SUPER::close_edit($p);
4748 $p->clear;
4749}
4750
4751sub abort_edit {
4752 my ($self) = @_;
4753 $self->SUPER::abort_edit($self->{pool});
61395354
EW
4754}
4755
4756sub DESTROY {
4757 my $self = shift;
4758 $self->SUPER::DESTROY(@_);
a5e0cedc
EW
4759 $self->{pool}->clear;
4760}
4761
44320b9e
EW
4762# this drives the editor
4763sub apply_diff {
61395354
EW
4764 my ($self) = @_;
4765 my $mods = $self->{mods};
5ec514bd 4766 my %o = ( D => 0, C => 1, R => 2, A => 3, M => 4, T => 5 );
379862ec
SW
4767 my %deletions;
4768
4769 foreach my $m (@$mods) {
4770 if ($m->{chg} eq "D") {
4771 $deletions{$m->{file_b}} = 1;
4772 }
4773 }
4774
6e8548cc 4775 foreach my $m (sort { $o{$a->{chg}} <=> $o{$b->{chg}} } @$mods) {
44320b9e
EW
4776 my $f = $m->{chg};
4777 if (defined $o{$f}) {
379862ec 4778 $self->$f($m, \%deletions);
44320b9e 4779 } else {
207f1a75 4780 fatal("Invalid change type: $f");
44320b9e
EW
4781 }
4782 }
6abd9332
SW
4783
4784 if (defined($self->{mergeinfo})) {
4785 $self->change_dir_prop($self->{bat}{''}, "svn:mergeinfo",
4786 $self->{mergeinfo});
4787 }
24e22aa8 4788 $self->rmdirs if $_rmdir;
93ccbba6 4789 if (@$mods == 0 && !defined($self->{mergeinfo})) {
44320b9e
EW
4790 $self->abort_edit;
4791 } else {
4792 $self->close_edit;
4793 }
6e8548cc 4794 return scalar @$mods;
44320b9e
EW
4795}
4796
d81bf827 4797package Git::SVN::Ra;
cdb51a13 4798use vars qw/@ISA $config_dir $_ignore_refs_regex $_log_window_size/;
d81bf827
EW
4799use strict;
4800use warnings;
a51cdb0c 4801my ($ra_invalid, $can_do_switch, %ignored_err, $RA);
d81bf827
EW
4802
4803BEGIN {
4804 # enforce temporary pool usage for some simple functions
c5f71ad0 4805 no strict 'refs';
bf8a40b8
EW
4806 for my $f (qw/rev_proplist get_latest_revnum get_uuid get_repos_root
4807 get_file/) {
c5f71ad0
SV
4808 my $SUPER = "SUPER::$f";
4809 *$f = sub {
4810 my $self = shift;
4811 my $pool = SVN::Pool->new;
4812 my @ret = $self->$SUPER(@_,$pool);
4813 $pool->clear;
4814 wantarray ? @ret : $ret[0];
4815 };
d81bf827 4816 }
d81bf827
EW
4817}
4818
9ff74e95 4819sub _auth_providers () {
082afee6 4820 my @rv = (
9ff74e95
SW
4821 SVN::Client::get_simple_provider(),
4822 SVN::Client::get_ssl_server_trust_file_provider(),
4823 SVN::Client::get_simple_prompt_provider(
4824 \&Git::SVN::Prompt::simple, 2),
4825 SVN::Client::get_ssl_client_cert_file_provider(),
4826 SVN::Client::get_ssl_client_cert_prompt_provider(
4827 \&Git::SVN::Prompt::ssl_client_cert, 2),
77266e96 4828 SVN::Client::get_ssl_client_cert_pw_file_provider(),
9ff74e95
SW
4829 SVN::Client::get_ssl_client_cert_pw_prompt_provider(
4830 \&Git::SVN::Prompt::ssl_client_cert_pw, 2),
4831 SVN::Client::get_username_provider(),
4832 SVN::Client::get_ssl_server_trust_prompt_provider(
4833 \&Git::SVN::Prompt::ssl_server_trust),
4834 SVN::Client::get_username_prompt_provider(
4835 \&Git::SVN::Prompt::username, 2)
082afee6
MK
4836 );
4837
4838 # earlier 1.6.x versions would segfault, and <= 1.5.x didn't have
4839 # this function
f760c903 4840 if (::compare_svn_version('1.6.12') > 0) {
082afee6
MK
4841 my $config = SVN::Core::config_get_config($config_dir);
4842 my ($p, @a);
4843 # config_get_config returns all config files from
4844 # ~/.subversion, auth_get_platform_specific_client_providers
4845 # just wants the config "file".
4846 @a = ($config->{'config'}, undef);
4847 $p = SVN::Core::auth_get_platform_specific_client_providers(@a);
4848 # Insert the return value from
4849 # auth_get_platform_specific_providers
4850 unshift @rv, @$p;
4851 }
4852 \@rv;
9ff74e95
SW
4853}
4854
cfbe7ab3
EW
4855sub escape_uri_only {
4856 my ($uri) = @_;
4857 my @tmp;
4858 foreach (split m{/}, $uri) {
6a004d3f 4859 s/([^~\w.%+-]|%(?![a-fA-F0-9]{2}))/sprintf("%%%02X",ord($1))/eg;
cfbe7ab3
EW
4860 push @tmp, $_;
4861 }
4862 join('/', @tmp);
4863}
4864
4865sub escape_url {
4866 my ($url) = @_;
4867 if ($url =~ m#^(https?)://([^/]+)(.*)$#) {
4868 my ($scheme, $domain, $uri) = ($1, $2, escape_uri_only($3));
4869 $url = "$scheme://$domain$uri";
4870 }
4871 $url;
4872}
4873
d81bf827
EW
4874sub new {
4875 my ($class, $url) = @_;
f6f09876 4876 $url =~ s!/+$!!;
5d3b7cd5 4877 return $RA if ($RA && $RA->{url} eq $url);
f6f09876 4878
d32fad2b 4879 ::_req_svn();
4880
d81bf827 4881 SVN::_Core::svn_config_ensure($config_dir, undef);
9ff74e95 4882 my ($baton, $callbacks) = SVN::Core::auth_open_helper(_auth_providers);
d81bf827 4883 my $config = SVN::Core::config_get_config($config_dir);
7730fbe6 4884 $RA = undef;
602015e0
ER
4885 my $dont_store_passwords = 1;
4886 my $conf_t = ${$config}{'config'};
4887 {
fd499bcc 4888 no warnings 'once';
602015e0
ER
4889 # The usage of $SVN::_Core::SVN_CONFIG_* variables
4890 # produces warnings that variables are used only once.
4891 # I had not found the better way to shut them up, so
fd499bcc 4892 # the warnings of type 'once' are disabled in this block.
602015e0
ER
4893 if (SVN::_Core::svn_config_get_bool($conf_t,
4894 $SVN::_Core::SVN_CONFIG_SECTION_AUTH,
4895 $SVN::_Core::SVN_CONFIG_OPTION_STORE_PASSWORDS,
4896 1) == 0) {
4897 SVN::_Core::svn_auth_set_parameter($baton,
4898 $SVN::_Core::SVN_AUTH_PARAM_DONT_STORE_PASSWORDS,
4899 bless (\$dont_store_passwords, "_p_void"));
4900 }
4901 if (SVN::_Core::svn_config_get_bool($conf_t,
4902 $SVN::_Core::SVN_CONFIG_SECTION_AUTH,
4903 $SVN::_Core::SVN_CONFIG_OPTION_STORE_AUTH_CREDS,
4904 1) == 0) {
4905 $Git::SVN::Prompt::_no_auth_cache = 1;
4906 }
fd499bcc 4907 } # no warnings 'once'
cfbe7ab3 4908 my $self = SVN::Ra->new(url => escape_url($url), auth => $baton,
d81bf827
EW
4909 config => $config,
4910 pool => SVN::Pool->new,
4911 auth_provider_callbacks => $callbacks);
cfbe7ab3 4912 $self->{url} = $url;
d81bf827
EW
4913 $self->{svn_path} = $url;
4914 $self->{repos_root} = $self->get_repos_root;
4e9f6cc7 4915 $self->{svn_path} =~ s#^\Q$self->{repos_root}\E(/|$)##;
0dc03d6a
EW
4916 $self->{cache} = { check_path => { r => 0, data => {} },
4917 get_dir => { r => 0, data => {} } };
5d3b7cd5 4918 $RA = bless $self, $class;
d81bf827
EW
4919}
4920
0dc03d6a
EW
4921sub check_path {
4922 my ($self, $path, $r) = @_;
4923 my $cache = $self->{cache}->{check_path};
4924 if ($r == $cache->{r} && exists $cache->{data}->{$path}) {
4925 return $cache->{data}->{$path};
4926 }
4927 my $pool = SVN::Pool->new;
4928 my $t = $self->SUPER::check_path($path, $r, $pool);
4929 $pool->clear;
4930 if ($r != $cache->{r}) {
4931 %{$cache->{data}} = ();
4932 $cache->{r} = $r;
4933 }
4934 $cache->{data}->{$path} = $t;
4935}
4936
4937sub get_dir {
4938 my ($self, $dir, $r) = @_;
4939 my $cache = $self->{cache}->{get_dir};
4940 if ($r == $cache->{r}) {
4941 if (my $x = $cache->{data}->{$dir}) {
4942 return wantarray ? @$x : $x->[0];
4943 }
4944 }
4945 my $pool = SVN::Pool->new;
4946 my ($d, undef, $props) = $self->SUPER::get_dir($dir, $r, $pool);
4947 my %dirents = map { $_ => { kind => $d->{$_}->kind } } keys %$d;
4948 $pool->clear;
4949 if ($r != $cache->{r}) {
4950 %{$cache->{data}} = ();
4951 $cache->{r} = $r;
4952 }
4953 $cache->{data}->{$dir} = [ \%dirents, $r, $props ];
4954 wantarray ? (\%dirents, $r, $props) : \%dirents;
4955}
4956
d81bf827 4957sub DESTROY {
5d3b7cd5 4958 # do not call the real DESTROY since we store ourselves in $RA
d81bf827
EW
4959}
4960
1ef626b4
EW
4961# get_log(paths, start, end, limit,
4962# discover_changed_paths, strict_node_history, receiver)
d81bf827
EW
4963sub get_log {
4964 my ($self, @args) = @_;
4965 my $pool = SVN::Pool->new;
1ef626b4 4966
3c49a035
MN
4967 # svn_log_changed_path_t objects passed to get_log are likely to be
4968 # overwritten even if only the refs are copied to an external variable,
4969 # so we should dup the structures in their entirety. Using an
4970 # externally passed pool (instead of our temporary and quickly cleared
4971 # pool in Git::SVN::Ra) does not help matters at all...
4972 my $receiver = pop @args;
0b2af457
MN
4973 my $prefix = "/".$self->{svn_path};
4974 $prefix =~ s#/+($)##;
4975 my $prefix_regex = qr#^\Q$prefix\E#;
3c49a035
MN
4976 push(@args, sub {
4977 my ($paths) = $_[0];
4978 return &$receiver(@_) unless $paths;
4979 $_[0] = ();
4980 foreach my $p (keys %$paths) {
4981 my $i = $paths->{$p};
0b2af457
MN
4982 # Make path relative to our url, not repos_root
4983 $p =~ s/$prefix_regex//;
4984 my %s = map { $_ => $i->$_; }
4985 qw/copyfrom_path copyfrom_rev action/;
4986 if ($s{'copyfrom_path'}) {
4987 $s{'copyfrom_path'} =~ s/$prefix_regex//;
4988 }
3c49a035
MN
4989 $_[0]{$p} = \%s;
4990 }
4991 &$receiver(@_);
4992 });
4993
4994
1ef626b4
EW
4995 # the limit parameter was not supported in SVN 1.1.x, so we
4996 # drop it. Therefore, the receiver callback passed to it
4997 # is made aware of this limitation by being wrapped if
4998 # the limit passed to is being wrapped.
f760c903 4999 if (::compare_svn_version('1.2.0') <= 0) {
1ef626b4
EW
5000 my $limit = splice(@args, 3, 1);
5001 if ($limit > 0) {
5002 my $receiver = pop @args;
5003 push(@args, sub { &$receiver(@_) if (--$limit >= 0) });
5004 }
5005 }
d81bf827
EW
5006 my $ret = $self->SUPER::get_log(@args, $pool);
5007 $pool->clear;
5008 $ret;
5009}
5010
9ff74e95
SW
5011sub trees_match {
5012 my ($self, $url1, $rev1, $url2, $rev2) = @_;
5013 my $ctx = SVN::Client->new(auth => _auth_providers);
5014 my $out = IO::File->new_tmpfile;
5015
5016 # older SVN (1.1.x) doesn't take $pool as the last parameter for
5017 # $ctx->diff(), so we'll create a default one
5018 my $pool = SVN::Pool->new_default_sub;
5019
5020 $ra_invalid = 1; # this will open a new SVN::Ra connection to $url1
5021 $ctx->diff([], $url1, $rev1, $url2, $rev2, 1, 1, 0, $out, $out);
5022 $out->flush;
5023 my $ret = (($out->stat)[7] == 0);
5024 close $out or croak $!;
5025
5026 $ret;
5027}
5028
d81bf827 5029sub get_commit_editor {
44320b9e 5030 my ($self, $log, $cb, $pool) = @_;
f760c903
JH
5031
5032 my @lock = (::compare_svn_version('1.2.0') >= 0) ? (undef, 0) : ();
44320b9e 5033 $self->SUPER::get_commit_editor($log, $cb, @lock, $pool);
d81bf827
EW
5034}
5035
d81bf827 5036sub gs_do_update {
8a603774
EW
5037 my ($self, $rev_a, $rev_b, $gs, $editor) = @_;
5038 my $new = ($rev_a == $rev_b);
5039 my $path = $gs->{path};
5040
2e5e2480
EW
5041 if ($new && -e $gs->{index}) {
5042 unlink $gs->{index} or die
5043 "Couldn't unlink index: $gs->{index}: $!\n";
5044 }
d81bf827 5045 my $pool = SVN::Pool->new;
8b8fc068 5046 $editor->set_path_strip($path);
2b27f6c8
EW
5047 my (@pc) = split m#/#, $path;
5048 my $reporter = $self->do_update($rev_b, (@pc ? shift @pc : ''),
8a603774 5049 1, $editor, $pool);
f760c903 5050 my @lock = (::compare_svn_version('1.2.0') >= 0) ? (undef) : ();
2b27f6c8
EW
5051
5052 # Since we can't rely on svn_ra_reparent being available, we'll
5053 # just have to do some magic with set_path to make it so
5054 # we only want a partial path.
5055 my $sp = '';
5056 my $final = join('/', @pc);
5057 while (@pc) {
5058 $reporter->set_path($sp, $rev_b, 0, @lock, $pool);
5059 $sp .= '/' if length $sp;
5060 $sp .= shift @pc;
5061 }
5062 die "BUG: '$sp' != '$final'\n" if ($sp ne $final);
5063
2b27f6c8
EW
5064 $reporter->set_path($sp, $rev_a, $new, @lock, $pool);
5065
d81bf827
EW
5066 $reporter->finish_report($pool);
5067 $pool->clear;
5068 $editor->{git_commit_ok};
5069}
5070
2b27f6c8
EW
5071# this requires SVN 1.4.3 or later (do_switch didn't work before 1.4.3, and
5072# svn_ra_reparent didn't work before 1.4)
d81bf827 5073sub gs_do_switch {
8a603774
EW
5074 my ($self, $rev_a, $rev_b, $gs, $url_b, $editor) = @_;
5075 my $path = $gs->{path};
d81bf827 5076 my $pool = SVN::Pool->new;
2b27f6c8
EW
5077
5078 my $full_url = $self->{url};
5079 my $old_url = $full_url;
2a679c7a 5080 $full_url .= '/' . $path if length $path;
5d3b7cd5 5081 my ($ra, $reparented);
ad0a82ba 5082
2a679c7a
EW
5083 if ($old_url =~ m#^svn(\+ssh)?://# ||
5084 ($full_url =~ m#^https?://# &&
5085 escape_url($full_url) ne $full_url)) {
ad0a82ba
AB
5086 $_[0] = undef;
5087 $self = undef;
5088 $RA = undef;
5089 $ra = Git::SVN::Ra->new($full_url);
5090 $ra_invalid = 1;
5091 } elsif ($old_url ne $full_url) {
5092 SVN::_Ra::svn_ra_reparent($self->{session}, $full_url, $pool);
5093 $self->{url} = $full_url;
5094 $reparented = 1;
5d3b7cd5 5095 }
ad0a82ba 5096
5d3b7cd5 5097 $ra ||= $self;
f4392df4 5098 $url_b = escape_url($url_b);
8a603774 5099 my $reporter = $ra->do_switch($rev_b, '', 1, $url_b, $editor, $pool);
f760c903 5100 my @lock = (::compare_svn_version('1.2.0') >= 0) ? (undef) : ();
8b8fc068 5101 $reporter->set_path('', $rev_a, 0, @lock, $pool);
d81bf827 5102 $reporter->finish_report($pool);
2b27f6c8 5103
5d3b7cd5
EW
5104 if ($reparented) {
5105 SVN::_Ra::svn_ra_reparent($self->{session}, $old_url, $pool);
5106 $self->{url} = $old_url;
5107 }
2b27f6c8 5108
d81bf827
EW
5109 $pool->clear;
5110 $editor->{git_commit_ok};
5111}
5112
b54a901e
EW
5113sub longest_common_path {
5114 my ($gsv, $globs) = @_;
d2ae1434 5115 my %common;
e518192f
EW
5116 my $common_max = scalar @$gsv;
5117
5118 foreach my $gs (@$gsv) {
d2ae1434
EW
5119 my @tmp = split m#/#, $gs->{path};
5120 my $p = '';
5121 foreach (@tmp) {
5122 $p .= length($p) ? "/$_" : $_;
5123 $common{$p} ||= 0;
5124 $common{$p}++;
5125 }
5126 }
e518192f
EW
5127 $globs ||= [];
5128 $common_max += scalar @$globs;
5129 foreach my $glob (@$globs) {
5130 my @tmp = split m#/#, $glob->{path}->{left};
5131 my $p = '';
5132 foreach (@tmp) {
5133 $p .= length($p) ? "/$_" : $_;
5134 $common{$p} ||= 0;
5135 $common{$p}++;
5136 }
5137 }
5138
d2ae1434
EW
5139 my $longest_path = '';
5140 foreach (sort {length $b <=> length $a} keys %common) {
e518192f 5141 if ($common{$_} == $common_max) {
d2ae1434
EW
5142 $longest_path = $_;
5143 last;
5144 }
0af9c9f9 5145 }
b54a901e
EW
5146 $longest_path;
5147}
5148
5149sub gs_fetch_loop_common {
5150 my ($self, $base, $head, $gsv, $globs) = @_;
5151 return if ($base > $head);
5152 my $inc = $_log_window_size;
5153 my ($min, $max) = ($base, $head < $base + $inc ? $head : $base + $inc);
5154 my $longest_path = longest_common_path($gsv, $globs);
a51cdb0c 5155 my $ra_url = $self->{url};
c69700fe 5156 my $find_trailing_edge;
0af9c9f9 5157 while (1) {
d4eff2bd 5158 my %revs;
d2ae1434 5159 my $err;
f7c3fc4a 5160 my $err_handler = $SVN::Error::handler;
d2ae1434
EW
5161 $SVN::Error::handler = sub {
5162 ($err) = @_;
5163 skip_unknown_revs($err);
5164 };
5165 sub _cb {
5166 my ($paths, $r, $author, $date, $log) = @_;
3c49a035 5167 [ $paths,
d2ae1434
EW
5168 { author => $author, date => $date, log => $log } ];
5169 }
5170 $self->get_log([$longest_path], $min, $max, 0, 1, 1,
5171 sub { $revs{$_[1]} = _cb(@_) });
99366565
DM
5172 if ($err) {
5173 print "Checked through r$max\r";
c69700fe
AV
5174 } else {
5175 $find_trailing_edge = 1;
99366565 5176 }
c69700fe 5177 if ($err and $find_trailing_edge) {
d2ae1434
EW
5178 print STDERR "Path '$longest_path' ",
5179 "was probably deleted:\n",
5180 $err->expanded_message,
5181 "\nWill attempt to follow ",
5182 "revisions r$min .. r$max ",
5183 "committed before the deletion\n";
5184 my $hi = $max;
5185 while (--$hi >= $min) {
5186 my $ok;
5187 $self->get_log([$longest_path], $min, $hi,
5188 0, 1, 1, sub {
b6c61778 5189 $ok = $_[1];
d2ae1434
EW
5190 $revs{$_[1]} = _cb(@_) });
5191 if ($ok) {
5192 print STDERR "r$min .. r$ok OK\n";
5193 last;
5194 }
5195 }
c69700fe 5196 $find_trailing_edge = 0;
d2ae1434 5197 }
d4eff2bd 5198 $SVN::Error::handler = $err_handler;
fbcc1737 5199
e518192f 5200 my %exists = map { $_->{path} => $_ } @$gsv;
d4eff2bd 5201 foreach my $r (sort {$a <=> $b} keys %revs) {
fbcc1737 5202 my ($paths, $logged) = @{$revs{$r}};
e518192f
EW
5203
5204 foreach my $gs ($self->match_globs(\%exists, $paths,
5205 $globs, $r)) {
060610c5 5206 if ($gs->rev_map_max >= $r) {
fbcc1737
EW
5207 next;
5208 }
5209 next unless $gs->match_paths($paths, $r);
5210 $gs->{logged_rev_props} = $logged;
e8d120bd
EW
5211 if (my $last_commit = $gs->last_commit) {
5212 $gs->assert_index_clean($last_commit);
5213 }
fbcc1737
EW
5214 my $log_entry = $gs->do_fetch($paths, $r);
5215 if ($log_entry) {
0af9c9f9
EW
5216 $gs->do_git_commit($log_entry);
5217 }
321b1842 5218 $INDEX_FILES{$gs->{index}} = 1;
0af9c9f9 5219 }
e518192f 5220 foreach my $g (@$globs) {
93f2689c
EW
5221 my $k = "svn-remote.$g->{remote}." .
5222 "$g->{t}-maxRev";
5223 Git::SVN::tmp_config($k, $r);
e518192f 5224 }
a51cdb0c
EW
5225 if ($ra_invalid) {
5226 $_[0] = undef;
5227 $self = undef;
5228 $RA = undef;
5229 $self = Git::SVN::Ra->new($ra_url);
5230 $ra_invalid = undef;
5231 }
0af9c9f9 5232 }
9c93fee5
EW
5233 # pre-fill the .rev_db since it'll eventually get filled in
5234 # with '0' x40 if something new gets committed
e518192f 5235 foreach my $gs (@$gsv) {
66ab84b9
EW
5236 next if $gs->rev_map_max >= $max;
5237 next if defined $gs->rev_map_get($max);
5238 $gs->rev_map_set($max, 0 x40);
9c93fee5 5239 }
c3560e53
EW
5240 foreach my $g (@$globs) {
5241 my $k = "svn-remote.$g->{remote}.$g->{t}-maxRev";
5242 Git::SVN::tmp_config($k, $max);
5243 }
0af9c9f9
EW
5244 last if $max >= $head;
5245 $min = $max + 1;
5246 $max += $inc;
5247 $max = $head if ($max > $head);
5248 }
94bc914c 5249 Git::SVN::gc();
0af9c9f9
EW
5250}
5251
570d35c2
MG
5252sub get_dir_globbed {
5253 my ($self, $left, $depth, $r) = @_;
5254
5255 my @x = eval { $self->get_dir($left, $r) };
5256 return unless scalar @x == 3;
5257 my $dirents = $x[0];
5258 my @finalents;
5259 foreach my $de (keys %$dirents) {
5260 next if $dirents->{$de}->{kind} != $SVN::Node::dir;
5261 if ($depth > 1) {
5262 my @args = ("$left/$de", $depth - 1, $r);
5263 foreach my $dir ($self->get_dir_globbed(@args)) {
5264 push @finalents, "$de/$dir";
5265 }
5266 } else {
5267 push @finalents, $de;
5268 }
5269 }
5270 @finalents;
5271}
5272
cdb51a13
MO
5273# return value: 0 -- don't ignore, 1 -- ignore
5274sub is_ref_ignored {
5275 my ($g, $p) = @_;
5276 my $refname = $g->{ref}->full_path($p);
5277 return 1 if defined($g->{ignore_refs_regex}) &&
5278 $refname =~ m!$g->{ignore_refs_regex}!;
5279 return 0 unless defined($_ignore_refs_regex);
5280 return 1 if $refname =~ m!$_ignore_refs_regex!o;
5281 return 0;
5282}
5283
e518192f
EW
5284sub match_globs {
5285 my ($self, $exists, $paths, $globs, $r) = @_;
74a81227
EW
5286
5287 sub get_dir_check {
5288 my ($self, $exists, $g, $r) = @_;
570d35c2
MG
5289
5290 my @dirs = $self->get_dir_globbed($g->{path}->{left},
5291 $g->{path}->{depth},
5292 $r);
5293
5294 foreach my $de (@dirs) {
74a81227
EW
5295 my $p = $g->{path}->full_path($de);
5296 next if $exists->{$p};
5297 next if (length $g->{path}->{right} &&
5298 ($self->check_path($p, $r) !=
5299 $SVN::Node::dir));
07576208 5300 next unless $p =~ /$g->{path}->{regex}/;
74a81227
EW
5301 $exists->{$p} = Git::SVN->init($self->{url}, $p, undef,
5302 $g->{ref}->full_path($de), 1);
5303 }
5304 }
e518192f 5305 foreach my $g (@$globs) {
74a81227
EW
5306 if (my $path = $paths->{"/$g->{path}->{left}"}) {
5307 if ($path->{action} =~ /^[AR]$/) {
5308 get_dir_check($self, $exists, $g, $r);
5309 }
5310 }
e518192f 5311 foreach (keys %$paths) {
28710f74
EW
5312 if (/$g->{path}->{left_regex}/ &&
5313 !/$g->{path}->{regex}/) {
74a81227
EW
5314 next if $paths->{$_}->{action} !~ /^[AR]$/;
5315 get_dir_check($self, $exists, $g, $r);
5316 }
e518192f
EW
5317 next unless /$g->{path}->{regex}/;
5318 my $p = $1;
5319 my $pathname = $g->{path}->full_path($p);
cdb51a13 5320 next if is_ref_ignored($g, $p);
e518192f 5321 next if $exists->{$pathname};
0c1ec5a1
EW
5322 next if ($self->check_path($pathname, $r) !=
5323 $SVN::Node::dir);
e518192f
EW
5324 $exists->{$pathname} = Git::SVN->init(
5325 $self->{url}, $pathname, undef,
5326 $g->{ref}->full_path($p), 1);
5327 }
5328 my $c = '';
5329 foreach (split m#/#, $g->{path}->{left}) {
5330 $c .= "/$_";
5331 next unless ($paths->{$c} &&
74a81227
EW
5332 ($paths->{$c}->{action} =~ /^[AR]$/));
5333 get_dir_check($self, $exists, $g, $r);
e518192f
EW
5334 }
5335 }
5336 values %$exists;
5337}
5338
e6434f87
EW
5339sub minimize_url {
5340 my ($self) = @_;
5341 return $self->{url} if ($self->{url} eq $self->{repos_root});
5342 my $url = $self->{repos_root};
5343 my @components = split(m!/!, $self->{svn_path});
5344 my $c = '';
5345 do {
5346 $url .= "/$c" if length $c;
5f8b2cba
EW
5347 eval {
5348 my $ra = (ref $self)->new($url);
5349 my $latest = $ra->get_latest_revnum;
5350 $ra->get_log("", $latest, 0, 1, 0, 1, sub {});
5351 };
e6434f87
EW
5352 } while ($@ && ($c = shift @components));
5353 $url;
5354}
5355
d81bf827
EW
5356sub can_do_switch {
5357 my $self = shift;
5358 unless (defined $can_do_switch) {
5359 my $pool = SVN::Pool->new;
5360 my $rep = eval {
5361 $self->do_switch(1, '', 0, $self->{url},
5362 SVN::Delta::Editor->new, $pool);
5363 };
5364 if ($@) {
5365 $can_do_switch = 0;
5366 } else {
5367 $rep->abort_report($pool);
5368 $can_do_switch = 1;
5369 }
5370 $pool->clear;
5371 }
5372 $can_do_switch;
5373}
5374
0af9c9f9
EW
5375sub skip_unknown_revs {
5376 my ($err) = @_;
5377 my $errno = $err->apr_err();
5378 # Maybe the branch we're tracking didn't
5379 # exist when the repo started, so it's
5380 # not an error if it doesn't, just continue
5381 #
5382 # Wonderfully consistent library, eh?
5383 # 160013 - svn:// and file://
5384 # 175002 - http(s)://
5385 # 175007 - http(s):// (this repo required authorization, too...)
5386 # More codes may be discovered later...
5387 if ($errno == 175007 || $errno == 175002 || $errno == 160013) {
a6a15a99
EW
5388 my $err_key = $err->expanded_message;
5389 # revision numbers change every time, filter them out
5390 $err_key =~ s/\d+/\0/g;
5391 $err_key = "$errno\0$err_key";
5392 unless ($ignored_err{$err_key}) {
5393 warn "W: Ignoring error from SVN, path probably ",
5394 "does not exist: ($errno): ",
5395 $err->expanded_message,"\n";
eee8a174
EW
5396 warn "W: Do not be alarmed at the above message ",
5397 "git-svn is just searching aggressively for ",
5398 "old history.\n",
5399 "This may take a while on large repositories\n";
a6a15a99
EW
5400 $ignored_err{$err_key} = 1;
5401 }
0af9c9f9
EW
5402 return;
5403 }
5404 die "Error from SVN, ($errno): ", $err->expanded_message,"\n";
5405}
5406
f8c9d1d2
EW
5407package Git::SVN::Log;
5408use strict;
5409use warnings;
5410use POSIX qw/strftime/;
111947ef 5411use constant commit_log_separator => ('-' x 72) . "\n";
f8c9d1d2
EW
5412use vars qw/$TZ $limit $color $pager $non_recursive $verbose $oneline
5413 %rusers $show_commit $incremental/;
5414my $l_fmt;
5415
5416sub cmt_showable {
5417 my ($c) = @_;
5418 return 1 if defined $c->{r};
c16d0871
EW
5419
5420 # big commit message got truncated by the 16k pretty buffer in rev-list
f8c9d1d2
EW
5421 if ($c->{l} && $c->{l}->[-1] eq "...\n" &&
5422 $c->{a_raw} =~ /\@([a-f\d\-]+)>$/) {
c16d0871 5423 @{$c->{l}} = ();
44320b9e 5424 my @log = command(qw/cat-file commit/, $c->{c});
c16d0871
EW
5425
5426 # shift off the headers
5427 shift @log while ($log[0] ne '');
44320b9e 5428 shift @log;
c16d0871
EW
5429
5430 # TODO: make $c->{l} not have a trailing newline in the future
5431 @{$c->{l}} = map { "$_\n" } grep !/^git-svn-id: /, @log;
f8c9d1d2
EW
5432
5433 (undef, $c->{r}, undef) = ::extract_metadata(
44320b9e 5434 (grep(/^git-svn-id: /, @log))[-1]);
f8c9d1d2
EW
5435 }
5436 return defined $c->{r};
5437}
5438
5439sub log_use_color {
cd459e3f 5440 return $color || Git->repository->get_colorbool('color.diff');
f8c9d1d2
EW
5441}
5442
5443sub git_svn_log_cmd {
3bc718ba
EW
5444 my ($r_min, $r_max, @args) = @_;
5445 my $head = 'HEAD';
6ed77266 5446 my (@files, @log_opts);
3bc718ba 5447 foreach my $x (@args) {
6ed77266
EW
5448 if ($x eq '--' || @files) {
5449 push @files, $x;
5450 } else {
5451 if (::verify_ref("$x^0")) {
5452 $head = $x;
5453 } else {
5454 push @log_opts, $x;
5455 }
5456 }
3bc718ba
EW
5457 }
5458
13c823fb
EW
5459 my ($url, $rev, $uuid, $gs) = ::working_head_info($head);
5460 $gs ||= Git::SVN->_new;
f8c9d1d2
EW
5461 my @cmd = (qw/log --abbrev-commit --pretty=raw --default/,
5462 $gs->refname);
5463 push @cmd, '-r' unless $non_recursive;
5464 push @cmd, qw/--raw --name-status/ if $verbose;
5465 push @cmd, '--color' if log_use_color();
6ed77266
EW
5466 push @cmd, @log_opts;
5467 if (defined $r_max && $r_max == $r_min) {
f8c9d1d2 5468 push @cmd, '--max-count=1';
060610c5 5469 if (my $c = $gs->rev_map_get($r_max)) {
f8c9d1d2
EW
5470 push @cmd, $c;
5471 }
6ed77266 5472 } elsif (defined $r_max) {
111947ef
DK
5473 if ($r_max < $r_min) {
5474 ($r_min, $r_max) = ($r_max, $r_min);
5475 }
5476 my (undef, $c_max) = $gs->find_rev_before($r_max, 1, $r_min);
5477 my (undef, $c_min) = $gs->find_rev_after($r_min, 1, $r_max);
5478 # If there are no commits in the range, both $c_max and $c_min
5479 # will be undefined. If there is at least 1 commit in the
5480 # range, both will be defined.
5481 return () if !defined $c_min || !defined $c_max;
5482 if ($c_min eq $c_max) {
5483 push @cmd, '--max-count=1', $c_min;
f8c9d1d2 5484 } else {
111947ef 5485 push @cmd, '--boundary', "$c_min..$c_max";
f8c9d1d2
EW
5486 }
5487 }
6ed77266 5488 return (@cmd, @files);
f8c9d1d2
EW
5489}
5490
5491# adapted from pager.c
5492sub config_pager {
190c1cda
JN
5493 if (! -t *STDOUT) {
5494 $ENV{GIT_PAGER_IN_USE} = 'false';
5495 $pager = undef;
5496 return;
5497 }
5498 chomp($pager = command_oneline(qw(var GIT_PAGER)));
dec543e6 5499 if ($pager eq 'cat') {
f8c9d1d2
EW
5500 $pager = undef;
5501 }
cd459e3f 5502 $ENV{GIT_PAGER_IN_USE} = defined($pager);
f8c9d1d2
EW
5503}
5504
5505sub run_pager {
190c1cda 5506 return unless defined $pager;
971e6283 5507 pipe my ($rfd, $wfd) or return;
207f1a75 5508 defined(my $pid = fork) or ::fatal "Can't fork: $!";
f8c9d1d2
EW
5509 if (!$pid) {
5510 open STDOUT, '>&', $wfd or
207f1a75 5511 ::fatal "Can't redirect to stdout: $!";
f8c9d1d2
EW
5512 return;
5513 }
207f1a75 5514 open STDIN, '<&', $rfd or ::fatal "Can't redirect stdin: $!";
f8c9d1d2 5515 $ENV{LESS} ||= 'FRSX';
207f1a75 5516 exec $pager or ::fatal "Can't run pager: $! ($pager)";
f8c9d1d2
EW
5517}
5518
b2b3ada7 5519sub format_svn_date {
736e619a 5520 my $t = shift || time;
6aa17fc6 5521 my $gmoff = Git::SVN::get_tz($t);
e8717841 5522 return strftime("%Y-%m-%d %H:%M:%S $gmoff (%a, %d %b %Y)", localtime($t));
b2b3ada7
DK
5523}
5524
5525sub parse_git_date {
5526 my ($t, $tz) = @_;
5527 # Date::Parse isn't in the standard Perl distro :(
5528 if ($tz =~ s/^\+//) {
5529 $t += tz_to_s_offset($tz);
5530 } elsif ($tz =~ s/^\-//) {
5531 $t -= tz_to_s_offset($tz);
5532 }
5533 return $t;
5534}
5535
5536sub set_local_timezone {
5537 if (defined $TZ) {
5538 $ENV{TZ} = $TZ;
5539 } else {
5540 delete $ENV{TZ};
5541 }
5542}
5543
21819a37
EW
5544sub tz_to_s_offset {
5545 my ($tz) = @_;
5546 $tz =~ s/(\d\d)$//;
5547 return ($1 * 60) + ($tz * 3600);
5548}
5549
f8c9d1d2
EW
5550sub get_author_info {
5551 my ($dest, $author, $t, $tz) = @_;
5552 $author =~ s/(?:^\s*|\s*$)//g;
5553 $dest->{a_raw} = $author;
5554 my $au;
1c8443b0 5555 if ($::_authors) {
f8c9d1d2
EW
5556 $au = $rusers{$author} || undef;
5557 }
5558 if (!$au) {
5559 ($au) = ($author =~ /<([^>]+)\@[^>]+>$/);
5560 }
5561 $dest->{t} = $t;
5562 $dest->{tz} = $tz;
5563 $dest->{a} = $au;
b2b3ada7 5564 $dest->{t_utc} = parse_git_date($t, $tz);
f8c9d1d2
EW
5565}
5566
5567sub process_commit {
5568 my ($c, $r_min, $r_max, $defer) = @_;
5569 if (defined $r_min && defined $r_max) {
5570 if ($r_min == $c->{r} && $r_min == $r_max) {
5571 show_commit($c);
5572 return 0;
5573 }
5574 return 1 if $r_min == $r_max;
5575 if ($r_min < $r_max) {
5576 # we need to reverse the print order
5577 return 0 if (defined $limit && --$limit < 0);
5578 push @$defer, $c;
5579 return 1;
5580 }
5581 if ($r_min != $r_max) {
5582 return 1 if ($r_min < $c->{r});
5583 return 1 if ($r_max > $c->{r});
5584 }
5585 }
5586 return 0 if (defined $limit && --$limit < 0);
5587 show_commit($c);
5588 return 1;
5589}
5590
5591sub show_commit {
5592 my $c = shift;
5593 if ($oneline) {
5594 my $x = "\n";
5595 if (my $l = $c->{l}) {
5596 while ($l->[0] =~ /^\s*$/) { shift @$l }
5597 $x = $l->[0];
5598 }
5599 $l_fmt ||= 'A' . length($c->{r});
5600 print 'r',pack($l_fmt, $c->{r}),' | ';
5601 print "$c->{c} | " if $show_commit;
5602 print $x;
5603 } else {
5604 show_commit_normal($c);
5605 }
5606}
5607
5608sub show_commit_changed_paths {
5609 my ($c) = @_;
5610 return unless $c->{changed};
5611 print "Changed paths:\n", @{$c->{changed}};
5612}
5613
5614sub show_commit_normal {
5615 my ($c) = @_;
111947ef 5616 print commit_log_separator, "r$c->{r} | ";
f8c9d1d2 5617 print "$c->{c} | " if $show_commit;
b2b3ada7 5618 print "$c->{a} | ", format_svn_date($c->{t_utc}), ' | ';
f8c9d1d2
EW
5619 my $nr_line = 0;
5620
5621 if (my $l = $c->{l}) {
5622 while ($l->[$#$l] eq "\n" && $#$l > 0
5623 && $l->[($#$l - 1)] eq "\n") {
5624 pop @$l;
5625 }
5626 $nr_line = scalar @$l;
5627 if (!$nr_line) {
5628 print "1 line\n\n\n";
5629 } else {
5630 if ($nr_line == 1) {
5631 $nr_line = '1 line';
5632 } else {
5633 $nr_line .= ' lines';
5634 }
5635 print $nr_line, "\n";
5636 show_commit_changed_paths($c);
5637 print "\n";
5638 print $_ foreach @$l;
5639 }
5640 } else {
5641 print "1 line\n";
5642 show_commit_changed_paths($c);
5643 print "\n";
5644
5645 }
488a63ec 5646 foreach my $x (qw/raw stat diff/) {
f8c9d1d2
EW
5647 if ($c->{$x}) {
5648 print "\n";
5649 print $_ foreach @{$c->{$x}}
5650 }
5651 }
5652}
5653
5654sub cmd_show_log {
5655 my (@args) = @_;
5656 my ($r_min, $r_max);
5657 my $r_last = -1; # prevent dupes
b2b3ada7 5658 set_local_timezone();
f8c9d1d2
EW
5659 if (defined $::_revision) {
5660 if ($::_revision =~ /^(\d+):(\d+)$/) {
5661 ($r_min, $r_max) = ($1, $2);
5662 } elsif ($::_revision =~ /^\d+$/) {
5663 $r_min = $r_max = $::_revision;
5664 } else {
5665 ::fatal "-r$::_revision is not supported, use ",
207f1a75 5666 "standard 'git log' arguments instead";
f8c9d1d2
EW
5667 }
5668 }
5669
5670 config_pager();
6ed77266 5671 @args = git_svn_log_cmd($r_min, $r_max, @args);
111947ef
DK
5672 if (!@args) {
5673 print commit_log_separator unless $incremental || $oneline;
5674 return;
5675 }
f8c9d1d2
EW
5676 my $log = command_output_pipe(@args);
5677 run_pager();
488a63ec 5678 my (@k, $c, $d, $stat);
f8c9d1d2
EW
5679 my $esc_color = qr/(?:\033\[(?:(?:\d+;)*\d*)?m)*/;
5680 while (<$log>) {
9963e025 5681 if (/^${esc_color}commit (?:- )?($::sha1_short)/o) {
f8c9d1d2
EW
5682 my $cmt = $1;
5683 if ($c && cmt_showable($c) && $c->{r} != $r_last) {
5684 $r_last = $c->{r};
5685 process_commit($c, $r_min, $r_max, \@k) or
5686 goto out;
5687 }
5688 $d = undef;
5689 $c = { c => $cmt };
5690 } elsif (/^${esc_color}author (.+) (\d+) ([\-\+]?\d+)$/o) {
5691 get_author_info($c, $1, $2, $3);
5692 } elsif (/^${esc_color}(?:tree|parent|committer) /o) {
5693 # ignore
5694 } elsif (/^${esc_color}:\d{6} \d{6} $::sha1_short/o) {
5695 push @{$c->{raw}}, $_;
5696 } elsif (/^${esc_color}[ACRMDT]\t/) {
5697 # we could add $SVN->{svn_path} here, but that requires
5698 # remote access at the moment (repo_path_split)...
5699 s#^(${esc_color})([ACRMDT])\t#$1 $2 #o;
5700 push @{$c->{changed}}, $_;
5701 } elsif (/^${esc_color}diff /o) {
5702 $d = 1;
5703 push @{$c->{diff}}, $_;
5704 } elsif ($d) {
5705 push @{$c->{diff}}, $_;
488a63ec
EW
5706 } elsif (/^\ .+\ \|\s*\d+\ $esc_color[\+\-]*
5707 $esc_color*[\+\-]*$esc_color$/x) {
5708 $stat = 1;
5709 push @{$c->{stat}}, $_;
5710 } elsif ($stat && /^ \d+ files changed, \d+ insertions/) {
5711 push @{$c->{stat}}, $_;
5712 $stat = undef;
f8c9d1d2
EW
5713 } elsif (/^${esc_color} (git-svn-id:.+)$/o) {
5714 ($c->{url}, $c->{r}, undef) = ::extract_metadata($1);
5715 } elsif (s/^${esc_color} //o) {
5716 push @{$c->{l}}, $_;
5717 }
5718 }
5719 if ($c && defined $c->{r} && $c->{r} != $r_last) {
5720 $r_last = $c->{r};
5721 process_commit($c, $r_min, $r_max, \@k);
5722 }
5723 if (@k) {
111947ef 5724 ($r_min, $r_max) = ($r_max, $r_min);
f8c9d1d2
EW
5725 process_commit($_, $r_min, $r_max) foreach reverse @k;
5726 }
5727out:
c843c464 5728 close $log;
111947ef 5729 print commit_log_separator unless $incremental || $oneline;
f8c9d1d2
EW
5730}
5731
6fb5375e 5732sub cmd_blame {
4be40381 5733 my $path = pop;
6fb5375e
TS
5734
5735 config_pager();
5736 run_pager();
5737
4be40381
SG
5738 my ($fh, $ctx, $rev);
5739
5740 if ($_git_format) {
5741 ($fh, $ctx) = command_output_pipe('blame', @_, $path);
5742 while (my $line = <$fh>) {
5743 if ($line =~ /^\^?([[:xdigit:]]+)\s/) {
5744 # Uncommitted edits show up as a rev ID of
5745 # all zeros, which we can't look up with
5746 # cmt_metadata
5747 if ($1 !~ /^0+$/) {
5748 (undef, $rev, undef) =
5749 ::cmt_metadata($1);
5750 $rev = '0' if (!$rev);
5751 } else {
5752 $rev = '0';
5753 }
5754 $rev = sprintf('%-10s', $rev);
5755 $line =~ s/^\^?[[:xdigit:]]+(\s)/$rev$1/;
5756 }
5757 print $line;
5758 }
5759 } else {
5760 ($fh, $ctx) = command_output_pipe('blame', '-p', @_, 'HEAD',
5761 '--', $path);
5762 my ($sha1);
5763 my %authors;
6ea42032
BB
5764 my @buffer;
5765 my %dsha; #distinct sha keys
5766
4be40381 5767 while (my $line = <$fh>) {
6ea42032
BB
5768 push @buffer, $line;
5769 if ($line =~ /^([[:xdigit:]]{40})\s\d+\s\d+/) {
5770 $dsha{$1} = 1;
5771 }
5772 }
5773
5774 my $s2r = ::cmt_sha2rev_batch([keys %dsha]);
5775
5776 foreach my $line (@buffer) {
4be40381 5777 if ($line =~ /^([[:xdigit:]]{40})\s\d+\s\d+/) {
6ea42032
BB
5778 $rev = $s2r->{$1};
5779 $rev = '0' if (!$rev)
4be40381
SG
5780 }
5781 elsif ($line =~ /^author (.*)/) {
5782 $authors{$rev} = $1;
5783 $authors{$rev} =~ s/\s/_/g;
5784 }
5785 elsif ($line =~ /^\t(.*)$/) {
5786 printf("%6s %10s %s\n", $rev, $authors{$rev}, $1);
5787 }
6fb5375e 5788 }
6fb5375e
TS
5789 }
5790 command_close_pipe($fh, $ctx);
5791}
5792
706587fc
EW
5793package Git::SVN::Migration;
5794# these version numbers do NOT correspond to actual version numbers
5795# of git nor git-svn. They are just relative.
5796#
5797# v0 layout: .git/$id/info/url, refs/heads/$id-HEAD
5798#
5799# v1 layout: .git/$id/info/url, refs/remotes/$id
5800#
5801# v2 layout: .git/svn/$id/info/url, refs/remotes/$id
5802#
5803# v3 layout: .git/svn/$id, refs/remotes/$id
5804# - info/url may remain for backwards compatibility
5805# - this is what we migrate up to this layout automatically,
5806# - this will be used by git svn init on single branches
26a62d57
EW
5807# v3.1 layout (auto migrated):
5808# - .rev_db => .rev_db.$UUID, .rev_db will remain as a symlink
5809# for backwards compatibility
706587fc
EW
5810#
5811# v4 layout: .git/svn/$repo_id/$id, refs/remotes/$repo_id/$id
5812# - this is only created for newly multi-init-ed
5813# repositories. Similar in spirit to the
5814# --use-separate-remotes option in git-clone (now default)
5815# - we do not automatically migrate to this (following
5816# the example set by core git)
060610c5
EW
5817#
5818# v5 layout: .rev_db.$UUID => .rev_map.$UUID
5819# - newer, more-efficient format that uses 24-bytes per record
5820# with no filler space.
5821# - use xxd -c24 < .rev_map.$UUID to view and debug
5822# - This is a one-way migration, repositories updated to the
5823# new format will not be able to use old git-svn without
5824# rebuilding the .rev_db. Rebuilding the rev_db is not
5825# possible if noMetadata or useSvmProps are set; but should
5826# be no problem for users that use the (sensible) defaults.
706587fc
EW
5827use strict;
5828use warnings;
5829use Carp qw/croak/;
5830use File::Path qw/mkpath/;
47e39c55
EW
5831use File::Basename qw/dirname basename/;
5832use vars qw/$_minimize/;
706587fc
EW
5833
5834sub migrate_from_v0 {
5835 my $git_dir = $ENV{GIT_DIR};
5836 return undef unless -d $git_dir;
5837 my ($fh, $ctx) = command_output_pipe(qw/rev-parse --symbolic --all/);
5838 my $migrated = 0;
5839 while (<$fh>) {
5840 chomp;
5841 my ($id, $orig_ref) = ($_, $_);
5842 next unless $id =~ s#^refs/heads/(.+)-HEAD$#$1#;
5843 next unless -f "$git_dir/$id/info/url";
5844 my $new_ref = "refs/remotes/$id";
5845 if (::verify_ref("$new_ref^0")) {
5846 print STDERR "W: $orig_ref is probably an old ",
5847 "branch used by an ancient version of ",
5848 "git-svn.\n",
5849 "However, $new_ref also exists.\n",
5850 "We will not be able ",
5851 "to use this branch until this ",
5852 "ambiguity is resolved.\n";
5853 next;
5854 }
5855 print STDERR "Migrating from v0 layout...\n" if !$migrated;
5856 print STDERR "Renaming ref: $orig_ref => $new_ref\n";
5857 command_noisy('update-ref', $new_ref, $orig_ref);
5858 command_noisy('update-ref', '-d', $orig_ref, $orig_ref);
5859 $migrated++;
5860 }
5861 command_close_pipe($fh, $ctx);
5862 print STDERR "Done migrating from v0 layout...\n" if $migrated;
5863 $migrated;
5864}
5865
5866sub migrate_from_v1 {
5867 my $git_dir = $ENV{GIT_DIR};
5868 my $migrated = 0;
5869 return $migrated unless -d $git_dir;
5870 my $svn_dir = "$git_dir/svn";
5871
5872 # just in case somebody used 'svn' as their $id at some point...
5873 return $migrated if -d $svn_dir && ! -f "$svn_dir/info/url";
5874
5875 print STDERR "Migrating from a git-svn v1 layout...\n";
5876 mkpath([$svn_dir]);
5877 print STDERR "Data from a previous version of git-svn exists, but\n\t",
5878 "$svn_dir\n\t(required for this version ",
8f510bef 5879 "($::VERSION) of git-svn) does not exist.\n";
706587fc
EW
5880 my ($fh, $ctx) = command_output_pipe(qw/rev-parse --symbolic --all/);
5881 while (<$fh>) {
5882 my $x = $_;
5883 next unless $x =~ s#^refs/remotes/##;
5884 chomp $x;
5885 next unless -f "$git_dir/$x/info/url";
5886 my $u = eval { ::file_to_s("$git_dir/$x/info/url") };
5887 next unless $u;
5888 my $dn = dirname("$git_dir/svn/$x");
5889 mkpath([$dn]) unless -d $dn;
5890 if ($x eq 'svn') { # they used 'svn' as GIT_SVN_ID:
5891 mkpath(["$git_dir/svn/svn"]);
5892 print STDERR " - $git_dir/$x/info => ",
5893 "$git_dir/svn/$x/info\n";
5894 rename "$git_dir/$x/info", "$git_dir/svn/$x/info" or
5895 croak "$!: $x";
5896 # don't worry too much about these, they probably
5897 # don't exist with repos this old (save for index,
5898 # and we can easily regenerate that)
5899 foreach my $f (qw/unhandled.log index .rev_db/) {
5900 rename "$git_dir/$x/$f", "$git_dir/svn/$x/$f";
5901 }
5902 } else {
5903 print STDERR " - $git_dir/$x => $git_dir/svn/$x\n";
5904 rename "$git_dir/$x", "$git_dir/svn/$x" or
5905 croak "$!: $x";
5906 }
5907 $migrated++;
5908 }
5909 command_close_pipe($fh, $ctx);
5910 print STDERR "Done migrating from a git-svn v1 layout\n";
5911 $migrated;
5912}
5913
5914sub read_old_urls {
5915 my ($l_map, $pfx, $path) = @_;
5916 my @dir;
5917 foreach (<$path/*>) {
5918 if (-r "$_/info/url") {
5919 $pfx .= '/' if $pfx && $pfx !~ m!/$!;
5920 my $ref_id = $pfx . basename $_;
5921 my $url = ::file_to_s("$_/info/url");
5922 $l_map->{$ref_id} = $url;
5923 } elsif (-d $_) {
5924 push @dir, $_;
5925 }
5926 }
5927 foreach (@dir) {
5928 my $x = $_;
5929 $x =~ s!^\Q$ENV{GIT_DIR}\E/svn/!!o;
5930 read_old_urls($l_map, $x, $_);
5931 }
5932}
5933
5934sub migrate_from_v2 {
5935 my @cfg = command(qw/config -l/);
5936 return if grep /^svn-remote\..+\.url=/, @cfg;
5937 my %l_map;
5938 read_old_urls(\%l_map, '', "$ENV{GIT_DIR}/svn");
5939 my $migrated = 0;
5940
5941 foreach my $ref_id (sort keys %l_map) {
471bc000
EW
5942 eval { Git::SVN->init($l_map{$ref_id}, '', undef, $ref_id) };
5943 if ($@) {
5944 Git::SVN->init($l_map{$ref_id}, '', $ref_id, $ref_id);
5945 }
706587fc
EW
5946 $migrated++;
5947 }
5948 $migrated;
5949}
5950
47e39c55
EW
5951sub minimize_connections {
5952 my $r = Git::SVN::read_all_remotes();
5953 my $new_urls = {};
5954 my $root_repos = {};
5955 foreach my $repo_id (keys %$r) {
5956 my $url = $r->{$repo_id}->{url} or next;
5957 my $fetch = $r->{$repo_id}->{fetch} or next;
5958 my $ra = Git::SVN::Ra->new($url);
5959
5960 # skip existing cases where we already connect to the root
5961 if (($ra->{url} eq $ra->{repos_root}) ||
7829f20f 5962 ($ra->{repos_root} eq $repo_id)) {
47e39c55
EW
5963 $root_repos->{$ra->{url}} = $repo_id;
5964 next;
5965 }
5966
5967 my $root_ra = Git::SVN::Ra->new($ra->{repos_root});
5968 my $root_path = $ra->{url};
4e9f6cc7 5969 $root_path =~ s#^\Q$ra->{repos_root}\E(/|$)##;
47e39c55
EW
5970 foreach my $path (keys %$fetch) {
5971 my $ref_id = $fetch->{$path};
5972 my $gs = Git::SVN->new($ref_id, $repo_id, $path);
5973
5974 # make sure we can read when connecting to
5975 # a higher level of a repository
5976 my ($last_rev, undef) = $gs->last_rev_commit;
5977 if (!defined $last_rev) {
5978 $last_rev = eval {
5979 $root_ra->get_latest_revnum;
5980 };
5981 next if $@;
5982 }
5983 my $new = $root_path;
5984 $new .= length $path ? "/$path" : '';
5985 eval {
5986 $root_ra->get_log([$new], $last_rev, $last_rev,
5987 0, 0, 1, sub { });
5988 };
5989 next if $@;
5990 $new_urls->{$ra->{repos_root}}->{$new} =
5991 { ref_id => $ref_id,
5992 old_repo_id => $repo_id,
5993 old_path => $path };
5994 }
5995 }
5996
5997 my @emptied;
5998 foreach my $url (keys %$new_urls) {
5999 # see if we can re-use an existing [svn-remote "repo_id"]
6000 # instead of creating a(n ugly) new section:
7829f20f 6001 my $repo_id = $root_repos->{$url} || $url;
47e39c55
EW
6002
6003 my $fetch = $new_urls->{$url};
6004 foreach my $path (keys %$fetch) {
6005 my $x = $fetch->{$path};
6006 Git::SVN->init($url, $path, $repo_id, $x->{ref_id});
6007 my $pfx = "svn-remote.$x->{old_repo_id}";
6008
6009 my $old_fetch = quotemeta("$x->{old_path}:".
6f5748e1 6010 "$x->{ref_id}");
8b8fc068 6011 command_noisy(qw/config --unset/,
47e39c55
EW
6012 "$pfx.fetch", '^'. $old_fetch . '$');
6013 delete $r->{$x->{old_repo_id}}->
6014 {fetch}->{$x->{old_path}};
6015 if (!keys %{$r->{$x->{old_repo_id}}->{fetch}}) {
8b8fc068 6016 command_noisy(qw/config --unset/,
47e39c55
EW
6017 "$pfx.url");
6018 push @emptied, $x->{old_repo_id}
6019 }
6020 }
6021 }
6022 if (@emptied) {
8befc50c 6023 my $file = $ENV{GIT_CONFIG} || "$ENV{GIT_DIR}/config";
47e39c55
EW
6024 print STDERR <<EOF;
6025The following [svn-remote] sections in your config file ($file) are empty
6026and can be safely removed:
6027EOF
6028 print STDERR "[svn-remote \"$_\"]\n" foreach @emptied;
6029 }
6030}
6031
706587fc
EW
6032sub migration_check {
6033 migrate_from_v0();
6034 migrate_from_v1();
6035 migrate_from_v2();
47e39c55 6036 minimize_connections() if $_minimize;
706587fc
EW
6037}
6038
ef3cfaad
EW
6039package Git::IndexInfo;
6040use strict;
6041use warnings;
6042use Git qw/command_input_pipe command_close_pipe/;
6043
6044sub new {
6045 my ($class) = @_;
6046 my ($gui, $ctx) = command_input_pipe(qw/update-index -z --index-info/);
6047 bless { gui => $gui, ctx => $ctx, nr => 0}, $class;
6048}
6049
6050sub remove {
6051 my ($self, $path) = @_;
6052 if (print { $self->{gui} } '0 ', 0 x 40, "\t", $path, "\0") {
6053 return ++$self->{nr};
6054 }
6055 undef;
6056}
6057
6058sub update {
6059 my ($self, $mode, $hash, $path) = @_;
6060 if (print { $self->{gui} } $mode, ' ', $hash, "\t", $path, "\0") {
6061 return ++$self->{nr};
6062 }
6063 undef;
6064}
6065
6066sub DESTROY {
6067 my ($self) = @_;
6068 command_close_pipe($self->{gui}, $self->{ctx});
6069}
6070
4bb9ed04
EW
6071package Git::SVN::GlobSpec;
6072use strict;
6073use warnings;
6074
6075sub new {
07576208 6076 my ($class, $glob, $pattern_ok) = @_;
4bb9ed04
EW
6077 my $re = $glob;
6078 $re =~ s!/+$!!g; # no need for trailing slashes
07576208
JS
6079 my (@left, @right, @patterns);
6080 my $state = "left";
6081 my $die_msg = "Only one set of wildcard directories " .
6082 "(e.g. '*' or '*/*/*') is supported: '$glob'\n";
6083 for my $part (split(m|/|, $glob)) {
6084 if ($part =~ /\*/ && $part ne "*") {
6085 die "Invalid pattern in '$glob': $part\n";
6086 } elsif ($pattern_ok && $part =~ /[{}]/ &&
6087 $part !~ /^\{[^{}]+\}/) {
6088 die "Invalid pattern in '$glob': $part\n";
6089 }
6090 if ($part eq "*") {
6091 die $die_msg if $state eq "right";
6092 $state = "pattern";
6093 push(@patterns, "[^/]*");
6094 } elsif ($pattern_ok && $part =~ /^\{(.*)\}$/) {
6095 die $die_msg if $state eq "right";
6096 $state = "pattern";
6097 my $p = quotemeta($1);
6098 $p =~ s/\\,/|/g;
6099 push(@patterns, "(?:$p)");
6100 } else {
6101 if ($state eq "left") {
6102 push(@left, $part);
6103 } else {
6104 push(@right, $part);
6105 $state = "right";
6106 }
6107 }
570d35c2 6108 }
07576208 6109 my $depth = @patterns;
570d35c2 6110 if ($depth == 0) {
07576208 6111 die "One '*' is needed in glob: '$glob'\n";
4e9f6cc7 6112 }
07576208
JS
6113 my $left = join('/', @left);
6114 my $right = join('/', @right);
6115 $re = join('/', @patterns);
6116 $re = join('\/',
6117 grep(length, quotemeta($left), "($re)", quotemeta($right)));
74a81227
EW
6118 my $left_re = qr/^\/\Q$left\E(\/|$)/;
6119 bless { left => $left, right => $right, left_regex => $left_re,
570d35c2 6120 regex => qr/$re/, glob => $glob, depth => $depth }, $class;
4bb9ed04
EW
6121}
6122
6123sub full_path {
6124 my ($self, $path) = @_;
6125 return (length $self->{left} ? "$self->{left}/" : '') .
6126 $path . (length $self->{right} ? "/$self->{right}" : '');
6127}
6128
3397f9df
EW
6129__END__
6130
6131Data structures:
6132
4bb9ed04
EW
6133
6134$remotes = { # returned by read_all_remotes()
6135 'svn' => {
6136 # svn-remote.svn.url=https://svn.musicpd.org
6137 url => 'https://svn.musicpd.org',
6138 # svn-remote.svn.fetch=mpd/trunk:trunk
6139 fetch => {
6140 'mpd/trunk' => 'trunk',
6141 },
6142 # svn-remote.svn.tags=mpd/tags/*:tags/*
6143 tags => {
6144 path => {
6145 left => 'mpd/tags',
6146 right => '',
6147 regex => qr!mpd/tags/([^/]+)$!,
6148 glob => 'tags/*',
6149 },
6150 ref => {
6151 left => 'tags',
6152 right => '',
6153 regex => qr!tags/([^/]+)$!,
6154 glob => 'tags/*',
6155 },
6156 }
6157 }
6158};
6159
44320b9e 6160$log_entry hashref as returned by libsvn_log_entry()
3397f9df 6161{
44320b9e 6162 log => 'whitespace-formatted log entry
3397f9df
EW
6163', # trailing newline is preserved
6164 revision => '8', # integer
6165 date => '2004-02-24T17:01:44.108345Z', # commit date
6166 author => 'committer name'
6167};
6168
6e8548cc
EW
6169
6170# this is generated by generate_diff();
3397f9df
EW
6171@mods = array of diff-index line hashes, each element represents one line
6172 of diff-index output
6173
6174diff-index line ($m hash)
6175{
6176 mode_a => first column of diff-index output, no leading ':',
6177 mode_b => second column of diff-index output,
6178 sha1_b => sha1sum of the final blob,
ac8e0b91 6179 chg => change type [MCRADT],
3397f9df
EW
6180 file_a => original file name of a file (iff chg is 'C' or 'R')
6181 file_b => new/current file name of a file (any chg)
6182}
6183;
a5e0cedc 6184
a00439ac
EW
6185# retval of read_url_paths{,_all}();
6186$l_map = {
6187 # repository root url
6188 'https://svn.musicpd.org' => {
6189 # repository path # GIT_SVN_ID
6190 'mpd/trunk' => 'trunk',
6191 'mpd/tags/0.11.5' => 'tags/0.11.5',
6192 },
6193}
6194
a5e0cedc
EW
6195Notes:
6196 I don't trust the each() function on unless I created %hash myself
6197 because the internal iterator may not have started at base.