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