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