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