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