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