]> git.ipfire.org Git - thirdparty/git.git/blame - git-svn.perl
introduce GIT_WORK_TREE to specify the work tree
[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
9760adcc
EW
7 $sha1 $sha1_short $_revision
8 $_q $_authors %users/;
3397f9df 9$AUTHOR = 'Eric Wong <normalperson@yhbt.net>';
60d02ccc 10$VERSION = '@@GIT_VERSION@@';
13ccd6d4 11
5253dc33 12my $git_dir_user_set = 1 if defined $ENV{GIT_DIR};
706587fc 13$ENV{GIT_DIR} ||= '.git';
9fa00b65 14$Git::SVN::default_repo_id = 'svn';
8b8fc068 15$Git::SVN::default_ref_id = $ENV{GIT_SVN_ID} || 'git-svn';
6af1db44 16$Git::SVN::Ra::_log_window_size = 100;
13ccd6d4 17
f8c9d1d2 18$Git::SVN::Log::TZ = $ENV{TZ};
3397f9df 19$ENV{TZ} = 'UTC';
a00439ac 20$| = 1; # unbuffer STDOUT
3397f9df 21
6fda05ae 22sub fatal (@) { print STDERR @_; exit 1 }
b9c85187
EW
23require SVN::Core; # use()-ing this causes segfaults for me... *shrug*
24require SVN::Ra;
25require SVN::Delta;
26if ($SVN::Core::VERSION lt '1.1.0') {
27 fatal "Need SVN::Core 1.1.0 or better (got $SVN::Core::VERSION)\n";
28}
d81bf827 29push @Git::SVN::Ra::ISA, 'SVN::Ra';
b9c85187
EW
30push @SVN::Git::Editor::ISA, 'SVN::Delta::Editor';
31push @SVN::Git::Fetcher::ISA, 'SVN::Delta::Editor';
3397f9df
EW
32use Carp qw/croak/;
33use IO::File qw//;
34use File::Basename qw/dirname basename/;
35use File::Path qw/mkpath/;
512b620b 36use Getopt::Long qw/:config gnu_getopt no_ignore_case auto_abbrev/;
968bdf1f 37use IPC::Open3;
336f1714 38use Git;
a5e0cedc 39
336f1714
EW
40BEGIN {
41 my $s;
42 foreach (qw/command command_oneline command_noisy command_output_pipe
43 command_input_pipe command_close_pipe/) {
44 $s .= "*SVN::Git::Editor::$_ = *SVN::Git::Fetcher::$_ = ".
706587fc 45 "*Git::SVN::Migration::$_ = ".
f8c9d1d2 46 "*Git::SVN::Log::$_ = *Git::SVN::$_ = *$_ = *Git::$_; ";
336f1714
EW
47 }
48 eval $s;
49}
50
b9c85187 51my ($SVN);
83e9940a 52
f8c9d1d2
EW
53$sha1 = qr/[a-f\d]{40}/;
54$sha1_short = qr/[a-f\d]{4,40}/;
44320b9e 55my ($_stdin, $_help, $_edit,
9760adcc 56 $_message, $_file,
d05d72e0 57 $_template, $_shared,
171af110 58 $_version, $_fetch_all, $_no_rebase,
dee41f3e 59 $_merge, $_strategy, $_dry_run, $_local,
905f8b7d 60 $_prefix, $_no_checkout, $_verbose);
0bed5eaa 61$Git::SVN::_follow_parent = 1;
706587fc
EW
62my %remote_opts = ( 'username=s' => \$Git::SVN::Prompt::_username,
63 'config-dir=s' => \$Git::SVN::Ra::config_dir,
64 'no-auth-cache' => \$Git::SVN::Prompt::_no_auth_cache );
0bed5eaa 65my %fc_opts = ( 'follow-parent|follow!' => \$Git::SVN::_follow_parent,
dc5869c0 66 'authors-file|A=s' => \$_authors,
ecc712dd 67 'repack:i' => \$Git::SVN::_repack,
97ae0911
EW
68 'noMetadata' => \$Git::SVN::_no_metadata,
69 'useSvmProps' => \$Git::SVN::_use_svm_props,
62e349d2 70 'useSvnsyncProps' => \$Git::SVN::_use_svnsync_props,
6af1db44 71 'log-window-size=i' => \$Git::SVN::Ra::_log_window_size,
1e889ef3 72 'no-checkout' => \$_no_checkout,
80f50749 73 'quiet|q' => \$_q,
ecc712dd
EW
74 'repack-flags|repack-args|repack-opts=s' =>
75 \$Git::SVN::_repack_flags,
706587fc 76 %remote_opts );
36f5b1f0 77
9d55b41a 78my ($_trunk, $_tags, $_branches);
0dfaf0a4 79my %icv;
dadc6d2a
EW
80my %init_opts = ( 'template=s' => \$_template, 'shared:s' => \$_shared,
81 'trunk|T=s' => \$_trunk, 'tags|t=s' => \$_tags,
82 'branches|b=s' => \$_branches, 'prefix=s' => \$_prefix,
4a1bb4c3 83 'minimize-url|m' => \$Git::SVN::_minimize_url,
0dfaf0a4
EW
84 'no-metadata' => sub { $icv{noMetadata} = 1 },
85 'use-svm-props' => sub { $icv{useSvmProps} = 1 },
86 'use-svnsync-props' => sub { $icv{useSvnsyncProps} = 1 },
87 'rewrite-root=s' => sub { $icv{rewriteRoot} = $_[1] },
dadc6d2a 88 %remote_opts );
27e9fb8d 89my %cmt_opts = ( 'edit|e' => \$_edit,
24e22aa8
EW
90 'rmdir' => \$SVN::Git::Editor::_rmdir,
91 'find-copies-harder' => \$SVN::Git::Editor::_find_copies_harder,
92 'l=i' => \$SVN::Git::Editor::_rename_limit,
93 'copy-similarity|C=i'=> \$SVN::Git::Editor::_cp_similarity
27e9fb8d 94);
9d55b41a 95
3397f9df 96my %cmd = (
2a3240be 97 fetch => [ \&cmd_fetch, "Download new revisions from SVN",
e98671e5 98 { 'revision|r=s' => \$_revision,
905f8b7d 99 'fetch-all|all' => \$_fetch_all,
e98671e5 100 %fc_opts } ],
0425ea90
EW
101 clone => [ \&cmd_clone, "Initialize and fetch revisions",
102 { 'revision|r=s' => \$_revision,
103 %fc_opts, %init_opts } ],
d2866f9e 104 init => [ \&cmd_init, "Initialize a repo for tracking" .
f8ab6b73 105 " (requires URL argument)",
9d55b41a 106 \%init_opts ],
dadc6d2a
EW
107 'multi-init' => [ \&cmd_multi_init,
108 "Deprecated alias for ".
109 "'$0 init -T<trunk> -b<branches> -t<tags>'",
110 \%init_opts ],
d7ad3bed
EW
111 dcommit => [ \&cmd_dcommit,
112 'Commit several diffs to merge with upstream',
3289e86e
EW
113 { 'merge|m|M' => \$_merge,
114 'strategy|s=s' => \$_strategy,
905f8b7d 115 'verbose|v' => \$_verbose,
3289e86e 116 'dry-run|n' => \$_dry_run,
905f8b7d 117 'fetch-all|all' => \$_fetch_all,
171af110 118 'no-rebase' => \$_no_rebase,
4b155223 119 %cmt_opts, %fc_opts } ],
1ce255dc
EW
120 'set-tree' => [ \&cmd_set_tree,
121 "Set an SVN repository to a git tree-ish",
122 { 'stdin|' => \$_stdin, %cmt_opts, %fc_opts, } ],
5969cbe1 123 'show-ignore' => [ \&cmd_show_ignore, "Show svn:ignore listings",
a5e0cedc 124 { 'revision|r=i' => \$_revision } ],
1c8443b0 125 'multi-fetch' => [ \&cmd_multi_fetch,
e98671e5
EW
126 "Deprecated alias for $0 fetch --all",
127 { 'revision|r=s' => \$_revision, %fc_opts } ],
706587fc
EW
128 'migrate' => [ sub { },
129 # no-op, we automatically run this anyways,
706587fc
EW
130 'Migrate configuration/metadata/layout from
131 previous versions of git-svn',
a836a0e1
EW
132 { 'minimize' => \$Git::SVN::Migration::_minimize,
133 %remote_opts } ],
f8c9d1d2
EW
134 'log' => [ \&Git::SVN::Log::cmd_show_log, 'Show commit logs',
135 { 'limit=i' => \$Git::SVN::Log::limit,
79bb8d88 136 'revision|r=s' => \$_revision,
f8c9d1d2
EW
137 'verbose|v' => \$Git::SVN::Log::verbose,
138 'incremental' => \$Git::SVN::Log::incremental,
139 'oneline' => \$Git::SVN::Log::oneline,
140 'show-commit' => \$Git::SVN::Log::show_commit,
141 'non-recursive' => \$Git::SVN::Log::non_recursive,
79bb8d88 142 'authors-file|A=s' => \$_authors,
f8c9d1d2
EW
143 'color' => \$Git::SVN::Log::color,
144 'pager=s' => \$Git::SVN::Log::pager,
79bb8d88 145 } ],
26e60160
AR
146 'find-rev' => [ \&cmd_find_rev, "Translate between SVN revision numbers and tree-ish",
147 { } ],
905f8b7d
EW
148 'rebase' => [ \&cmd_rebase, "Fetch and rebase your working directory",
149 { 'merge|m|M' => \$_merge,
150 'verbose|v' => \$_verbose,
151 'strategy|s=s' => \$_strategy,
dee41f3e 152 'local|l' => \$_local,
905f8b7d
EW
153 'fetch-all|all' => \$_fetch_all,
154 %fc_opts } ],
44320b9e
EW
155 'commit-diff' => [ \&cmd_commit_diff,
156 'Commit a diff between two trees',
27e9fb8d
EW
157 { 'message|m=s' => \$_message,
158 'file|F=s' => \$_file,
45bf473a 159 'revision|r=s' => \$_revision,
27e9fb8d 160 %cmt_opts } ],
3397f9df 161);
9d55b41a 162
3397f9df
EW
163my $cmd;
164for (my $i = 0; $i < @ARGV; $i++) {
165 if (defined $cmd{$ARGV[$i]}) {
166 $cmd = $ARGV[$i];
167 splice @ARGV, $i, 1;
168 last;
169 }
170};
171
448c81b4 172my %opts = %{$cmd{$cmd}->[2]} if (defined $cmd);
a9612be2 173
b8c92cad 174read_repo_config(\%opts);
c284914a 175Getopt::Long::Configure('pass_through') if ($cmd && $cmd eq 'log');
9760adcc
EW
176my $rv = GetOptions(%opts, 'help|H|h' => \$_help, 'version|V' => \$_version,
177 'minimize-connections' => \$Git::SVN::Migration::_minimize,
178 'id|i=s' => \$Git::SVN::default_ref_id,
befc9adc
EW
179 'svn-remote|remote|R=s' => sub {
180 $Git::SVN::no_reuse_existing = 1;
181 $Git::SVN::default_repo_id = $_[1] });
c284914a 182exit 1 if (!$rv && $cmd && $cmd ne 'log');
6f0783cf 183
3397f9df 184usage(0) if $_help;
551ce28f 185version() if $_version;
eeb0abe0
EW
186usage(1) unless defined $cmd;
187load_authors() if $_authors;
5253dc33
EW
188
189# make sure we're always running
190unless ($cmd =~ /(?:clone|init|multi-init)$/) {
191 unless (-d $ENV{GIT_DIR}) {
192 if ($git_dir_user_set) {
193 die "GIT_DIR=$ENV{GIT_DIR} explicitly set, ",
194 "but it is not a directory\n";
195 }
196 my $git_dir = delete $ENV{GIT_DIR};
197 chomp(my $cdup = command_oneline(qw/rev-parse --show-cdup/));
198 unless (length $cdup) {
199 die "Already at toplevel, but $git_dir ",
200 "not found '$cdup'\n";
201 }
202 chdir $cdup or die "Unable to chdir up to '$cdup'\n";
203 unless (-d $git_dir) {
204 die "$git_dir still not found after going to ",
205 "'$cdup'\n";
206 }
207 $ENV{GIT_DIR} = $git_dir;
208 }
209}
0425ea90 210unless ($cmd =~ /^(?:clone|init|multi-init|commit-diff)$/) {
706587fc
EW
211 Git::SVN::Migration::migration_check();
212}
ecc712dd 213Git::SVN::init_vars();
b805b44a
EW
214eval {
215 Git::SVN::verify_remotes_sanity();
216 $cmd{$cmd}->[0]->(@ARGV);
217};
218fatal $@ if $@;
1e889ef3 219post_fetch_checkout();
3397f9df
EW
220exit 0;
221
222####################### primary functions ######################
223sub usage {
224 my $exit = shift || 0;
225 my $fd = $exit ? \*STDERR : \*STDOUT;
226 print $fd <<"";
227git-svn - bidirectional operations between a single Subversion tree and git
228Usage: $0 <command> [options] [arguments]\n
448c81b4
EW
229
230 print $fd "Available commands:\n" unless $cmd;
3397f9df
EW
231
232 foreach (sort keys %cmd) {
448c81b4 233 next if $cmd && $cmd ne $_;
a836a0e1 234 next if /^multi-/; # don't show deprecated commands
b203b769 235 print $fd ' ',pack('A17',$_),$cmd{$_}->[1],"\n";
448c81b4 236 foreach (keys %{$cmd{$_}->[2]}) {
512b620b
EW
237 # mixed-case options are for .git/config only
238 next if /[A-Z]/ && /^[a-z]+$/i;
448c81b4 239 # prints out arguments as they should be passed:
b8c92cad 240 my $x = s#[:=]s$## ? '<arg>' : s#[:=]i$## ? '<num>' : '';
b203b769 241 print $fd ' ' x 21, join(', ', map { length $_ > 1 ?
448c81b4
EW
242 "--$_" : "-$_" }
243 split /\|/,$_)," $x\n";
244 }
3397f9df
EW
245 }
246 print $fd <<"";
448c81b4
EW
247\nGIT_SVN_ID may be set in the environment or via the --id/-i switch to an
248arbitrary identifier if you're tracking multiple SVN branches/repositories in
249one git repository and want to keep them separate. See git-svn(1) for more
250information.
3397f9df
EW
251
252 exit $exit;
253}
254
551ce28f 255sub version {
7d60ab2c 256 print "git-svn version $VERSION (svn $SVN::Core::VERSION)\n";
551ce28f
EW
257 exit 0;
258}
259
8164b652
EW
260sub do_git_init_db {
261 unless (-d $ENV{GIT_DIR}) {
262 my @init_db = ('init');
263 push @init_db, "--template=$_template" if defined $_template;
dadc6d2a
EW
264 if (defined $_shared) {
265 if ($_shared =~ /[a-z]/) {
266 push @init_db, "--shared=$_shared";
267 } else {
268 push @init_db, "--shared";
269 }
270 }
8164b652
EW
271 command_noisy(@init_db);
272 }
0dfaf0a4
EW
273 my $set;
274 my $pfx = "svn-remote.$Git::SVN::default_repo_id";
275 foreach my $i (keys %icv) {
276 die "'$set' and '$i' cannot both be set\n" if $set;
277 next unless defined $icv{$i};
278 command_noisy('config', "$pfx.$i", $icv{$i});
279 $set = $i;
280 }
8164b652
EW
281}
282
dadc6d2a
EW
283sub init_subdir {
284 my $repo_path = shift or return;
285 mkpath([$repo_path]) unless -d $repo_path;
286 chdir $repo_path or die "Couldn't chdir to $repo_path: $!\n";
f30603fc 287 $ENV{GIT_DIR} = '.git';
dadc6d2a
EW
288}
289
0425ea90
EW
290sub cmd_clone {
291 my ($url, $path) = @_;
292 if (!defined $path &&
293 (defined $_trunk || defined $_branches || defined $_tags) &&
294 $url !~ m#^[a-z\+]+://#) {
295 $path = $url;
296 }
0425ea90 297 $path = basename($url) if !defined $path || !length $path;
f30603fc 298 cmd_init($url, $path);
0425ea90
EW
299 Git::SVN::fetch_all($Git::SVN::default_repo_id);
300}
301
d2866f9e 302sub cmd_init {
dadc6d2a
EW
303 if (defined $_trunk || defined $_branches || defined $_tags) {
304 return cmd_multi_init(@_);
03e0ea87 305 }
dadc6d2a
EW
306 my $url = shift or die "SVN repository location required ",
307 "as a command-line argument\n";
308 init_subdir(@_);
8164b652 309 do_git_init_db();
03e0ea87 310
706587fc 311 Git::SVN->init($url);
3397f9df
EW
312}
313
2a3240be 314sub cmd_fetch {
e98671e5
EW
315 if (grep /^\d+=./, @_) {
316 die "'<rev>=<commit>' fetch arguments are ",
317 "no longer supported.\n";
07a1c950 318 }
e98671e5
EW
319 my ($remote) = @_;
320 if (@_ > 1) {
905f8b7d 321 die "Usage: $0 fetch [--all] [svn-remote]\n";
e98671e5
EW
322 }
323 $remote ||= $Git::SVN::default_repo_id;
324 if ($_fetch_all) {
325 cmd_multi_fetch();
326 } else {
327 Git::SVN::fetch_all($remote, Git::SVN::read_all_remotes());
1c8443b0 328 }
2a3240be
EW
329}
330
1ce255dc 331sub cmd_set_tree {
3397f9df
EW
332 my (@commits) = @_;
333 if ($_stdin || !@commits) {
334 print "Reading from stdin...\n";
335 @commits = ();
336 while (<STDIN>) {
1ca72aef 337 if (/\b($sha1_short)\b/o) {
3397f9df
EW
338 unshift @commits, $1;
339 }
340 }
341 }
342 my @revs;
8de010ad 343 foreach my $c (@commits) {
aef4e921 344 my @tmp = command('rev-parse',$c);
8de010ad
EW
345 if (scalar @tmp == 1) {
346 push @revs, $tmp[0];
347 } elsif (scalar @tmp > 1) {
aef4e921 348 push @revs, reverse(command('rev-list',@tmp));
8de010ad 349 } else {
1ce255dc 350 fatal "Failed to rev-parse $c\n";
8de010ad 351 }
3397f9df 352 }
1ce255dc
EW
353 my $gs = Git::SVN->new;
354 my ($r_last, $cmt_last) = $gs->last_rev_commit;
355 $gs->fetch;
97f6987a 356 if (defined $gs->{last_rev} && $r_last != $gs->{last_rev}) {
1ce255dc
EW
357 fatal "There are new revisions that were fetched ",
358 "and need to be merged (or acknowledged) ",
359 "before committing.\nlast rev: $r_last\n",
360 " current: $gs->{last_rev}\n";
a5e0cedc 361 }
1ce255dc
EW
362 $gs->set_tree($_) foreach @revs;
363 print "Done committing ",scalar @revs," revisions to SVN\n";
a5e0cedc 364}
8f22562c 365
d7ad3bed
EW
366sub cmd_dcommit {
367 my $head = shift;
d7ad3bed 368 $head ||= 'HEAD';
a8ae2623 369 my @refs;
13c823fb
EW
370 my ($url, $rev, $uuid, $gs) = working_head_info($head, \@refs);
371 unless ($gs) {
a8ae2623 372 die "Unable to determine upstream SVN information from ",
905f8b7d 373 "$head history\n";
a8ae2623 374 }
13c823fb 375 my $c = $refs[-1];
45bf473a 376 my $last_rev;
a8ae2623 377 foreach my $d (@refs) {
aef4e921 378 if (!verify_ref("$d~1")) {
d7ad3bed
EW
379 fatal "Commit $d\n",
380 "has no parent commit, and therefore ",
381 "nothing to diff against.\n",
382 "You should be working from a repository ",
383 "originally created by git-svn\n";
48d044b5 384 }
45bf473a
EW
385 unless (defined $last_rev) {
386 (undef, $last_rev, undef) = cmt_metadata("$d~1");
387 unless (defined $last_rev) {
d7ad3bed
EW
388 fatal "Unable to extract revision information ",
389 "from commit $d~1\n";
45bf473a
EW
390 }
391 }
b22d4497
EW
392 if ($_dry_run) {
393 print "diff-tree $d~1 $d\n";
394 } else {
d7ad3bed 395 my %ed_opts = ( r => $last_rev,
61395354 396 log => get_commit_entry($d)->{log},
645833b5 397 ra => Git::SVN::Ra->new($gs->full_url),
61395354
EW
398 tree_a => "$d~1",
399 tree_b => $d,
400 editor_cb => sub {
401 print "Committed r$_[0]\n";
402 $last_rev = $_[0]; },
a8ae2623 403 svn_path => '');
61395354 404 if (!SVN::Git::Editor->new(\%ed_opts)->apply_diff) {
d7ad3bed
EW
405 print "No changes\n$d~1 == $d\n";
406 }
b22d4497
EW
407 }
408 }
409 return if $_dry_run;
60d9c97a
EW
410 unless ($gs) {
411 warn "Could not determine fetch information for $url\n",
412 "Will not attempt to fetch and rebase commits.\n",
413 "This probably means you have useSvmProps and should\n",
414 "now resync your SVN::Mirror repository.\n";
415 return;
416 }
905f8b7d 417 $_fetch_all ? $gs->fetch_all : $gs->fetch;
171af110
KW
418 unless ($_no_rebase) {
419 # we always want to rebase against the current HEAD, not any
420 # head that was passed to us
421 my @diff = command('diff-tree', 'HEAD', $gs->refname, '--');
422 my @finish;
423 if (@diff) {
424 @finish = rebase_cmd();
425 print STDERR "W: HEAD and ", $gs->refname, " differ, ",
426 "using @finish:\n", "@diff";
427 } else {
428 print "No changes between current HEAD and ",
429 $gs->refname, "\nResetting to the latest ",
430 $gs->refname, "\n";
431 @finish = qw/reset --mixed/;
432 }
433 command_noisy(@finish, $gs->refname);
b22d4497 434 }
b22d4497
EW
435}
436
26e60160
AR
437sub cmd_find_rev {
438 my $revision_or_hash = shift;
439 my $result;
440 if ($revision_or_hash =~ /^r\d+$/) {
b3cb7e45
AR
441 my $head = shift;
442 $head ||= 'HEAD';
443 my @refs;
444 my (undef, undef, undef, $gs) = working_head_info($head, \@refs);
445 unless ($gs) {
446 die "Unable to determine upstream SVN information from ",
447 "$head history\n";
26e60160 448 }
b3cb7e45
AR
449 my $desired_revision = substr($revision_or_hash, 1);
450 $result = $gs->rev_db_get($desired_revision);
26e60160
AR
451 } else {
452 my (undef, $rev, undef) = cmt_metadata($revision_or_hash);
453 $result = $rev;
454 }
455 print "$result\n" if $result;
456}
457
905f8b7d
EW
458sub cmd_rebase {
459 command_noisy(qw/update-index --refresh/);
13c823fb
EW
460 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
461 unless ($gs) {
905f8b7d
EW
462 die "Unable to determine upstream SVN information from ",
463 "working tree history\n";
464 }
905f8b7d
EW
465 if (command(qw/diff-index HEAD --/)) {
466 print STDERR "Cannot rebase with uncommited changes:\n";
467 command_noisy('status');
468 exit 1;
469 }
dee41f3e
EW
470 unless ($_local) {
471 $_fetch_all ? $gs->fetch_all : $gs->fetch;
472 }
905f8b7d
EW
473 command_noisy(rebase_cmd(), $gs->refname);
474}
475
5969cbe1 476sub cmd_show_ignore {
13c823fb
EW
477 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
478 $gs ||= Git::SVN->new;
5969cbe1 479 my $r = (defined $_revision ? $_revision : $gs->ra->get_latest_revnum);
102a0a2d 480 $gs->traverse_ignore(\*STDOUT, $gs->{path}, $r);
a5e0cedc
EW
481}
482
8164b652 483sub cmd_multi_init {
9d55b41a 484 my $url = shift;
98327e58
EW
485 unless (defined $_trunk || defined $_branches || defined $_tags) {
486 usage(1);
9d55b41a 487 }
dc431666
EW
488
489 # there are currently some bugs that prevent multi-init/multi-fetch
490 # setups from working well without this.
491 $Git::SVN::_minimize_url = 1;
492
8164b652 493 $_prefix = '' unless defined $_prefix;
dadc6d2a
EW
494 if (defined $url) {
495 $url =~ s#/+$##;
496 init_subdir(@_);
497 }
f30603fc 498 do_git_init_db();
98327e58 499 if (defined $_trunk) {
706587fc
EW
500 my $trunk_ref = $_prefix . 'trunk';
501 # try both old-style and new-style lookups:
502 my $gs_trunk = eval { Git::SVN->new($trunk_ref) };
8164b652 503 unless ($gs_trunk) {
706587fc
EW
504 my ($trunk_url, $trunk_path) =
505 complete_svn_url($url, $_trunk);
506 $gs_trunk = Git::SVN->init($trunk_url, $trunk_path,
507 undef, $trunk_ref);
98327e58 508 }
c35b96e7 509 }
706587fc 510 return unless defined $_branches || defined $_tags;
e7db67e6
EW
511 my $ra = $url ? Git::SVN::Ra->new($url) : undef;
512 complete_url_ls_init($ra, $_branches, '--branches/-b', $_prefix);
513 complete_url_ls_init($ra, $_tags, '--tags/-t', $_prefix . 'tags/');
9d55b41a
EW
514}
515
1c8443b0 516sub cmd_multi_fetch {
0af9c9f9
EW
517 my $remotes = Git::SVN::read_all_remotes();
518 foreach my $repo_id (sort keys %$remotes) {
db03cd24 519 if ($remotes->{$repo_id}->{url}) {
4bb9ed04
EW
520 Git::SVN::fetch_all($repo_id, $remotes);
521 }
9d55b41a 522 }
9d55b41a
EW
523}
524
44320b9e
EW
525# this command is special because it requires no metadata
526sub cmd_commit_diff {
527 my ($ta, $tb, $url) = @_;
528 my $usage = "Usage: $0 commit-diff -r<revision> ".
529 "<tree-ish> <tree-ish> [<URL>]\n";
530 fatal($usage) if (!defined $ta || !defined $tb);
d3a840dc 531 my $svn_path;
44320b9e
EW
532 if (!defined $url) {
533 my $gs = eval { Git::SVN->new };
534 if (!$gs) {
535 fatal("Needed URL or usable git-svn --id in ",
536 "the command-line\n", $usage);
537 }
538 $url = $gs->{url};
d3a840dc 539 $svn_path = $gs->{path};
44320b9e
EW
540 }
541 unless (defined $_revision) {
542 fatal("-r|--revision is a required argument\n", $usage);
543 }
544 if (defined $_message && defined $_file) {
545 fatal("Both --message/-m and --file/-F specified ",
546 "for the commit message.\n",
547 "I have no idea what you mean\n");
548 }
549 if (defined $_file) {
550 $_message = file_to_s($_file);
551 } else {
552 $_message ||= get_commit_entry($tb)->{log};
553 }
554 my $ra ||= Git::SVN::Ra->new($url);
d3a840dc 555 $svn_path ||= $ra->{svn_path};
44320b9e
EW
556 my $r = $_revision;
557 if ($r eq 'HEAD') {
558 $r = $ra->get_latest_revnum;
559 } elsif ($r !~ /^\d+$/) {
560 die "revision argument: $r not understood by git-svn\n";
561 }
61395354
EW
562 my %ed_opts = ( r => $r,
563 log => $_message,
564 ra => $ra,
565 tree_a => $ta,
566 tree_b => $tb,
567 editor_cb => sub { print "Committed r$_[0]\n" },
568 svn_path => $svn_path );
569 if (!SVN::Git::Editor->new(\%ed_opts)->apply_diff) {
44320b9e
EW
570 print "No changes\n$ta == $tb\n";
571 }
44320b9e
EW
572}
573
3397f9df
EW
574########################### utility functions #########################
575
905f8b7d
EW
576sub rebase_cmd {
577 my @cmd = qw/rebase/;
578 push @cmd, '-v' if $_verbose;
579 push @cmd, qw/--merge/ if $_merge;
580 push @cmd, "--strategy=$_strategy" if $_strategy;
581 @cmd;
582}
583
1e889ef3
EW
584sub post_fetch_checkout {
585 return if $_no_checkout;
586 my $gs = $Git::SVN::_head or return;
587 return if verify_ref('refs/heads/master^0');
588
589 my $valid_head = verify_ref('HEAD^0');
590 command_noisy(qw(update-ref refs/heads/master), $gs->refname);
591 return if ($valid_head || !verify_ref('HEAD^0'));
592
593 return if $ENV{GIT_DIR} !~ m#^(?:.*/)?\.git$#;
594 my $index = $ENV{GIT_INDEX_FILE} || "$ENV{GIT_DIR}/index";
595 return if -f $index;
596
493c774e 597 return if command_oneline(qw/rev-parse --is-bare-repository/) eq 'true';
1e889ef3
EW
598 return if command_oneline(qw/rev-parse --is-inside-git-dir/) eq 'true';
599 command_noisy(qw/read-tree -m -u -v HEAD HEAD/);
600 print STDERR "Checked out HEAD:\n ",
601 $gs->full_url, " r", $gs->last_rev, "\n";
602}
603
98327e58
EW
604sub complete_svn_url {
605 my ($url, $path) = @_;
606 $path =~ s#/+$##;
98327e58 607 if ($path !~ m#^[a-z\+]+://#) {
98327e58
EW
608 if (!defined $url || $url !~ m#^[a-z\+]+://#) {
609 fatal("E: '$path' is not a complete URL ",
610 "and a separate URL is not specified\n");
611 }
706587fc 612 return ($url, $path);
98327e58 613 }
706587fc 614 return ($path, '');
98327e58
EW
615}
616
9d55b41a 617sub complete_url_ls_init {
706587fc
EW
618 my ($ra, $repo_path, $switch, $pfx) = @_;
619 unless ($repo_path) {
9d55b41a
EW
620 print STDERR "W: $switch not specified\n";
621 return;
622 }
706587fc
EW
623 $repo_path =~ s#/+$##;
624 if ($repo_path =~ m#^[a-z\+]+://#) {
625 $ra = Git::SVN::Ra->new($repo_path);
626 $repo_path = '';
e7db67e6 627 } else {
706587fc 628 $repo_path =~ s#^/+##;
e7db67e6 629 unless ($ra) {
706587fc 630 fatal("E: '$repo_path' is not a complete URL ",
e7db67e6 631 "and a separate URL is not specified\n");
8164b652 632 }
e7db67e6 633 }
706587fc 634 my $url = $ra->{url};
b4d57e5e
EW
635 my $gs = Git::SVN->init($url, undef, undef, undef, 1);
636 my $k = "svn-remote.$gs->{repo_id}.url";
637 my $orig_url = eval { command_oneline(qw/config --get/, $k) };
638 if ($orig_url && ($orig_url ne $gs->{url})) {
639 die "$k already set: $orig_url\n",
640 "wanted to set to: $gs->{url}\n";
88cf4107 641 }
b4d57e5e
EW
642 command_oneline('config', $k, $gs->{url}) unless $orig_url;
643 my $remote_path = "$ra->{svn_path}/$repo_path/*";
644 $remote_path =~ s#/+#/#g;
645 $remote_path =~ s#^/##g;
646 my ($n) = ($switch =~ /^--(\w+)/);
647 if (length $pfx && $pfx !~ m#/$#) {
648 die "--prefix='$pfx' must have a trailing slash '/'\n";
9d55b41a 649 }
b4d57e5e
EW
650 command_noisy('config', "svn-remote.$gs->{repo_id}.$n",
651 "$remote_path:refs/remotes/$pfx*");
9d55b41a
EW
652}
653
aef4e921
EW
654sub verify_ref {
655 my ($ref) = @_;
2c5c1d53
EW
656 eval { command_oneline([ 'rev-parse', '--verify', $ref ],
657 { STDERR => 0 }); };
aef4e921
EW
658}
659
a5e0cedc 660sub get_tree_from_treeish {
cf52b8f0 661 my ($treeish) = @_;
44320b9e 662 # $treeish can be a symbolic ref, too:
aef4e921 663 my $type = command_oneline(qw/cat-file -t/, $treeish);
cf52b8f0
EW
664 my $expected;
665 while ($type eq 'tag') {
aef4e921 666 ($treeish, $type) = command(qw/cat-file tag/, $treeish);
cf52b8f0
EW
667 }
668 if ($type eq 'commit') {
aef4e921
EW
669 $expected = (grep /^tree /, command(qw/cat-file commit/,
670 $treeish))[0];
44320b9e 671 ($expected) = ($expected =~ /^tree ($sha1)$/o);
cf52b8f0
EW
672 die "Unable to get tree from $treeish\n" unless $expected;
673 } elsif ($type eq 'tree') {
674 $expected = $treeish;
675 } else {
676 die "$treeish is a $type, expected tree, tag or commit\n";
677 }
a5e0cedc
EW
678 return $expected;
679}
680
44320b9e
EW
681sub get_commit_entry {
682 my ($treeish) = shift;
683 my %log_entry = ( log => '', tree => get_tree_from_treeish($treeish) );
684 my $commit_editmsg = "$ENV{GIT_DIR}/COMMIT_EDITMSG";
685 my $commit_msg = "$ENV{GIT_DIR}/COMMIT_MSG";
686 open my $log_fh, '>', $commit_editmsg or croak $!;
3397f9df 687
44320b9e 688 my $type = command_oneline(qw/cat-file -t/, $treeish);
4ad4515d 689 if ($type eq 'commit' || $type eq 'tag') {
aef4e921 690 my ($msg_fh, $ctx) = command_output_pipe('cat-file',
44320b9e 691 $type, $treeish);
3397f9df
EW
692 my $in_msg = 0;
693 while (<$msg_fh>) {
694 if (!$in_msg) {
695 $in_msg = 1 if (/^\s*$/);
df746c5a 696 } elsif (/^git-svn-id: /) {
44320b9e
EW
697 # skip this for now, we regenerate the
698 # correct one on re-fetch anyways
699 # TODO: set *:merge properties or like...
3397f9df 700 } else {
44320b9e 701 print $log_fh $_ or croak $!;
3397f9df
EW
702 }
703 }
aef4e921 704 command_close_pipe($msg_fh, $ctx);
3397f9df 705 }
44320b9e 706 close $log_fh or croak $!;
3397f9df
EW
707
708 if ($_edit || ($type eq 'tree')) {
709 my $editor = $ENV{VISUAL} || $ENV{EDITOR} || 'vi';
44320b9e
EW
710 # TODO: strip out spaces, comments, like git-commit.sh
711 system($editor, $commit_editmsg);
3397f9df 712 }
44320b9e
EW
713 rename $commit_editmsg, $commit_msg or croak $!;
714 open $log_fh, '<', $commit_msg or croak $!;
715 { local $/; chomp($log_entry{log} = <$log_fh>); }
716 close $log_fh or croak $!;
717 unlink $commit_msg;
718 \%log_entry;
a5e0cedc
EW
719}
720
3397f9df
EW
721sub s_to_file {
722 my ($str, $file, $mode) = @_;
723 open my $fd,'>',$file or croak $!;
724 print $fd $str,"\n" or croak $!;
725 close $fd or croak $!;
726 chmod ($mode &~ umask, $file) if (defined $mode);
727}
728
729sub file_to_s {
730 my $file = shift;
731 open my $fd,'<',$file or croak "$!: file: $file\n";
732 local $/;
733 my $ret = <$fd>;
734 close $fd or croak $!;
735 $ret =~ s/\s*$//s;
736 return $ret;
737}
738
eeb0abe0
EW
739# '<svn username> = real-name <email address>' mapping based on git-svnimport:
740sub load_authors {
741 open my $authors, '<', $_authors or die "Can't open $_authors $!\n";
f8c9d1d2 742 my $log = $cmd eq 'log';
eeb0abe0
EW
743 while (<$authors>) {
744 chomp;
8815788e 745 next unless /^(\S+?|\(no author\))\s*=\s*(.+?)\s*<(.+)>\s*$/;
eeb0abe0 746 my ($user, $name, $email) = ($1, $2, $3);
f8c9d1d2
EW
747 if ($log) {
748 $Git::SVN::Log::rusers{"$name <$email>"} = $user;
749 } else {
750 $users{$user} = [$name, $email];
751 }
79bb8d88
EW
752 }
753 close $authors or croak $!;
754}
755
e0d10e1c 756# convert GetOpt::Long specs for use by git-config
b8c92cad 757sub read_repo_config {
706587fc 758 return unless -d $ENV{GIT_DIR};
b8c92cad 759 my $opts = shift;
97ae0911 760 my @config_only;
b8c92cad 761 foreach my $o (keys %$opts) {
97ae0911
EW
762 # if we have mixedCase and a long option-only, then
763 # it's a config-only variable that we don't need for
764 # the command-line.
765 push @config_only, $o if ($o =~ /[A-Z]/ && $o =~ /^[a-z]+$/i);
b8c92cad 766 my $v = $opts->{$o};
97ae0911 767 my ($key) = ($o =~ /^([a-zA-Z\-]+)/);
b8c92cad 768 $key =~ s/-//g;
e0d10e1c 769 my $arg = 'git-config';
b8c92cad
EW
770 $arg .= ' --int' if ($o =~ /[:=]i$/);
771 $arg .= ' --bool' if ($o !~ /[:=][sfi]$/);
772 if (ref $v eq 'ARRAY') {
773 chomp(my @tmp = `$arg --get-all svn.$key`);
774 @$v = @tmp if @tmp;
775 } else {
776 chomp(my $tmp = `$arg --get svn.$key`);
7774284a 777 if ($tmp && !($arg =~ / --bool/ && $tmp eq 'false')) {
b8c92cad
EW
778 $$v = $tmp;
779 }
780 }
781 }
97ae0911 782 delete @$opts{@config_only} if @config_only;
b8c92cad
EW
783}
784
79bb8d88 785sub extract_metadata {
c1927a85 786 my $id = shift or return (undef, undef, undef);
79bb8d88
EW
787 my ($url, $rev, $uuid) = ($id =~ /^git-svn-id:\s(\S+?)\@(\d+)
788 \s([a-f\d\-]+)$/x);
e70dc780 789 if (!defined $rev || !$uuid || !$url) {
79bb8d88 790 # some of the original repositories I made had
82e5a82f 791 # identifiers like this:
79bb8d88
EW
792 ($rev, $uuid) = ($id =~/^git-svn-id:\s(\d+)\@([a-f\d\-]+)/);
793 }
794 return ($url, $rev, $uuid);
795}
796
c1927a85
EW
797sub cmt_metadata {
798 return extract_metadata((grep(/^git-svn-id: /,
aef4e921 799 command(qw/cat-file commit/, shift)))[-1]);
c1927a85
EW
800}
801
905f8b7d
EW
802sub working_head_info {
803 my ($head, $refs) = @_;
905f8b7d 804 my ($fh, $ctx) = command_output_pipe('rev-list', $head);
b03c7a63
AR
805 while (my $hash = <$fh>) {
806 chomp($hash);
807 my ($url, $rev, $uuid) = cmt_metadata($hash);
13c823fb
EW
808 if (defined $url && defined $rev) {
809 if (my $gs = Git::SVN->find_by_url($url)) {
810 my $c = $gs->rev_db_get($rev);
b03c7a63 811 if ($c && $c eq $hash) {
13c823fb
EW
812 close $fh; # break the pipe
813 return ($url, $rev, $uuid, $gs);
814 }
815 }
816 }
b03c7a63 817 unshift @$refs, $hash if $refs;
905f8b7d 818 }
13c823fb
EW
819 command_close_pipe($fh, $ctx);
820 (undef, undef, undef, undef);
905f8b7d
EW
821}
822
9b981fc6
EW
823package Git::SVN;
824use strict;
825use warnings;
ecc712dd 826use vars qw/$default_repo_id $default_ref_id $_no_metadata $_follow_parent
62e349d2 827 $_repack $_repack_flags $_use_svm_props $_head
4a1bb4c3 828 $_use_svnsync_props $no_reuse_existing $_minimize_url/;
9b981fc6
EW
829use Carp qw/croak/;
830use File::Path qw/mkpath/;
373274f9 831use File::Copy qw/copy/;
9b981fc6
EW
832use IPC::Open3;
833
ecc712dd 834my $_repack_nr;
9b981fc6
EW
835# properties that we do not log:
836my %SKIP_PROP;
837BEGIN {
838 %SKIP_PROP = map { $_ => 1 } qw/svn:wc:ra_dav:version-url
839 svn:special svn:executable
840 svn:entry:committed-rev
841 svn:entry:last-author
842 svn:entry:uuid
843 svn:entry:committed-date/;
91b03282
EW
844
845 # some options are read globally, but can be overridden locally
846 # per [svn-remote "..."] section. Command-line options will *NOT*
847 # override options set in an [svn-remote "..."] section
848 my $e;
62e349d2
EW
849 foreach (qw/follow_parent no_metadata use_svm_props
850 use_svnsync_props/) {
91b03282
EW
851 my $key = $_;
852 $key =~ tr/_//d;
853 $e .= "sub $_ {
854 my (\$self) = \@_;
855 return \$self->{-$_} if exists \$self->{-$_};
856 my \$k = \"svn-remote.\$self->{repo_id}\.$key\";
857 eval { command_oneline(qw/config --get/, \$k) };
858 if (\$@) {
859 \$self->{-$_} = \$Git::SVN::_$_;
860 } else {
861 my \$v = command_oneline(qw/config --bool/,\$k);
862 \$self->{-$_} = \$v eq 'false' ? 0 : 1;
863 }
864 return \$self->{-$_} }\n";
865 }
866 $e .= "1;\n";
867 eval $e or die $@;
9b981fc6
EW
868}
869
373274f9
EW
870my %LOCKFILES;
871END { unlink keys %LOCKFILES if %LOCKFILES }
872
4bb9ed04
EW
873sub resolve_local_globs {
874 my ($url, $fetch, $glob_spec) = @_;
875 return unless defined $glob_spec;
876 my $ref = $glob_spec->{ref};
877 my $path = $glob_spec->{path};
878 foreach (command(qw#for-each-ref --format=%(refname) refs/remotes#)) {
879 next unless m#^refs/remotes/$ref->{regex}$#;
880 my $p = $1;
881 my $pathname = $path->full_path($p);
882 my $refname = $ref->full_path($p);
883 if (my $existing = $fetch->{$pathname}) {
884 if ($existing ne $refname) {
885 die "Refspec conflict:\n",
886 "existing: refs/remotes/$existing\n",
887 " globbed: refs/remotes/$refname\n";
888 }
889 my $u = (::cmt_metadata("refs/remotes/$refname"))[0];
4e9f6cc7 890 $u =~ s!^\Q$url\E(/|$)!! or die
4bb9ed04
EW
891 "refs/remotes/$refname: '$url' not found in '$u'\n";
892 if ($pathname ne $u) {
893 warn "W: Refspec glob conflict ",
894 "(ref: refs/remotes/$refname):\n",
895 "expected path: $pathname\n",
896 " real path: $u\n",
897 "Continuing ahead with $u\n";
898 next;
899 }
900 } else {
4bb9ed04
EW
901 $fetch->{$pathname} = $refname;
902 }
903 }
904}
905
e98671e5
EW
906sub parse_revision_argument {
907 my ($base, $head) = @_;
908 if (!defined $::_revision || $::_revision eq 'BASE:HEAD') {
909 return ($base, $head);
910 }
911 return ($1, $2) if ($::_revision =~ /^(\d+):(\d+)$/);
912 return ($::_revision, $::_revision) if ($::_revision =~ /^\d+$/);
913 return ($head, $head) if ($::_revision eq 'HEAD');
914 return ($base, $1) if ($::_revision =~ /^BASE:(\d+)$/);
915 return ($1, $head) if ($::_revision =~ /^(\d+):HEAD$/);
916 die "revision argument: $::_revision not understood by git-svn\n";
917}
918
0af9c9f9 919sub fetch_all {
4bb9ed04 920 my ($repo_id, $remotes) = @_;
905f8b7d
EW
921 if (ref $repo_id) {
922 my $gs = $repo_id;
923 $repo_id = undef;
924 $repo_id = $gs->{repo_id};
925 }
926 $remotes ||= read_all_remotes();
7447b4bc
EW
927 my $remote = $remotes->{$repo_id} or
928 die "[svn-remote \"$repo_id\"] unknown\n";
e518192f 929 my $fetch = $remote->{fetch};
7447b4bc 930 my $url = $remote->{url} or die "svn-remote.$repo_id.url not defined\n";
e518192f 931 my (@gs, @globs);
0af9c9f9 932 my $ra = Git::SVN::Ra->new($url);
26a62d57 933 my $uuid = $ra->get_uuid;
0af9c9f9 934 my $head = $ra->get_latest_revnum;
28710f74 935 my $base = defined $fetch ? $head : 0;
e518192f
EW
936
937 # read the max revs for wildcard expansion (branches/*, tags/*)
938 foreach my $t (qw/branches tags/) {
939 defined $remote->{$t} or next;
940 push @globs, $remote->{$t};
93f2689c
EW
941 my $max_rev = eval { tmp_config(qw/--int --get/,
942 "svn-remote.$repo_id.${t}-maxRev") };
943 if (defined $max_rev && ($max_rev < $base)) {
944 $base = $max_rev;
d6d3346b
EW
945 } elsif (!defined $max_rev) {
946 $base = 0;
e518192f
EW
947 }
948 }
949
db03cd24
EW
950 if ($fetch) {
951 foreach my $p (sort keys %$fetch) {
952 my $gs = Git::SVN->new($fetch->{$p}, $repo_id, $p);
953 my $lr = $gs->rev_db_max;
954 if (defined $lr) {
955 $base = $lr if ($lr < $base);
956 }
957 push @gs, $gs;
0af9c9f9 958 }
0af9c9f9 959 }
e98671e5
EW
960
961 ($base, $head) = parse_revision_argument($base, $head);
e518192f 962 $ra->gs_fetch_loop_common($base, $head, \@gs, \@globs);
0af9c9f9
EW
963}
964
47e39c55
EW
965sub read_all_remotes {
966 my $r = {};
8b8fc068 967 foreach (grep { s/^svn-remote\.// } command(qw/config -l/)) {
47e39c55
EW
968 if (m!^(.+)\.fetch=\s*(.*)\s*:\s*refs/remotes/(.+)\s*$!) {
969 $r->{$1}->{fetch}->{$2} = $3;
970 } elsif (m!^(.+)\.url=\s*(.*)\s*$!) {
971 $r->{$1}->{url} = $2;
4bb9ed04
EW
972 } elsif (m!^(.+)\.(branches|tags)=
973 (.*):refs/remotes/(.+)\s*$/!x) {
974 my ($p, $g) = ($3, $4);
975 my $rs = $r->{$1}->{$2} = {
e518192f 976 t => $2,
93f2689c 977 remote => $1,
4bb9ed04
EW
978 path => Git::SVN::GlobSpec->new($p),
979 ref => Git::SVN::GlobSpec->new($g) };
980 if (length($rs->{ref}->{right}) != 0) {
981 die "The '*' glob character must be the last ",
982 "character of '$g'\n";
983 }
47e39c55
EW
984 }
985 }
986 $r;
987}
988
ecc712dd
EW
989sub init_vars {
990 if (defined $_repack) {
991 $_repack = 1000 if ($_repack <= 0);
992 $_repack_nr = $_repack;
993 $_repack_flags ||= '-d';
994 }
995}
996
b805b44a 997sub verify_remotes_sanity {
536c4b09 998 return unless -d $ENV{GIT_DIR};
b805b44a
EW
999 my %seen;
1000 foreach (command(qw/config -l/)) {
1001 if (m!^svn-remote\.(?:.+)\.fetch=.*:refs/remotes/(\S+)\s*$!) {
1002 if ($seen{$1}) {
1003 die "Remote ref refs/remote/$1 is tracked by",
1004 "\n \"$_\"\nand\n \"$seen{$1}\"\n",
1005 "Please resolve this ambiguity in ",
1006 "your git configuration file before ",
1007 "continuing\n";
1008 }
1009 $seen{$1} = $_;
1010 }
1011 }
1012}
1013
47e39c55 1014# we allow more chars than remotes2config.sh...
706587fc
EW
1015sub sanitize_remote_name {
1016 my ($name) = @_;
47e39c55 1017 $name =~ tr{A-Za-z0-9:,/+-}{.}c;
706587fc
EW
1018 $name;
1019}
1020
e6434f87
EW
1021sub find_existing_remote {
1022 my ($url, $remotes) = @_;
befc9adc 1023 return undef if $no_reuse_existing;
e6434f87
EW
1024 my $existing;
1025 foreach my $repo_id (keys %$remotes) {
1026 my $u = $remotes->{$repo_id}->{url} or next;
1027 next if $u ne $url;
1028 $existing = $repo_id;
1029 last;
1030 }
1031 $existing;
1032}
b805b44a 1033
e6434f87 1034sub init_remote_config {
d8115c51 1035 my ($self, $url, $no_write) = @_;
e6434f87
EW
1036 $url =~ s!/+$!!; # strip trailing slash
1037 my $r = read_all_remotes();
1038 my $existing = find_existing_remote($url, $r);
1039 if ($existing) {
e518192f
EW
1040 unless ($no_write) {
1041 print STDERR "Using existing ",
1042 "[svn-remote \"$existing\"]\n";
1043 }
e6434f87 1044 $self->{repo_id} = $existing;
4a1bb4c3 1045 } elsif ($_minimize_url) {
e6434f87
EW
1046 my $min_url = Git::SVN::Ra->new($url)->minimize_url;
1047 $existing = find_existing_remote($min_url, $r);
1048 if ($existing) {
e518192f
EW
1049 unless ($no_write) {
1050 print STDERR "Using existing ",
1051 "[svn-remote \"$existing\"]\n";
1052 }
e6434f87
EW
1053 $self->{repo_id} = $existing;
1054 }
1055 if ($min_url ne $url) {
e518192f
EW
1056 unless ($no_write) {
1057 print STDERR "Using higher level of URL: ",
1058 "$url => $min_url\n";
1059 }
e6434f87
EW
1060 my $old_path = $self->{path};
1061 $self->{path} = $url;
4e9f6cc7 1062 $self->{path} =~ s!^\Q$min_url\E(/|$)!!;
e6434f87
EW
1063 if (length $old_path) {
1064 $self->{path} .= "/$old_path";
1065 }
1066 $url = $min_url;
1067 }
1068 }
1069 my $orig_url;
1070 if (!$existing) {
b805b44a 1071 # verify that we aren't overwriting anything:
e6434f87 1072 $orig_url = eval {
706587fc 1073 command_oneline('config', '--get',
e6434f87 1074 "svn-remote.$self->{repo_id}.url")
706587fc 1075 };
b805b44a 1076 if ($orig_url && ($orig_url ne $url)) {
e6434f87 1077 die "svn-remote.$self->{repo_id}.url already set: ",
b805b44a
EW
1078 "$orig_url\nwanted to set to: $url\n";
1079 }
9b981fc6 1080 }
e6434f87
EW
1081 my ($xrepo_id, $xpath) = find_ref($self->refname);
1082 if (defined $xpath) {
1083 die "svn-remote.$xrepo_id.fetch already set to track ",
1084 "$xpath:refs/remotes/", $self->refname, "\n";
1085 }
d8115c51
EW
1086 unless ($no_write) {
1087 command_noisy('config',
1088 "svn-remote.$self->{repo_id}.url", $url);
1089 command_noisy('config', '--add',
1090 "svn-remote.$self->{repo_id}.fetch",
1091 "$self->{path}:".$self->refname);
1092 }
9b981fc6 1093 $self->{url} = $url;
e6434f87
EW
1094}
1095
a8ae2623
EW
1096sub find_by_url { # repos_root and, path are optional
1097 my ($class, $full_url, $repos_root, $path) = @_;
56973d20 1098
1a97a506 1099 return undef unless defined $full_url;
56973d20
AR
1100 remove_username($full_url);
1101 remove_username($repos_root) if defined $repos_root;
a8ae2623
EW
1102 my $remotes = read_all_remotes();
1103 if (defined $full_url && defined $repos_root && !defined $path) {
1104 $path = $full_url;
1105 $path =~ s#^\Q$repos_root\E(?:/|$)##;
1106 }
1107 foreach my $repo_id (keys %$remotes) {
1108 my $u = $remotes->{$repo_id}->{url} or next;
56973d20 1109 remove_username($u);
a8ae2623
EW
1110 next if defined $repos_root && $repos_root ne $u;
1111
1112 my $fetch = $remotes->{$repo_id}->{fetch} || {};
1113 foreach (qw/branches tags/) {
1114 resolve_local_globs($u, $fetch,
1115 $remotes->{$repo_id}->{$_});
1116 }
1117 my $p = $path;
1118 unless (defined $p) {
1119 $p = $full_url;
1120 $p =~ s#^\Q$u\E(?:/|$)## or next;
1121 }
1122 foreach my $f (keys %$fetch) {
1123 next if $f ne $p;
1124 return Git::SVN->new($fetch->{$f}, $repo_id, $f);
1125 }
1126 }
1127 undef;
1128}
1129
e6434f87 1130sub init {
d8115c51 1131 my ($class, $url, $path, $repo_id, $ref_id, $no_write) = @_;
e6434f87
EW
1132 my $self = _new($class, $repo_id, $ref_id, $path);
1133 if (defined $url) {
d8115c51 1134 $self->init_remote_config($url, $no_write);
e6434f87 1135 }
9b981fc6
EW
1136 $self;
1137}
1138
706587fc
EW
1139sub find_ref {
1140 my ($ref_id) = @_;
1141 foreach (command(qw/config -l/)) {
1142 next unless m!^svn-remote\.(.+)\.fetch=
1143 \s*(.*)\s*:\s*refs/remotes/(.+)\s*$!x;
1144 my ($repo_id, $path, $ref) = ($1, $2, $3);
1145 if ($ref eq $ref_id) {
1146 $path = '' if ($path =~ m#^\./?#);
1147 return ($repo_id, $path);
1148 }
1149 }
1150 (undef, undef, undef);
1151}
1152
9b981fc6 1153sub new {
706587fc
EW
1154 my ($class, $ref_id, $repo_id, $path) = @_;
1155 if (defined $ref_id && !defined $repo_id && !defined $path) {
1156 ($repo_id, $path) = find_ref($ref_id);
1157 if (!defined $repo_id) {
1158 die "Could not find a \"svn-remote.*.fetch\" key ",
1159 "in the repository configuration matching: ",
1160 "refs/remotes/$ref_id\n";
1161 }
1162 }
1163 my $self = _new($class, $repo_id, $ref_id, $path);
8b8fc068
EW
1164 if (!defined $self->{path} || !length $self->{path}) {
1165 my $fetch = command_oneline('config', '--get',
1166 "svn-remote.$repo_id.fetch",
1167 ":refs/remotes/$ref_id\$") or
1168 die "Failed to read \"svn-remote.$repo_id.fetch\" ",
1169 "\":refs/remotes/$ref_id\$\" in config\n";
1170 ($self->{path}, undef) = split(/\s*:\s*/, $fetch);
1171 }
706587fc
EW
1172 $self->{url} = command_oneline('config', '--get',
1173 "svn-remote.$repo_id.url") or
1174 die "Failed to read \"svn-remote.$repo_id.url\" in config\n";
d6d3346b 1175 $self->rebuild;
9b981fc6
EW
1176 $self;
1177}
1178
706587fc 1179sub refname { "refs/remotes/$_[0]->{ref_id}" }
9b981fc6 1180
26a62d57
EW
1181sub svm_uuid {
1182 my ($self) = @_;
1183 return $self->{svm}->{uuid} if $self->svm;
1184 $self->ra;
1185 unless ($self->{svm}) {
1186 die "SVM UUID not cached, and reading remotely failed\n";
1187 }
1188 $self->{svm}->{uuid};
1189}
8a49ee97 1190
26a62d57
EW
1191sub svm {
1192 my ($self) = @_;
1193 return $self->{svm} if $self->{svm};
1194 my $svm;
8a49ee97
EW
1195 # see if we have it in our config, first:
1196 eval {
26a62d57
EW
1197 my $section = "svn-remote.$self->{repo_id}";
1198 $svm = {
93f2689c
EW
1199 source => tmp_config('--get', "$section.svm-source"),
1200 uuid => tmp_config('--get', "$section.svm-uuid"),
befc9adc 1201 replace => tmp_config('--get', "$section.svm-replace"),
8a49ee97
EW
1202 }
1203 };
befc9adc
EW
1204 if ($svm && $svm->{source} && $svm->{uuid} && $svm->{replace}) {
1205 $self->{svm} = $svm;
1206 }
26a62d57
EW
1207 $self->{svm};
1208}
1209
1210sub _set_svm_vars {
1211 my ($self, $ra) = @_;
db03cd24
EW
1212 return $ra if $self->svm;
1213
1214 my @err = ( "useSvmProps set, but failed to read SVM properties\n",
befc9adc 1215 "(svm:source, svm:uuid) ",
db03cd24
EW
1216 "from the following URLs:\n" );
1217 sub read_svm_props {
befc9adc
EW
1218 my ($self, $ra, $path, $r) = @_;
1219 my $props = ($ra->get_dir($path, $r))[2];
db03cd24 1220 my $src = $props->{'svm:source'};
db03cd24 1221 my $uuid = $props->{'svm:uuid'};
befc9adc 1222 return undef if (!$src || !$uuid);
26a62d57 1223
befc9adc 1224 chomp($src, $uuid);
26a62d57 1225
db03cd24
EW
1226 $uuid =~ m{^[0-9a-f\-]{30,}$}
1227 or die "doesn't look right - svm:uuid is '$uuid'\n";
befc9adc
EW
1228
1229 # the '!' is used to mark the repos_root!/relative/path
1230 $src =~ s{/?!/?}{/};
db03cd24 1231 $src =~ s{/+$}{}; # no trailing slashes please
befc9adc 1232 # username is of no interest
8a49ee97 1233 $src =~ s{(^[a-z\+]*://)[^/@]*@}{$1};
8a49ee97 1234
befc9adc
EW
1235 my $replace = $ra->{url};
1236 $replace .= "/$path" if length $path;
1237
db03cd24 1238 my $section = "svn-remote.$self->{repo_id}";
befc9adc
EW
1239 tmp_config("$section.svm-source", $src);
1240 tmp_config("$section.svm-replace", $replace);
1241 tmp_config("$section.svm-uuid", $uuid);
1242 $self->{svm} = {
1243 source => $src,
1244 uuid => $uuid,
1245 replace => $replace
1246 };
db03cd24
EW
1247 }
1248
1249 my $r = $ra->get_latest_revnum;
1250 my $path = $self->{path};
befc9adc 1251 my %tried;
db03cd24 1252 while (length $path) {
befc9adc
EW
1253 unless ($tried{"$self->{url}/$path"}) {
1254 return $ra if $self->read_svm_props($ra, $path, $r);
1255 $tried{"$self->{url}/$path"} = 1;
db03cd24 1256 }
befc9adc 1257 $path =~ s#/?[^/]+$##;
8a49ee97 1258 }
befc9adc
EW
1259 die "Path: '$path' should be ''\n" if $path ne '';
1260 return $ra if $self->read_svm_props($ra, $path, $r);
1261 $tried{"$self->{url}/$path"} = 1;
db03cd24
EW
1262
1263 if ($ra->{repos_root} eq $self->{url}) {
befc9adc 1264 die @err, (map { " $_\n" } keys %tried), "\n";
db03cd24
EW
1265 }
1266
1267 # nope, make sure we're connected to the repository root:
1268 my $ok;
1269 my @tried_b;
1270 $path = $ra->{svn_path};
db03cd24
EW
1271 $ra = Git::SVN::Ra->new($ra->{repos_root});
1272 while (length $path) {
befc9adc
EW
1273 unless ($tried{"$ra->{url}/$path"}) {
1274 $ok = $self->read_svm_props($ra, $path, $r);
1275 last if $ok;
1276 $tried{"$ra->{url}/$path"} = 1;
1277 }
1278 $path =~ s#/?[^/]+$##;
db03cd24 1279 }
befc9adc
EW
1280 die "Path: '$path' should be ''\n" if $path ne '';
1281 $ok ||= $self->read_svm_props($ra, $path, $r);
1282 $tried{"$ra->{url}/$path"} = 1;
db03cd24 1283 if (!$ok) {
befc9adc 1284 die @err, (map { " $_\n" } keys %tried), "\n";
db03cd24
EW
1285 }
1286 Git::SVN::Ra->new($self->{url});
8a49ee97
EW
1287}
1288
62e349d2
EW
1289sub svnsync {
1290 my ($self) = @_;
1291 return $self->{svnsync} if $self->{svnsync};
1292
1293 if ($self->no_metadata) {
1294 die "Can't have both 'noMetadata' and ",
1295 "'useSvnsyncProps' options set!\n";
1296 }
1297 if ($self->rewrite_root) {
1298 die "Can't have both 'useSvnsyncProps' and 'rewriteRoot' ",
1299 "options set!\n";
1300 }
1301
1302 my $svnsync;
1303 # see if we have it in our config, first:
1304 eval {
1305 my $section = "svn-remote.$self->{repo_id}";
1306 $svnsync = {
1307 url => tmp_config('--get', "$section.svnsync-url"),
1308 uuid => tmp_config('--get', "$section.svnsync-uuid"),
1309 }
1310 };
1311 if ($svnsync && $svnsync->{url} && $svnsync->{uuid}) {
1312 return $self->{svnsync} = $svnsync;
1313 }
1314
1315 my $err = "useSvnsyncProps set, but failed to read " .
1316 "svnsync property: svn:sync-from-";
1317 my $rp = $self->ra->rev_proplist(0);
1318
1319 my $url = $rp->{'svn:sync-from-url'} or die $err . "url\n";
1320 $url =~ m{^[a-z\+]+://} or
1321 die "doesn't look right - svn:sync-from-url is '$url'\n";
1322
1323 my $uuid = $rp->{'svn:sync-from-uuid'} or die $err . "uuid\n";
1324 $uuid =~ m{^[0-9a-f\-]{30,}$} or
1325 die "doesn't look right - svn:sync-from-uuid is '$uuid'\n";
1326
1327 my $section = "svn-remote.$self->{repo_id}";
1328 tmp_config('--add', "$section.svnsync-uuid", $uuid);
1329 tmp_config('--add', "$section.svnsync-url", $url);
1330 return $self->{svnsync} = { url => $url, uuid => $uuid };
1331}
1332
26a62d57
EW
1333# this allows us to memoize our SVN::Ra UUID locally and avoid a
1334# remote lookup (useful for 'git svn log').
1335sub ra_uuid {
1336 my ($self) = @_;
1337 unless ($self->{ra_uuid}) {
1338 my $key = "svn-remote.$self->{repo_id}.uuid";
1339 my $uuid = eval { tmp_config('--get', $key) };
1340 if (!$@ && $uuid && $uuid =~ /^([a-f\d\-]{30,})$/) {
1341 $self->{ra_uuid} = $uuid;
1342 } else {
1343 die "ra_uuid called without URL\n" unless $self->{url};
1344 $self->{ra_uuid} = $self->ra->get_uuid;
1345 tmp_config('--add', $key, $self->{ra_uuid});
1346 }
1347 }
1348 $self->{ra_uuid};
1349}
1350
9b981fc6
EW
1351sub ra {
1352 my ($self) = shift;
8a49ee97 1353 my $ra = Git::SVN::Ra->new($self->{url});
91b03282
EW
1354 if ($self->use_svm_props && !$self->{svm}) {
1355 if ($self->no_metadata) {
97ae0911
EW
1356 die "Can't have both 'noMetadata' and ",
1357 "'useSvmProps' options set!\n";
62e349d2
EW
1358 } elsif ($self->use_svnsync_props) {
1359 die "Can't have both 'useSvnsyncProps' and ",
1360 "'useSvmProps' options set!\n";
91b03282 1361 }
26a62d57 1362 $ra = $self->_set_svm_vars($ra);
8a49ee97
EW
1363 $self->{-want_revprops} = 1;
1364 }
1365 $ra;
9b981fc6
EW
1366}
1367
15710b6f
EW
1368sub rel_path {
1369 my ($self) = @_;
1370 my $repos_root = $self->ra->{repos_root};
1371 return $self->{path} if ($self->{url} eq $repos_root);
0b59451c
EW
1372 my $url = $self->{url} .
1373 (length $self->{path} ? "/$self->{path}" : $self->{path});
1374 $url =~ s!^\Q$repos_root\E(?:/+|$)!!g;
1375 $url;
15710b6f
EW
1376}
1377
9b981fc6
EW
1378sub traverse_ignore {
1379 my ($self, $fh, $path, $r) = @_;
1380 $path =~ s#^/+##g;
5d3b7cd5
EW
1381 my $ra = $self->ra;
1382 my ($dirent, undef, $props) = $ra->get_dir($path, $r);
9b981fc6 1383 my $p = $path;
102a0a2d 1384 $p =~ s#^\Q$self->{path}\E(/|$)##;
9b981fc6
EW
1385 print $fh length $p ? "\n# $p\n" : "\n# /\n";
1386 if (my $s = $props->{'svn:ignore'}) {
1387 $s =~ s/[\r\n]+/\n/g;
1388 chomp $s;
1389 if (length $p == 0) {
1390 $s =~ s#\n#\n/$p#g;
1391 print $fh "/$s\n";
1392 } else {
1393 $s =~ s#\n#\n/$p/#g;
1394 print $fh "/$p/$s\n";
1395 }
1396 }
1397 foreach (sort keys %$dirent) {
0dc03d6a 1398 next if $dirent->{$_}->{kind} != $SVN::Node::dir;
9b981fc6
EW
1399 $self->traverse_ignore($fh, "$path/$_", $r);
1400 }
1401}
1402
3ebe8df7
EW
1403sub last_rev { ($_[0]->last_rev_commit)[0] }
1404sub last_commit { ($_[0]->last_rev_commit)[1] }
1405
9b981fc6
EW
1406# returns the newest SVN revision number and newest commit SHA1
1407sub last_rev_commit {
1408 my ($self) = @_;
1409 if (defined $self->{last_rev} && defined $self->{last_commit}) {
1410 return ($self->{last_rev}, $self->{last_commit});
1411 }
d2866f9e 1412 my $c = ::verify_ref($self->refname.'^0');
91b03282 1413 if ($c && !$self->use_svm_props && !$self->no_metadata) {
d2866f9e 1414 my $rev = (::cmt_metadata($c))[1];
9b981fc6
EW
1415 if (defined $rev) {
1416 ($self->{last_rev}, $self->{last_commit}) = ($rev, $c);
1417 return ($rev, $c);
1418 }
1419 }
26a62d57
EW
1420 my $db_path = $self->db_path;
1421 unless (-e $db_path) {
1422 ($self->{last_rev}, $self->{last_commit}) = (undef, undef);
1423 return (undef, undef);
1424 }
9b981fc6
EW
1425 my $offset = -41; # from tail
1426 my $rl;
26a62d57 1427 open my $fh, '<', $db_path or croak "$db_path not readable: $!\n";
ce4b4af7
EW
1428 sysseek($fh, $offset, 2); # don't care for errors
1429 sysread($fh, $rl, 41) == 41 or return (undef, undef);
9b981fc6 1430 chomp $rl;
ce4b4af7 1431 while (('0' x40) eq $rl && sysseek($fh, 0, 1) != 0) {
9b981fc6 1432 $offset -= 41;
ce4b4af7
EW
1433 sysseek($fh, $offset, 2); # don't care for errors
1434 sysread($fh, $rl, 41) == 41 or return (undef, undef);
9b981fc6
EW
1435 chomp $rl;
1436 }
91b03282 1437 if ($c && $c ne $rl) {
26a62d57 1438 die "$db_path and ", $self->refname,
9c93fee5
EW
1439 " inconsistent!:\n$c != $rl\n";
1440 }
ce4b4af7 1441 my $rev = sysseek($fh, 0, 1) or croak $!;
9b981fc6
EW
1442 $rev = ($rev - 41) / 41;
1443 close $fh or croak $!;
1444 ($self->{last_rev}, $self->{last_commit}) = ($rev, $c);
1445 return ($rev, $c);
1446}
1447
3ebe8df7
EW
1448sub get_fetch_range {
1449 my ($self, $min, $max) = @_;
1450 $max ||= $self->ra->get_latest_revnum;
9c93fee5 1451 $min ||= $self->rev_db_max;
3ebe8df7 1452 (++$min, $max);
9b981fc6
EW
1453}
1454
8a49ee97 1455sub tmp_config {
93f2689c 1456 my (@args) = @_;
b7e5348c
EW
1457 my $old_def_config = "$ENV{GIT_DIR}/svn/config";
1458 my $config = "$ENV{GIT_DIR}/svn/.metadata";
1459 if (-e $old_def_config && ! -e $config) {
1460 rename $old_def_config, $config or
1461 die "Failed rename $old_def_config => $config: $!\n";
1462 }
8a49ee97 1463 my $old_config = $ENV{GIT_CONFIG};
93f2689c 1464 $ENV{GIT_CONFIG} = $config;
8a49ee97 1465 $@ = undef;
b4d57e5e
EW
1466 my @ret = eval {
1467 unless (-f $config) {
1468 mkfile($config);
1469 open my $fh, '>', $config or
1470 die "Can't open $config: $!\n";
1471 print $fh "; This file is used internally by ",
1472 "git-svn\n" or die
1473 "Couldn't write to $config: $!\n";
1474 print $fh "; You should not have to edit it\n" or
1475 die "Couldn't write to $config: $!\n";
1476 close $fh or die "Couldn't close $config: $!\n";
1477 }
1478 command('config', @args);
1479 };
8a49ee97
EW
1480 my $err = $@;
1481 if (defined $old_config) {
1482 $ENV{GIT_CONFIG} = $old_config;
1483 } else {
1484 delete $ENV{GIT_CONFIG};
1485 }
1486 die $err if $err;
1487 wantarray ? @ret : $ret[0];
1488}
1489
9b981fc6
EW
1490sub tmp_index_do {
1491 my ($self, $sub) = @_;
1492 my $old_index = $ENV{GIT_INDEX_FILE};
1493 $ENV{GIT_INDEX_FILE} = $self->{index};
8a49ee97 1494 $@ = undef;
b4d57e5e
EW
1495 my @ret = eval {
1496 my ($dir, $base) = ($self->{index} =~ m#^(.*?)/?([^/]+)$#);
1497 mkpath([$dir]) unless -d $dir;
1498 &$sub;
1499 };
8a49ee97
EW
1500 my $err = $@;
1501 if (defined $old_index) {
9b981fc6
EW
1502 $ENV{GIT_INDEX_FILE} = $old_index;
1503 } else {
1504 delete $ENV{GIT_INDEX_FILE};
1505 }
8a49ee97 1506 die $err if $err;
9b981fc6
EW
1507 wantarray ? @ret : $ret[0];
1508}
1509
1510sub assert_index_clean {
1511 my ($self, $treeish) = @_;
1512
1513 $self->tmp_index_do(sub {
1514 command_noisy('read-tree', $treeish) unless -e $self->{index};
1515 my $x = command_oneline('write-tree');
1516 my ($y) = (command(qw/cat-file commit/, $treeish) =~
1517 /^tree ($::sha1)/mo);
e8d120bd
EW
1518 return if $y eq $x;
1519
1520 warn "Index mismatch: $y != $x\nrereading $treeish\n";
1521 unlink $self->{index} or die "unlink $self->{index}: $!\n";
1522 command_noisy('read-tree', $treeish);
9b981fc6
EW
1523 $x = command_oneline('write-tree');
1524 if ($y ne $x) {
1525 ::fatal "trees ($treeish) $y != $x\n",
1526 "Something is seriously wrong...\n";
1527 }
1528 });
1529}
1530
1531sub get_commit_parents {
0af9c9f9 1532 my ($self, $log_entry) = @_;
9b981fc6 1533 my (%seen, @ret, @tmp);
0af9c9f9
EW
1534 # legacy support for 'set-tree'; this is only used by set_tree_cb:
1535 if (my $ip = $self->{inject_parents}) {
1536 if (my $commit = delete $ip->{$log_entry->{revision}}) {
1537 push @tmp, $commit;
9b981fc6
EW
1538 }
1539 }
d2866f9e 1540 if (my $cur = ::verify_ref($self->refname.'^0')) {
9b981fc6
EW
1541 push @tmp, $cur;
1542 }
44320b9e 1543 push @tmp, $_ foreach (@{$log_entry->{parents}}, @tmp);
9b981fc6
EW
1544 while (my $p = shift @tmp) {
1545 next if $seen{$p};
1546 $seen{$p} = 1;
1547 push @ret, $p;
1548 # MAXPARENT is defined to 16 in commit-tree.c:
1549 last if @ret >= 16;
1550 }
1551 if (@tmp) {
44320b9e 1552 die "r$log_entry->{revision}: No room for parents:\n\t",
9b981fc6
EW
1553 join("\n\t", @tmp), "\n";
1554 }
1555 @ret;
1556}
1557
aea736cc
EW
1558sub rewrite_root {
1559 my ($self) = @_;
1560 return $self->{-rewrite_root} if exists $self->{-rewrite_root};
1561 my $k = "svn-remote.$self->{repo_id}.rewriteRoot";
1562 my $rwr = eval { command_oneline(qw/config --get/, $k) };
1563 if ($rwr) {
1564 $rwr =~ s#/+$##;
1565 if ($rwr !~ m#^[a-z\+]+://#) {
1566 die "$rwr is not a valid URL (key: $k)\n";
1567 }
1568 }
1569 $self->{-rewrite_root} = $rwr;
1570}
1571
1572sub metadata_url {
1573 my ($self) = @_;
1574 ($self->rewrite_root || $self->{url}) .
1575 (length $self->{path} ? '/' . $self->{path} : '');
1576}
1577
706587fc 1578sub full_url {
9b981fc6 1579 my ($self) = @_;
5d3b7cd5 1580 $self->{url} . (length $self->{path} ? '/' . $self->{path} : '');
9b981fc6
EW
1581}
1582
1583sub do_git_commit {
0af9c9f9 1584 my ($self, $log_entry) = @_;
8a603774
EW
1585 my $lr = $self->last_rev;
1586 if (defined $lr && $lr >= $log_entry->{revision}) {
1587 die "Last fetched revision of ", $self->refname,
1588 " was r$lr, but we are about to fetch: ",
1589 "r$log_entry->{revision}!\n";
1590 }
44320b9e
EW
1591 if (my $c = $self->rev_db_get($log_entry->{revision})) {
1592 croak "$log_entry->{revision} = $c already exists! ",
9b981fc6
EW
1593 "Why are we refetching it?\n";
1594 }
db03cd24
EW
1595 $ENV{GIT_AUTHOR_NAME} = $ENV{GIT_COMMITTER_NAME} = $log_entry->{name};
1596 $ENV{GIT_AUTHOR_EMAIL} = $ENV{GIT_COMMITTER_EMAIL} =
1597 $log_entry->{email};
44320b9e 1598 $ENV{GIT_AUTHOR_DATE} = $ENV{GIT_COMMITTER_DATE} = $log_entry->{date};
9b981fc6 1599
44320b9e 1600 my $tree = $log_entry->{tree};
9b981fc6
EW
1601 if (!defined $tree) {
1602 $tree = $self->tmp_index_do(sub {
1603 command_oneline('write-tree') });
1604 }
1605 die "Tree is not a valid sha1: $tree\n" if $tree !~ /^$::sha1$/o;
1606
1607 my @exec = ('git-commit-tree', $tree);
0af9c9f9 1608 foreach ($self->get_commit_parents($log_entry)) {
9b981fc6
EW
1609 push @exec, '-p', $_;
1610 }
1611 defined(my $pid = open3(my $msg_fh, my $out_fh, '>&STDERR', @exec))
1612 or croak $!;
44320b9e 1613 print $msg_fh $log_entry->{log} or croak $!;
91b03282 1614 unless ($self->no_metadata) {
8a49ee97
EW
1615 print $msg_fh "\ngit-svn-id: $log_entry->{metadata}\n"
1616 or croak $!;
9760adcc 1617 }
9b981fc6
EW
1618 $msg_fh->flush == 0 or croak $!;
1619 close $msg_fh or croak $!;
1620 chomp(my $commit = do { local $/; <$out_fh> });
1621 close $out_fh or croak $!;
1622 waitpid $pid, 0;
1623 croak $? if $?;
1624 if ($commit !~ /^$::sha1$/o) {
1625 die "Failed to commit, invalid sha1: $commit\n";
1626 }
1627
373274f9 1628 $self->rev_db_set($log_entry->{revision}, $commit, 1);
9b981fc6 1629
44320b9e 1630 $self->{last_rev} = $log_entry->{revision};
9b981fc6 1631 $self->{last_commit} = $commit;
8a49ee97
EW
1632 print "r$log_entry->{revision}";
1633 if (defined $log_entry->{svm_revision}) {
1634 print " (\@$log_entry->{svm_revision})";
26a62d57
EW
1635 $self->rev_db_set($log_entry->{svm_revision}, $commit,
1636 0, $self->svm_uuid);
8a49ee97
EW
1637 }
1638 print " = $commit ($self->{ref_id})\n";
ecc712dd
EW
1639 if (defined $_repack && (--$_repack_nr == 0)) {
1640 $_repack_nr = $_repack;
1641 # repack doesn't use any arguments with spaces in them, does it?
1642 print "Running git repack $_repack_flags ...\n";
1643 command_noisy('repack', split(/\s+/, $_repack_flags));
1644 print "Done repacking\n";
1645 }
9b981fc6
EW
1646 return $commit;
1647}
1648
fbcc1737
EW
1649sub match_paths {
1650 my ($self, $paths, $r) = @_;
4e9f6cc7 1651 return 1 if $self->{path} eq '';
d542aedb
EW
1652 if (my $path = $paths->{"/$self->{path}"}) {
1653 return ($path->{action} eq 'D') ? 0 : 1;
1654 }
4e9f6cc7 1655 $self->{path_regex} ||= qr/^\/\Q$self->{path}\E\//;
fbcc1737
EW
1656 if (grep /$self->{path_regex}/, keys %$paths) {
1657 return 1;
1658 }
1659 my $c = '';
1660 foreach (split m#/#, $self->{path}) {
1661 $c .= "/$_";
74a81227
EW
1662 next unless ($paths->{$c} &&
1663 ($paths->{$c}->{action} =~ /^[AR]$/));
e518192f
EW
1664 if ($self->ra->check_path($self->{path}, $r) ==
1665 $SVN::Node::dir) {
fbcc1737
EW
1666 return 1;
1667 }
1668 }
1669 return 0;
1670}
1671
15710b6f
EW
1672sub find_parent_branch {
1673 my ($self, $paths, $rev) = @_;
91b03282 1674 return undef unless $self->follow_parent;
e5a0b240 1675 unless (defined $paths) {
c7eba716
EW
1676 my $err_handler = $SVN::Error::handler;
1677 $SVN::Error::handler = \&Git::SVN::Ra::skip_unknown_revs;
d4eff2bd
EW
1678 $self->ra->get_log([$self->{path}], $rev, $rev, 0, 1, 1, sub {
1679 $paths =
1680 Git::SVN::Ra::dup_changed_paths($_[0]) });
c7eba716 1681 $SVN::Error::handler = $err_handler;
e5a0b240
EW
1682 }
1683 return undef unless defined $paths;
15710b6f
EW
1684
1685 # look for a parent from another branch:
7f578c55
EW
1686 my @b_path_components = split m#/#, $self->rel_path;
1687 my @a_path_components;
1688 my $i;
1689 while (@b_path_components) {
1690 $i = $paths->{'/'.join('/', @b_path_components)};
74a81227 1691 last if $i && defined $i->{copyfrom_path};
7f578c55
EW
1692 unshift(@a_path_components, pop(@b_path_components));
1693 }
74a81227
EW
1694 return undef unless defined $i && defined $i->{copyfrom_path};
1695 my $branch_from = $i->{copyfrom_path};
7f578c55
EW
1696 if (@a_path_components) {
1697 print STDERR "branch_from: $branch_from => ";
1698 $branch_from .= '/'.join('/', @a_path_components);
1699 print STDERR $branch_from, "\n";
1700 }
3ebe8df7 1701 my $r = $i->{copyfrom_rev};
15710b6f
EW
1702 my $repos_root = $self->ra->{repos_root};
1703 my $url = $self->ra->{url};
1704 my $new_url = $repos_root . $branch_from;
1705 print STDERR "Found possible branch point: ",
1706 "$new_url => ", $self->full_url, ", $r\n";
1707 $branch_from =~ s#^/##;
a8ae2623 1708 my $gs = Git::SVN->find_by_url($new_url, $repos_root, $branch_from);
15710b6f 1709 unless ($gs) {
ce2a0f2f
EW
1710 my $ref_id = $self->{ref_id};
1711 $ref_id =~ s/\@\d+$//;
1712 $ref_id .= "\@$r";
15710b6f
EW
1713 # just grow a tail if we're not unique enough :x
1714 $ref_id .= '-' while find_ref($ref_id);
ce2a0f2f 1715 print STDERR "Initializing parent: $ref_id\n";
d8115c51 1716 $gs = Git::SVN->init($new_url, '', $ref_id, $ref_id, 1);
15710b6f
EW
1717 }
1718 my ($r0, $parent) = $gs->find_rev_before($r, 1);
91b03282 1719 if (!defined $r0 || !defined $parent) {
d627de6b
EW
1720 my ($base, $head) = parse_revision_argument(0, $r);
1721 if ($base <= $r) {
1722 $gs->fetch($base, $r);
1723 }
15710b6f
EW
1724 ($r0, $parent) = $gs->last_rev_commit;
1725 }
ef70de96 1726 if (defined $r0 && defined $parent) {
15710b6f 1727 print STDERR "Found branch parent: ($self->{ref_id}) $parent\n";
15710b6f
EW
1728 my $ed;
1729 if ($self->ra->can_do_switch) {
2e5e2480 1730 $self->assert_index_clean($parent);
8b8fc068 1731 print STDERR "Following parent with do_switch\n";
15710b6f 1732 # do_switch works with svn/trunk >= r22312, but that
2b27f6c8 1733 # is not included with SVN 1.4.3 (the latest version
15710b6f
EW
1734 # at the moment), so we can't rely on it
1735 $self->{last_commit} = $parent;
1736 $ed = SVN::Git::Fetcher->new($self);
8a603774 1737 $gs->ra->gs_do_switch($r0, $rev, $gs,
15710b6f
EW
1738 $self->full_url, $ed)
1739 or die "SVN connection failed somewhere...\n";
1740 } else {
8b8fc068 1741 print STDERR "Following parent with do_update\n";
15710b6f 1742 $ed = SVN::Git::Fetcher->new($self);
8a603774 1743 $self->ra->gs_do_update($rev, $rev, $self, $ed)
15710b6f
EW
1744 or die "SVN connection failed somewhere...\n";
1745 }
f7c3fc4a 1746 print STDERR "Successfully followed parent\n";
15710b6f
EW
1747 return $self->make_log_entry($rev, [$parent], $ed);
1748 }
15710b6f
EW
1749 return undef;
1750}
1751
9b981fc6 1752sub do_fetch {
706587fc 1753 my ($self, $paths, $rev) = @_;
15710b6f 1754 my $ed;
9b981fc6 1755 my ($last_rev, @parents);
b9dffd8c
EW
1756 if (my $lc = $self->last_commit) {
1757 # we can have a branch that was deleted, then re-added
1758 # under the same name but copied from another path, in
1759 # which case we'll have multiple parents (we don't
1760 # want to break the original ref, nor lose copypath info):
1761 if (my $log_entry = $self->find_parent_branch($paths, $rev)) {
1762 push @{$log_entry->{parents}}, $lc;
1763 return $log_entry;
1764 }
15710b6f 1765 $ed = SVN::Git::Fetcher->new($self);
9b981fc6 1766 $last_rev = $self->{last_rev};
b9dffd8c
EW
1767 $ed->{c} = $lc;
1768 @parents = ($lc);
9b981fc6
EW
1769 } else {
1770 $last_rev = $rev;
15710b6f
EW
1771 if (my $log_entry = $self->find_parent_branch($paths, $rev)) {
1772 return $log_entry;
1773 }
1774 $ed = SVN::Git::Fetcher->new($self);
9b981fc6 1775 }
8a603774 1776 unless ($self->ra->gs_do_update($last_rev, $rev, $self, $ed)) {
9b981fc6
EW
1777 die "SVN connection failed somewhere...\n";
1778 }
1779 $self->make_log_entry($rev, \@parents, $ed);
1780}
1781
97f6987a
EW
1782sub get_untracked {
1783 my ($self, $ed) = @_;
1784 my @out;
1785 my $h = $ed->{empty};
9b981fc6
EW
1786 foreach (sort keys %$h) {
1787 my $act = $h->{$_} ? '+empty_dir' : '-empty_dir';
97f6987a 1788 push @out, " $act: " . uri_encode($_);
9b981fc6
EW
1789 warn "W: $act: $_\n";
1790 }
1791 foreach my $t (qw/dir_prop file_prop/) {
97f6987a 1792 $h = $ed->{$t} or next;
9b981fc6
EW
1793 foreach my $path (sort keys %$h) {
1794 my $ppath = $path eq '' ? '.' : $path;
1795 foreach my $prop (sort keys %{$h->{$path}}) {
1ce255dc 1796 next if $SKIP_PROP{$prop};
9b981fc6 1797 my $v = $h->{$path}->{$prop};
97f6987a
EW
1798 my $t_ppath_prop = "$t: " .
1799 uri_encode($ppath) . ' ' .
1800 uri_encode($prop);
9b981fc6 1801 if (defined $v) {
97f6987a
EW
1802 push @out, " +$t_ppath_prop " .
1803 uri_encode($v);
9b981fc6 1804 } else {
97f6987a 1805 push @out, " -$t_ppath_prop";
9b981fc6
EW
1806 }
1807 }
1808 }
1809 }
1810 foreach my $t (qw/absent_file absent_directory/) {
97f6987a 1811 $h = $ed->{$t} or next;
9b981fc6
EW
1812 foreach my $parent (sort keys %$h) {
1813 foreach my $path (sort @{$h->{$parent}}) {
97f6987a
EW
1814 push @out, " $t: " .
1815 uri_encode("$parent/$path");
9b981fc6
EW
1816 warn "W: $t: $parent/$path ",
1817 "Insufficient permissions?\n";
1818 }
1819 }
1820 }
97f6987a 1821 \@out;
9b981fc6
EW
1822}
1823
1c8443b0
EW
1824sub parse_svn_date {
1825 my $date = shift || return '+0000 1970-01-01 00:00:00';
1826 my ($Y,$m,$d,$H,$M,$S) = ($date =~ /^(\d{4})\-(\d\d)\-(\d\d)T
1827 (\d\d)\:(\d\d)\:(\d\d).\d+Z$/x) or
1828 croak "Unable to parse date: $date\n";
1829 "+0000 $Y-$m-$d $H:$M:$S";
1830}
1831
1832sub check_author {
1833 my ($author) = @_;
1834 if (!defined $author || length $author == 0) {
1835 $author = '(no author)';
1836 }
1837 if (defined $::_authors && ! defined $::users{$author}) {
1838 die "Author: $author not defined in $::_authors file\n";
1839 }
1840 $author;
1841}
1842
9b981fc6 1843sub make_log_entry {
97f6987a
EW
1844 my ($self, $rev, $parents, $ed) = @_;
1845 my $untracked = $self->get_untracked($ed);
1846
9b981fc6 1847 open my $un, '>>', "$self->{dir}/unhandled.log" or croak $!;
97f6987a
EW
1848 print $un "r$rev\n" or croak $!;
1849 print $un $_, "\n" foreach @$untracked;
1850 my %log_entry = ( parents => $parents || [], revision => $rev,
1851 log => '');
fbcc1737 1852
8a49ee97 1853 my $headrev;
fbcc1737 1854 my $logged = delete $self->{logged_rev_props};
8a49ee97 1855 if (!$logged || $self->{-want_revprops}) {
fbcc1737
EW
1856 my $rp = $self->ra->rev_proplist($rev);
1857 foreach (sort keys %$rp) {
1858 my $v = $rp->{$_};
1859 if (/^svn:(author|date|log)$/) {
1860 $log_entry{$1} = $v;
8a49ee97
EW
1861 } elsif ($_ eq 'svm:headrev') {
1862 $headrev = $v;
fbcc1737
EW
1863 } else {
1864 print $un " rev_prop: ", uri_encode($_), ' ',
1865 uri_encode($v), "\n";
1866 }
9b981fc6 1867 }
fbcc1737
EW
1868 } else {
1869 map { $log_entry{$_} = $logged->{$_} } keys %$logged;
9b981fc6
EW
1870 }
1871 close $un or croak $!;
97f6987a 1872
9b981fc6 1873 $log_entry{date} = parse_svn_date($log_entry{date});
9b981fc6 1874 $log_entry{log} .= "\n";
db03cd24
EW
1875 my $author = $log_entry{author} = check_author($log_entry{author});
1876 my ($name, $email) = defined $::users{$author} ? @{$::users{$author}}
1877 : ($author, undef);
91b03282 1878 if (defined $headrev && $self->use_svm_props) {
aea736cc
EW
1879 if ($self->rewrite_root) {
1880 die "Can't have both 'useSvmProps' and 'rewriteRoot' ",
1881 "options set!\n";
1882 }
8a49ee97 1883 my ($uuid, $r) = $headrev =~ m{^([a-f\d\-]{30,}):(\d+)$};
befc9adc
EW
1884 # we don't want "SVM: initializing mirror for junk" ...
1885 return undef if $r == 0;
1886 my $svm = $self->svm;
1887 if ($uuid ne $svm->{uuid}) {
8a49ee97 1888 die "UUID mismatch on SVM path:\n",
befc9adc 1889 "expected: $svm->{uuid}\n",
8a49ee97
EW
1890 " got: $uuid\n";
1891 }
befc9adc
EW
1892 my $full_url = $self->full_url;
1893 $full_url =~ s#^\Q$svm->{replace}\E(/|$)#$svm->{source}$1# or
1894 die "Failed to replace '$svm->{replace}' with ",
1895 "'$svm->{source}' in $full_url\n";
18ea92bd
SV
1896 # throw away username for storing in records
1897 remove_username($full_url);
8a49ee97
EW
1898 $log_entry{metadata} = "$full_url\@$r $uuid";
1899 $log_entry{svm_revision} = $r;
db03cd24 1900 $email ||= "$author\@$uuid"
62e349d2
EW
1901 } elsif ($self->use_svnsync_props) {
1902 my $full_url = $self->svnsync->{url};
1903 $full_url .= "/$self->{path}" if length $self->{path};
ce118739 1904 remove_username($full_url);
62e349d2
EW
1905 my $uuid = $self->svnsync->{uuid};
1906 $log_entry{metadata} = "$full_url\@$rev $uuid";
1907 $email ||= "$author\@$uuid"
8a49ee97 1908 } else {
ce118739
AR
1909 my $url = $self->metadata_url;
1910 remove_username($url);
1911 $log_entry{metadata} = "$url\@$rev " .
26a62d57 1912 $self->ra->get_uuid;
db03cd24 1913 $email ||= "$author\@" . $self->ra->get_uuid;
8a49ee97 1914 }
db03cd24
EW
1915 $log_entry{name} = $name;
1916 $log_entry{email} = $email;
9b981fc6
EW
1917 \%log_entry;
1918}
1919
1920sub fetch {
3ebe8df7 1921 my ($self, $min_rev, $max_rev, @parents) = @_;
9b981fc6 1922 my ($last_rev, $last_commit) = $self->last_rev_commit;
3ebe8df7 1923 my ($base, $head) = $self->get_fetch_range($min_rev, $max_rev);
e518192f 1924 $self->ra->gs_fetch_loop_common($base, $head, [$self]);
9b981fc6
EW
1925}
1926
1927sub set_tree_cb {
1928 my ($self, $log_entry, $tree, $rev, $date, $author) = @_;
490f49ea
EW
1929 $self->{inject_parents} = { $rev => $tree };
1930 $self->fetch(undef, undef);
9b981fc6
EW
1931}
1932
1933sub set_tree {
1934 my ($self, $tree) = (shift, shift);
1ce255dc 1935 my $log_entry = ::get_commit_entry($tree);
9b981fc6
EW
1936 unless ($self->{last_rev}) {
1937 fatal("Must have an existing revision to commit\n");
1938 }
61395354
EW
1939 my %ed_opts = ( r => $self->{last_rev},
1940 log => $log_entry->{log},
1941 ra => $self->ra,
1942 tree_a => $self->{last_commit},
1943 tree_b => $tree,
1944 editor_cb => sub {
1945 $self->set_tree_cb($log_entry, $tree, @_) },
1946 svn_path => $self->{path} );
1947 if (!SVN::Git::Editor->new(\%ed_opts)->apply_diff) {
9b981fc6
EW
1948 print "No changes\nr$self->{last_rev} = $tree\n";
1949 }
9b981fc6
EW
1950}
1951
f0ecca10
EW
1952sub rebuild {
1953 my ($self) = @_;
26a62d57 1954 my $db_path = $self->db_path;
d6d3346b
EW
1955 return if (-e $db_path && ! -z $db_path);
1956 return unless ::verify_ref($self->refname.'^0');
26a62d57
EW
1957 if (-f $self->{db_root}) {
1958 rename $self->{db_root}, $db_path or die
1959 "rename $self->{db_root} => $db_path failed: $!\n";
1960 my ($dir, $base) = ($db_path =~ m#^(.*?)/?([^/]+)$#);
1961 symlink $base, $self->{db_root} or die
1962 "symlink $base => $self->{db_root} failed: $!\n";
1963 return;
1964 }
1965 print "Rebuilding $db_path ...\n";
f0ecca10
EW
1966 my ($rev_list, $ctx) = command_output_pipe("rev-list", $self->refname);
1967 my $latest;
1968 my $full_url = $self->full_url;
18ea92bd 1969 remove_username($full_url);
f0ecca10
EW
1970 my $svn_uuid;
1971 while (<$rev_list>) {
1972 chomp;
1973 my $c = $_;
1974 die "Non-SHA1: $c\n" unless $c =~ /^$::sha1$/o;
1975 my ($url, $rev, $uuid) = ::cmt_metadata($c);
18ea92bd 1976 remove_username($url);
f0ecca10
EW
1977
1978 # ignore merges (from set-tree)
1979 next if (!defined $rev || !$uuid);
1980
1981 # if we merged or otherwise started elsewhere, this is
1982 # how we break out of it
1983 if ((defined $svn_uuid && ($uuid ne $svn_uuid)) ||
1984 ($full_url && $url && ($url ne $full_url))) {
1985 next;
1986 }
1987 $latest ||= $rev;
1988 $svn_uuid ||= $uuid;
1989
1990 $self->rev_db_set($rev, $c);
1991 print "r$rev = $c\n";
1992 }
1993 command_close_pipe($rev_list, $ctx);
26a62d57 1994 print "Done rebuilding $db_path\n";
f0ecca10
EW
1995}
1996
9b981fc6
EW
1997# rev_db:
1998# Tie::File seems to be prone to offset errors if revisions get sparse,
1999# it's not that fast, either. Tie::File is also not in Perl 5.6. So
2000# one of my favorite modules is out :< Next up would be one of the DBM
2001# modules, but I'm not sure which is most portable... So I'll just
2002# go with something that's plain-text, but still capable of
2003# being randomly accessed. So here's my ultra-simple fixed-width
2004# database. All records are 40 characters + "\n", so it's easy to seek
2005# to a revision: (41 * rev) is the byte offset.
2006# A record of 40 0s denotes an empty revision.
2007# And yes, it's still pretty fast (faster than Tie::File).
97ae0911 2008# These files are disposable unless noMetadata or useSvmProps is set
9b981fc6 2009
26a62d57
EW
2010sub _rev_db_set {
2011 my ($fh, $rev, $commit) = @_;
2012 my $offset = $rev * 41;
2013 # assume that append is the common case:
2014 seek $fh, 0, 2 or croak $!;
2015 my $pos = tell $fh;
2016 if ($pos < $offset) {
2017 for (1 .. (($offset - $pos) / 41)) {
2018 print $fh (('0' x 40),"\n") or croak $!;
2019 }
2020 }
2021 seek $fh, $offset, 0 or croak $!;
2022 print $fh $commit,"\n" or croak $!;
2023}
2024
2025sub mkfile {
2026 my ($path) = @_;
2027 unless (-e $path) {
2028 my ($dir, $base) = ($path =~ m#^(.*?)/?([^/]+)$#);
2029 mkpath([$dir]) unless -d $dir;
2030 open my $fh, '>>', $path or die "Couldn't create $path: $!\n";
2031 close $fh or die "Couldn't close (create) $path: $!\n";
2032 }
2033}
2034
9b981fc6 2035sub rev_db_set {
26a62d57
EW
2036 my ($self, $rev, $commit, $update_ref, $uuid) = @_;
2037 length $commit == 40 or die "arg3 must be a full SHA1 hexsum\n";
2038 my $db = $self->db_path($uuid);
2039 my $db_lock = "$db.lock";
373274f9
EW
2040 my $sig;
2041 if ($update_ref) {
2042 $SIG{INT} = $SIG{HUP} = $SIG{TERM} = $SIG{ALRM} = $SIG{PIPE} =
2043 $SIG{USR1} = $SIG{USR2} = sub { $sig = $_[0] };
2044 }
26a62d57
EW
2045 mkfile($db);
2046
373274f9 2047 $LOCKFILES{$db_lock} = 1;
97ae0911 2048 my $sync;
97ae0911
EW
2049 # both of these options make our .rev_db file very, very important
2050 # and we can't afford to lose it because rebuild() won't work
2051 if ($self->use_svm_props || $self->no_metadata) {
2052 $sync = 1;
373274f9 2053 copy($db, $db_lock) or die "rev_db_set(@_): ",
26a62d57 2054 "Failed to copy: ",
373274f9
EW
2055 "$db => $db_lock ($!)\n";
2056 } else {
2057 rename $db, $db_lock or die "rev_db_set(@_): ",
26a62d57 2058 "Failed to rename: ",
373274f9
EW
2059 "$db => $db_lock ($!)\n";
2060 }
26a62d57
EW
2061 open my $fh, '+<', $db_lock or die "Couldn't open $db_lock: $!\n";
2062 _rev_db_set($fh, $rev, $commit);
97ae0911
EW
2063 if ($sync) {
2064 $fh->flush or die "Couldn't flush $db_lock: $!\n";
2065 $fh->sync or die "Couldn't sync $db_lock: $!\n";
2066 }
9b981fc6 2067 close $fh or croak $!;
373274f9 2068 if ($update_ref) {
1e889ef3 2069 $_head = $self;
373274f9
EW
2070 command_noisy('update-ref', '-m', "r$rev",
2071 $self->refname, $commit);
2072 }
2073 rename $db_lock, $db or die "rev_db_set(@_): ", "Failed to rename: ",
2074 "$db_lock => $db ($!)\n";
2075 delete $LOCKFILES{$db_lock};
2076 if ($update_ref) {
2077 $SIG{INT} = $SIG{HUP} = $SIG{TERM} = $SIG{ALRM} = $SIG{PIPE} =
2078 $SIG{USR1} = $SIG{USR2} = 'DEFAULT';
2079 kill $sig, $$ if defined $sig;
2080 }
9b981fc6
EW
2081}
2082
9c93fee5
EW
2083sub rev_db_max {
2084 my ($self) = @_;
d6d3346b 2085 $self->rebuild;
26a62d57
EW
2086 my $db_path = $self->db_path;
2087 my @stat = stat $db_path or return 0;
2088 ($stat[7] % 41) == 0 or die "$db_path inconsistent size: $stat[7]\n";
9c93fee5
EW
2089 my $max = $stat[7] / 41;
2090 (($max > 0) ? $max - 1 : 0);
2091}
2092
9b981fc6 2093sub rev_db_get {
26a62d57 2094 my ($self, $rev, $uuid) = @_;
9b981fc6
EW
2095 my $ret;
2096 my $offset = $rev * 41;
26a62d57
EW
2097 my $db_path = $self->db_path($uuid);
2098 return undef unless -e $db_path;
2099 open my $fh, '<', $db_path or croak $!;
ce4b4af7
EW
2100 if (sysseek($fh, $offset, 0) == $offset) {
2101 my $read = sysread($fh, $ret, 40);
2102 $ret = undef if ($read != 40 || $ret eq ('0'x40));
9b981fc6
EW
2103 }
2104 close $fh or croak $!;
2105 $ret;
2106}
2107
15710b6f
EW
2108sub find_rev_before {
2109 my ($self, $rev, $eq_ok) = @_;
2110 --$rev unless $eq_ok;
2111 while ($rev > 0) {
2112 if (my $c = $self->rev_db_get($rev)) {
2113 return ($rev, $c);
2114 }
2115 --$rev;
2116 }
2117 return (undef, undef);
2118}
2119
9b981fc6 2120sub _new {
706587fc
EW
2121 my ($class, $repo_id, $ref_id, $path) = @_;
2122 unless (defined $repo_id && length $repo_id) {
2123 $repo_id = $Git::SVN::default_repo_id;
2124 }
2125 unless (defined $ref_id && length $ref_id) {
8b8fc068 2126 $_[2] = $ref_id = $Git::SVN::default_ref_id;
706587fc
EW
2127 }
2128 $_[1] = $repo_id = sanitize_remote_name($repo_id);
2129 my $dir = "$ENV{GIT_DIR}/svn/$ref_id";
2130 $_[3] = $path = '' unless (defined $path);
b4d57e5e 2131 mkpath(["$ENV{GIT_DIR}/svn"]);
26a62d57
EW
2132 bless {
2133 ref_id => $ref_id, dir => $dir, index => "$dir/index",
8a49ee97 2134 path => $path, config => "$ENV{GIT_DIR}/svn/config",
26a62d57
EW
2135 db_root => "$dir/.rev_db", repo_id => $repo_id }, $class;
2136}
2137
2138sub db_path {
2139 my ($self, $uuid) = @_;
2140 $uuid ||= $self->ra_uuid;
2141 "$self->{db_root}.$uuid";
9b981fc6
EW
2142}
2143
1c8443b0
EW
2144sub uri_encode {
2145 my ($f) = @_;
2146 $f =~ s#([^a-zA-Z0-9\*!\:_\./\-])#uc sprintf("%%%02x",ord($1))#eg;
2147 $f
2148}
9b981fc6 2149
18ea92bd
SV
2150sub remove_username {
2151 $_[0] =~ s{^([^:]*://)[^@]+@}{$1};
2152}
2153
d976acfd
EW
2154package Git::SVN::Prompt;
2155use strict;
2156use warnings;
2157require SVN::Core;
2158use vars qw/$_no_auth_cache $_username/;
2159
2160sub simple {
30d055aa
EW
2161 my ($cred, $realm, $default_username, $may_save, $pool) = @_;
2162 $may_save = undef if $_no_auth_cache;
2163 $default_username = $_username if defined $_username;
2164 if (defined $default_username && length $default_username) {
2165 if (defined $realm && length $realm) {
6f729591
EW
2166 print STDERR "Authentication realm: $realm\n";
2167 STDERR->flush;
30d055aa
EW
2168 }
2169 $cred->username($default_username);
2170 } else {
d976acfd 2171 username($cred, $realm, $may_save, $pool);
30d055aa
EW
2172 }
2173 $cred->password(_read_password("Password for '" .
2174 $cred->username . "': ", $realm));
2175 $cred->may_save($may_save);
2176 $SVN::_Core::SVN_NO_ERROR;
2177}
2178
d976acfd 2179sub ssl_server_trust {
30d055aa
EW
2180 my ($cred, $realm, $failures, $cert_info, $may_save, $pool) = @_;
2181 $may_save = undef if $_no_auth_cache;
6f729591 2182 print STDERR "Error validating server certificate for '$realm':\n";
30d055aa 2183 if ($failures & $SVN::Auth::SSL::UNKNOWNCA) {
6f729591 2184 print STDERR " - The certificate is not issued by a trusted ",
30d055aa
EW
2185 "authority. Use the\n",
2186 " fingerprint to validate the certificate manually!\n";
2187 }
2188 if ($failures & $SVN::Auth::SSL::CNMISMATCH) {
6f729591 2189 print STDERR " - The certificate hostname does not match.\n";
30d055aa
EW
2190 }
2191 if ($failures & $SVN::Auth::SSL::NOTYETVALID) {
6f729591 2192 print STDERR " - The certificate is not yet valid.\n";
30d055aa
EW
2193 }
2194 if ($failures & $SVN::Auth::SSL::EXPIRED) {
6f729591 2195 print STDERR " - The certificate has expired.\n";
30d055aa
EW
2196 }
2197 if ($failures & $SVN::Auth::SSL::OTHER) {
6f729591 2198 print STDERR " - The certificate has an unknown error.\n";
30d055aa 2199 }
6f729591
EW
2200 printf STDERR
2201 "Certificate information:\n".
30d055aa
EW
2202 " - Hostname: %s\n".
2203 " - Valid: from %s until %s\n".
2204 " - Issuer: %s\n".
2205 " - Fingerprint: %s\n",
2206 map $cert_info->$_, qw(hostname valid_from valid_until
6f729591 2207 issuer_dname fingerprint);
30d055aa
EW
2208 my $choice;
2209prompt:
6f729591 2210 print STDERR $may_save ?
30d055aa
EW
2211 "(R)eject, accept (t)emporarily or accept (p)ermanently? " :
2212 "(R)eject or accept (t)emporarily? ";
6f729591 2213 STDERR->flush;
30d055aa
EW
2214 $choice = lc(substr(<STDIN> || 'R', 0, 1));
2215 if ($choice =~ /^t$/i) {
2216 $cred->may_save(undef);
2217 } elsif ($choice =~ /^r$/i) {
2218 return -1;
2219 } elsif ($may_save && $choice =~ /^p$/i) {
2220 $cred->may_save($may_save);
2221 } else {
2222 goto prompt;
2223 }
2224 $cred->accepted_failures($failures);
2225 $SVN::_Core::SVN_NO_ERROR;
2226}
2227
d976acfd 2228sub ssl_client_cert {
30d055aa
EW
2229 my ($cred, $realm, $may_save, $pool) = @_;
2230 $may_save = undef if $_no_auth_cache;
6f729591
EW
2231 print STDERR "Client certificate filename: ";
2232 STDERR->flush;
30d055aa
EW
2233 chomp(my $filename = <STDIN>);
2234 $cred->cert_file($filename);
2235 $cred->may_save($may_save);
2236 $SVN::_Core::SVN_NO_ERROR;
2237}
2238
d976acfd 2239sub ssl_client_cert_pw {
30d055aa
EW
2240 my ($cred, $realm, $may_save, $pool) = @_;
2241 $may_save = undef if $_no_auth_cache;
2242 $cred->password(_read_password("Password: ", $realm));
2243 $cred->may_save($may_save);
2244 $SVN::_Core::SVN_NO_ERROR;
2245}
2246
d976acfd 2247sub username {
30d055aa
EW
2248 my ($cred, $realm, $may_save, $pool) = @_;
2249 $may_save = undef if $_no_auth_cache;
2250 if (defined $realm && length $realm) {
6f729591 2251 print STDERR "Authentication realm: $realm\n";
30d055aa
EW
2252 }
2253 my $username;
2254 if (defined $_username) {
2255 $username = $_username;
2256 } else {
6f729591
EW
2257 print STDERR "Username: ";
2258 STDERR->flush;
30d055aa
EW
2259 chomp($username = <STDIN>);
2260 }
2261 $cred->username($username);
2262 $cred->may_save($may_save);
2263 $SVN::_Core::SVN_NO_ERROR;
2264}
2265
2266sub _read_password {
2267 my ($prompt, $realm) = @_;
6f729591
EW
2268 print STDERR $prompt;
2269 STDERR->flush;
30d055aa
EW
2270 require Term::ReadKey;
2271 Term::ReadKey::ReadMode('noecho');
2272 my $password = '';
2273 while (defined(my $key = Term::ReadKey::ReadKey(0))) {
2274 last if $key =~ /[\012\015]/; # \n\r
2275 $password .= $key;
2276 }
2277 Term::ReadKey::ReadMode('restore');
6f729591
EW
2278 print STDERR "\n";
2279 STDERR->flush;
30d055aa
EW
2280 $password;
2281}
2282
d976acfd
EW
2283package main;
2284
b9c85187
EW
2285{
2286 my $kill_stupid_warnings = $SVN::Node::none.$SVN::Node::file.
2287 $SVN::Node::dir.$SVN::Node::unknown.
2288 $SVN::Node::none.$SVN::Node::file.
2289 $SVN::Node::dir.$SVN::Node::unknown.
2290 $SVN::Auth::SSL::CNMISMATCH.
2291 $SVN::Auth::SSL::NOTYETVALID.
2292 $SVN::Auth::SSL::EXPIRED.
2293 $SVN::Auth::SSL::UNKNOWNCA.
2294 $SVN::Auth::SSL::OTHER;
2295}
2296
27a1a801
EW
2297package SVN::Git::Fetcher;
2298use vars qw/@ISA/;
2299use strict;
2300use warnings;
2301use Carp qw/croak/;
2302use IO::File qw//;
90c1b15d 2303use Digest::MD5;
27a1a801
EW
2304
2305# file baton members: path, mode_a, mode_b, pool, fh, blob, base
2306sub new {
2307 my ($class, $git_svn) = @_;
2308 my $self = SVN::Delta::Editor->new;
2309 bless $self, $class;
1c8443b0 2310 $self->{c} = $git_svn->{last_commit} if exists $git_svn->{last_commit};
d2a9a87b
EW
2311 $self->{empty} = {};
2312 $self->{dir_prop} = {};
2313 $self->{file_prop} = {};
2314 $self->{absent_dir} = {};
2315 $self->{absent_file} = {};
ef3cfaad 2316 $self->{gii} = $git_svn->tmp_index_do(sub { Git::IndexInfo->new });
27a1a801
EW
2317 $self;
2318}
2319
8b8fc068
EW
2320sub set_path_strip {
2321 my ($self, $path) = @_;
4e9f6cc7 2322 $self->{path_strip} = qr/^\Q$path\E(\/|$)/ if length $path;
8b8fc068
EW
2323}
2324
d2a9a87b
EW
2325sub open_root {
2326 { path => '' };
2327}
2328
2329sub open_directory {
2330 my ($self, $path, $pb, $rev) = @_;
2331 { path => $path };
2332}
2333
706587fc
EW
2334sub git_path {
2335 my ($self, $path) = @_;
2b27f6c8
EW
2336 if ($self->{path_strip}) {
2337 $path =~ s!$self->{path_strip}!! or
2338 die "Failed to strip path '$path' ($self->{path_strip})\n";
2339 }
706587fc
EW
2340 $path;
2341}
2342
27a1a801
EW
2343sub delete_entry {
2344 my ($self, $path, $rev, $pb) = @_;
4a87db0e 2345
706587fc 2346 my $gpath = $self->git_path($path);
8a603774
EW
2347 return undef if ($gpath eq '');
2348
4a87db0e 2349 # remove entire directories.
706587fc 2350 if (command('ls-tree', $self->{c}, '--', $gpath) =~ /^040000 tree/) {
4a87db0e
EW
2351 my ($ls, $ctx) = command_output_pipe(qw/ls-tree
2352 -r --name-only -z/,
706587fc 2353 $self->{c}, '--', $gpath);
4a87db0e
EW
2354 local $/ = "\0";
2355 while (<$ls>) {
ef3cfaad
EW
2356 chomp;
2357 $self->{gii}->remove($_);
9e3cdbd4 2358 print "\tD\t$_\n" unless $::_q;
4a87db0e 2359 }
9e3cdbd4 2360 print "\tD\t$gpath/\n" unless $::_q;
4a87db0e
EW
2361 command_close_pipe($ls, $ctx);
2362 $self->{empty}->{$path} = 0
2363 } else {
ef3cfaad 2364 $self->{gii}->remove($gpath);
9e3cdbd4 2365 print "\tD\t$gpath\n" unless $::_q;
4a87db0e 2366 }
27a1a801
EW
2367 undef;
2368}
2369
2370sub open_file {
2371 my ($self, $path, $pb, $rev) = @_;
706587fc
EW
2372 my $gpath = $self->git_path($path);
2373 my ($mode, $blob) = (command('ls-tree', $self->{c}, '--', $gpath)
27a1a801 2374 =~ /^(\d{6}) blob ([a-f\d]{40})\t/);
006ede5e
EW
2375 unless (defined $mode && defined $blob) {
2376 die "$path was not found in commit $self->{c} (r$rev)\n";
2377 }
27a1a801 2378 { path => $path, mode_a => $mode, mode_b => $mode, blob => $blob,
0864e3ba 2379 pool => SVN::Pool->new, action => 'M' };
27a1a801
EW
2380}
2381
2382sub add_file {
2383 my ($self, $path, $pb, $cp_path, $cp_rev) = @_;
d2a9a87b
EW
2384 my ($dir, $file) = ($path =~ m#^(.*?)/?([^/]+)$#);
2385 delete $self->{empty}->{$dir};
27a1a801 2386 { path => $path, mode_a => 100644, mode_b => 100644,
0864e3ba 2387 pool => SVN::Pool->new, action => 'A' };
27a1a801
EW
2388}
2389
d2a9a87b
EW
2390sub add_directory {
2391 my ($self, $path, $cp_path, $cp_rev) = @_;
2392 my ($dir, $file) = ($path =~ m#^(.*?)/?([^/]+)$#);
2393 delete $self->{empty}->{$dir};
2394 $self->{empty}->{$path} = 1;
2395 { path => $path };
2396}
2397
2398sub change_dir_prop {
2399 my ($self, $db, $prop, $value) = @_;
2400 $self->{dir_prop}->{$db->{path}} ||= {};
2401 $self->{dir_prop}->{$db->{path}}->{$prop} = $value;
2402 undef;
2403}
2404
2405sub absent_directory {
2406 my ($self, $path, $pb) = @_;
2407 $self->{absent_dir}->{$pb->{path}} ||= [];
2408 push @{$self->{absent_dir}->{$pb->{path}}}, $path;
2409 undef;
2410}
2411
2412sub absent_file {
2413 my ($self, $path, $pb) = @_;
2414 $self->{absent_file}->{$pb->{path}} ||= [];
2415 push @{$self->{absent_file}->{$pb->{path}}}, $path;
2416 undef;
2417}
2418
27a1a801
EW
2419sub change_file_prop {
2420 my ($self, $fb, $prop, $value) = @_;
2421 if ($prop eq 'svn:executable') {
2422 if ($fb->{mode_b} != 120000) {
2423 $fb->{mode_b} = defined $value ? 100755 : 100644;
2424 }
2425 } elsif ($prop eq 'svn:special') {
2426 $fb->{mode_b} = defined $value ? 120000 : 100644;
d2a9a87b
EW
2427 } else {
2428 $self->{file_prop}->{$fb->{path}} ||= {};
2429 $self->{file_prop}->{$fb->{path}}->{$prop} = $value;
27a1a801
EW
2430 }
2431 undef;
2432}
2433
2434sub apply_textdelta {
2435 my ($self, $fb, $exp) = @_;
2436 my $fh = IO::File->new_tmpfile;
2437 $fh->autoflush(1);
2438 # $fh gets auto-closed() by SVN::TxDelta::apply(),
2439 # (but $base does not,) so dup() it for reading in close_file
2440 open my $dup, '<&', $fh or croak $!;
2441 my $base = IO::File->new_tmpfile;
2442 $base->autoflush(1);
2443 if ($fb->{blob}) {
2444 defined (my $pid = fork) or croak $!;
2445 if (!$pid) {
2446 open STDOUT, '>&', $base or croak $!;
2447 print STDOUT 'link ' if ($fb->{mode_a} == 120000);
2448 exec qw/git-cat-file blob/, $fb->{blob} or croak $!;
2449 }
2450 waitpid $pid, 0;
2451 croak $? if $?;
2452
2453 if (defined $exp) {
2454 seek $base, 0, 0 or croak $!;
2455 my $md5 = Digest::MD5->new;
2456 $md5->addfile($base);
2457 my $got = $md5->hexdigest;
2458 die "Checksum mismatch: $fb->{path} $fb->{blob}\n",
2459 "expected: $exp\n",
2460 " got: $got\n" if ($got ne $exp);
2461 }
2462 }
2463 seek $base, 0, 0 or croak $!;
2464 $fb->{fh} = $dup;
2465 $fb->{base} = $base;
2466 [ SVN::TxDelta::apply($base, $fh, undef, $fb->{path}, $fb->{pool}) ];
2467}
2468
2469sub close_file {
2470 my ($self, $fb, $exp) = @_;
2471 my $hash;
706587fc 2472 my $path = $self->git_path($fb->{path});
27a1a801 2473 if (my $fh = $fb->{fh}) {
7faf0686
EW
2474 if (defined $exp) {
2475 seek($fh, 0, 0) or croak $!;
2476 my $md5 = Digest::MD5->new;
2477 $md5->addfile($fh);
2478 my $got = $md5->hexdigest;
2479 if ($got ne $exp) {
2480 die "Checksum mismatch: $path\n",
2481 "expected: $exp\n got: $got\n";
2482 }
2483 }
bcd8ee5b 2484 sysseek($fh, 0, 0) or croak $!;
27a1a801 2485 if ($fb->{mode_b} == 120000) {
bcd8ee5b 2486 sysread($fh, my $buf, 5) == 5 or croak $!;
27a1a801
EW
2487 $buf eq 'link ' or die "$path has mode 120000",
2488 "but is not a link\n";
2489 }
2490 defined(my $pid = open my $out,'-|') or die "Can't fork: $!\n";
2491 if (!$pid) {
2492 open STDIN, '<&', $fh or croak $!;
2493 exec qw/git-hash-object -w --stdin/ or croak $!;
2494 }
2495 chomp($hash = do { local $/; <$out> });
2496 close $out or croak $!;
2497 close $fh or croak $!;
2498 $hash =~ /^[a-f\d]{40}$/ or die "not a sha1: $hash\n";
2499 close $fb->{base} or croak $!;
2500 } else {
2501 $hash = $fb->{blob} or die "no blob information\n";
2502 }
2503 $fb->{pool}->clear;
ef3cfaad 2504 $self->{gii}->update($fb->{mode_b}, $hash, $path) or croak $!;
9e3cdbd4 2505 print "\t$fb->{action}\t$path\n" if $fb->{action} && ! $::_q;
27a1a801
EW
2506 undef;
2507}
2508
2509sub abort_edit {
2510 my $self = shift;
ef3cfaad
EW
2511 $self->{nr} = $self->{gii}->{nr};
2512 delete $self->{gii};
27a1a801
EW
2513 $self->SUPER::abort_edit(@_);
2514}
2515
2516sub close_edit {
2517 my $self = shift;
dad73c0b 2518 $self->{git_commit_ok} = 1;
ef3cfaad
EW
2519 $self->{nr} = $self->{gii}->{nr};
2520 delete $self->{gii};
27a1a801
EW
2521 $self->SUPER::close_edit(@_);
2522}
1a82e793 2523
a5e0cedc 2524package SVN::Git::Editor;
24e22aa8 2525use vars qw/@ISA $_rmdir $_cp_similarity $_find_copies_harder $_rename_limit/;
a5e0cedc
EW
2526use strict;
2527use warnings;
2528use Carp qw/croak/;
2529use IO::File;
90c1b15d 2530use Digest::MD5;
a5e0cedc
EW
2531
2532sub new {
61395354
EW
2533 my ($class, $opts) = @_;
2534 foreach (qw/svn_path r ra tree_a tree_b log editor_cb/) {
2535 die "$_ required!\n" unless (defined $opts->{$_});
2536 }
2537
2538 my $pool = SVN::Pool->new;
2539 my $mods = generate_diff($opts->{tree_a}, $opts->{tree_b});
2540 my $types = check_diff_paths($opts->{ra}, $opts->{svn_path},
2541 $opts->{r}, $mods);
2542
2543 # $opts->{ra} functions should not be used after this:
2544 my @ce = $opts->{ra}->get_commit_editor($opts->{log},
2545 $opts->{editor_cb}, $pool);
2546 my $self = SVN::Delta::Editor->new(@ce, $pool);
a5e0cedc 2547 bless $self, $class;
61395354
EW
2548 foreach (qw/svn_path r tree_a tree_b/) {
2549 $self->{$_} = $opts->{$_};
a5e0cedc 2550 }
61395354
EW
2551 $self->{url} = $opts->{ra}->{url};
2552 $self->{mods} = $mods;
2553 $self->{types} = $types;
2554 $self->{pool} = $pool;
a5e0cedc
EW
2555 $self->{bat} = { '' => $self->open_root($self->{r}, $self->{pool}) };
2556 $self->{rm} = { };
d3a840dc
EW
2557 $self->{path_prefix} = length $self->{svn_path} ?
2558 "$self->{svn_path}/" : '';
a5e0cedc
EW
2559 return $self;
2560}
2561
61395354
EW
2562sub generate_diff {
2563 my ($tree_a, $tree_b) = @_;
2564 my @diff_tree = qw(diff-tree -z -r);
24e22aa8
EW
2565 if ($_cp_similarity) {
2566 push @diff_tree, "-C$_cp_similarity";
61395354
EW
2567 } else {
2568 push @diff_tree, '-C';
2569 }
24e22aa8
EW
2570 push @diff_tree, '--find-copies-harder' if $_find_copies_harder;
2571 push @diff_tree, "-l$_rename_limit" if defined $_rename_limit;
61395354
EW
2572 push @diff_tree, $tree_a, $tree_b;
2573 my ($diff_fh, $ctx) = command_output_pipe(@diff_tree);
2574 local $/ = "\0";
2575 my $state = 'meta';
2576 my @mods;
2577 while (<$diff_fh>) {
2578 chomp $_; # this gets rid of the trailing "\0"
2579 if ($state eq 'meta' && /^:(\d{6})\s(\d{6})\s
2580 $::sha1\s($::sha1)\s
2581 ([MTCRAD])\d*$/xo) {
2582 push @mods, { mode_a => $1, mode_b => $2,
2583 sha1_b => $3, chg => $4 };
2584 if ($4 =~ /^(?:C|R)$/) {
2585 $state = 'file_a';
2586 } else {
2587 $state = 'file_b';
2588 }
2589 } elsif ($state eq 'file_a') {
2590 my $x = $mods[$#mods] or croak "Empty array\n";
2591 if ($x->{chg} !~ /^(?:C|R)$/) {
2592 croak "Error parsing $_, $x->{chg}\n";
2593 }
2594 $x->{file_a} = $_;
2595 $state = 'file_b';
2596 } elsif ($state eq 'file_b') {
2597 my $x = $mods[$#mods] or croak "Empty array\n";
2598 if (exists $x->{file_a} && $x->{chg} !~ /^(?:C|R)$/) {
2599 croak "Error parsing $_, $x->{chg}\n";
2600 }
2601 if (!exists $x->{file_a} && $x->{chg} =~ /^(?:C|R)$/) {
2602 croak "Error parsing $_, $x->{chg}\n";
2603 }
2604 $x->{file_b} = $_;
2605 $state = 'meta';
2606 } else {
2607 croak "Error parsing $_\n";
2608 }
2609 }
2610 command_close_pipe($diff_fh, $ctx);
2611 \@mods;
2612}
2613
2614sub check_diff_paths {
2615 my ($ra, $pfx, $rev, $mods) = @_;
2616 my %types;
2617 $pfx .= '/' if length $pfx;
2618
2619 sub type_diff_paths {
2620 my ($ra, $types, $path, $rev) = @_;
2621 my @p = split m#/+#, $path;
2622 my $c = shift @p;
2623 unless (defined $types->{$c}) {
2624 $types->{$c} = $ra->check_path($c, $rev);
2625 }
2626 while (@p) {
2627 $c .= '/' . shift @p;
2628 next if defined $types->{$c};
2629 $types->{$c} = $ra->check_path($c, $rev);
2630 }
2631 }
2632
2633 foreach my $m (@$mods) {
2634 foreach my $f (qw/file_a file_b/) {
2635 next unless defined $m->{$f};
2636 my ($dir) = ($m->{$f} =~ m#^(.*?)/?(?:[^/]+)$#);
2637 if (length $pfx.$dir && ! defined $types{$dir}) {
2638 type_diff_paths($ra, \%types, $pfx.$dir, $rev);
2639 }
2640 }
2641 }
2642 \%types;
2643}
2644
a5e0cedc
EW
2645sub split_path {
2646 return ($_[0] =~ m#^(.*?)/?([^/]+)$#);
2647}
2648
2649sub repo_path {
d3a840dc
EW
2650 my ($self, $path) = @_;
2651 $self->{path_prefix}.(defined $path ? $path : '');
a5e0cedc
EW
2652}
2653
2654sub url_path {
2655 my ($self, $path) = @_;
6e8548cc 2656 $self->{url} . '/' . $self->repo_path($path);
a5e0cedc
EW
2657}
2658
2659sub rmdirs {
61395354 2660 my ($self) = @_;
a5e0cedc
EW
2661 my $rm = $self->{rm};
2662 delete $rm->{''}; # we never delete the url we're tracking
2663 return unless %$rm;
2664
2665 foreach (keys %$rm) {
2666 my @d = split m#/#, $_;
2667 my $c = shift @d;
2668 $rm->{$c} = 1;
2669 while (@d) {
2670 $c .= '/' . shift @d;
2671 $rm->{$c} = 1;
2672 }
2673 }
2674 delete $rm->{$self->{svn_path}};
2675 delete $rm->{''}; # we never delete the url we're tracking
2676 return unless %$rm;
2677
61395354
EW
2678 my ($fh, $ctx) = command_output_pipe(qw/ls-tree --name-only -r -z/,
2679 $self->{tree_b});
a5e0cedc
EW
2680 local $/ = "\0";
2681 while (<$fh>) {
2682 chomp;
747fa12c 2683 my @dn = split m#/#, $_;
c07eee1f
EW
2684 while (pop @dn) {
2685 delete $rm->{join '/', @dn};
2686 }
2687 unless (%$rm) {
22600a25 2688 close $fh;
c07eee1f
EW
2689 return;
2690 }
a5e0cedc 2691 }
aef4e921 2692 command_close_pipe($fh, $ctx);
c07eee1f 2693
a5e0cedc
EW
2694 my ($r, $p, $bat) = ($self->{r}, $self->{pool}, $self->{bat});
2695 foreach my $d (sort { $b =~ tr#/#/# <=> $a =~ tr#/#/# } keys %$rm) {
2696 $self->close_directory($bat->{$d}, $p);
2697 my ($dn) = ($d =~ m#^(.*?)/?(?:[^/]+)$#);
44320b9e 2698 print "\tD+\t$d/\n" unless $::_q;
a5e0cedc
EW
2699 $self->SUPER::delete_entry($d, $r, $bat->{$dn}, $p);
2700 delete $bat->{$d};
2701 }
2702}
2703
2704sub open_or_add_dir {
2705 my ($self, $full_path, $baton) = @_;
6e8548cc
EW
2706 my $t = $self->{types}->{$full_path};
2707 if (!defined $t) {
2708 die "$full_path not known in r$self->{r} or we have a bug!\n";
2709 }
a5e0cedc
EW
2710 if ($t == $SVN::Node::none) {
2711 return $self->add_directory($full_path, $baton,
2712 undef, -1, $self->{pool});
2713 } elsif ($t == $SVN::Node::dir) {
2714 return $self->open_directory($full_path, $baton,
2715 $self->{r}, $self->{pool});
2716 }
2717 print STDERR "$full_path already exists in repository at ",
2718 "r$self->{r} and it is not a directory (",
2719 ($t == $SVN::Node::file ? 'file' : 'unknown'),"/$t)\n";
2720 exit 1;
2721}
2722
2723sub ensure_path {
2724 my ($self, $path) = @_;
2725 my $bat = $self->{bat};
6e8548cc
EW
2726 my $repo_path = $self->repo_path($path);
2727 return $bat->{''} unless (length $repo_path);
2728 my @p = split m#/+#, $repo_path;
a5e0cedc
EW
2729 my $c = shift @p;
2730 $bat->{$c} ||= $self->open_or_add_dir($c, $bat->{''});
2731 while (@p) {
2732 my $c0 = $c;
2733 $c .= '/' . shift @p;
2734 $bat->{$c} ||= $self->open_or_add_dir($c, $bat->{$c0});
2735 }
2736 return $bat->{$c};
2737}
2738
2739sub A {
44320b9e 2740 my ($self, $m) = @_;
a5e0cedc
EW
2741 my ($dir, $file) = split_path($m->{file_b});
2742 my $pbat = $self->ensure_path($dir);
2743 my $fbat = $self->add_file($self->repo_path($m->{file_b}), $pbat,
2744 undef, -1);
44320b9e 2745 print "\tA\t$m->{file_b}\n" unless $::_q;
a5e0cedc
EW
2746 $self->chg_file($fbat, $m);
2747 $self->close_file($fbat,undef,$self->{pool});
2748}
2749
2750sub C {
44320b9e 2751 my ($self, $m) = @_;
a5e0cedc
EW
2752 my ($dir, $file) = split_path($m->{file_b});
2753 my $pbat = $self->ensure_path($dir);
2754 my $fbat = $self->add_file($self->repo_path($m->{file_b}), $pbat,
2755 $self->url_path($m->{file_a}), $self->{r});
44320b9e 2756 print "\tC\t$m->{file_a} => $m->{file_b}\n" unless $::_q;
a5e0cedc
EW
2757 $self->chg_file($fbat, $m);
2758 $self->close_file($fbat,undef,$self->{pool});
2759}
2760
2761sub delete_entry {
2762 my ($self, $path, $pbat) = @_;
2763 my $rpath = $self->repo_path($path);
2764 my ($dir, $file) = split_path($rpath);
2765 $self->{rm}->{$dir} = 1;
2766 $self->SUPER::delete_entry($rpath, $self->{r}, $pbat, $self->{pool});
2767}
2768
2769sub R {
44320b9e 2770 my ($self, $m) = @_;
a5e0cedc
EW
2771 my ($dir, $file) = split_path($m->{file_b});
2772 my $pbat = $self->ensure_path($dir);
2773 my $fbat = $self->add_file($self->repo_path($m->{file_b}), $pbat,
2774 $self->url_path($m->{file_a}), $self->{r});
44320b9e 2775 print "\tR\t$m->{file_a} => $m->{file_b}\n" unless $::_q;
a5e0cedc
EW
2776 $self->chg_file($fbat, $m);
2777 $self->close_file($fbat,undef,$self->{pool});
2778
2779 ($dir, $file) = split_path($m->{file_a});
2780 $pbat = $self->ensure_path($dir);
2781 $self->delete_entry($m->{file_a}, $pbat);
2782}
2783
2784sub M {
44320b9e 2785 my ($self, $m) = @_;
a5e0cedc
EW
2786 my ($dir, $file) = split_path($m->{file_b});
2787 my $pbat = $self->ensure_path($dir);
2788 my $fbat = $self->open_file($self->repo_path($m->{file_b}),
2789 $pbat,$self->{r},$self->{pool});
44320b9e 2790 print "\t$m->{chg}\t$m->{file_b}\n" unless $::_q;
a5e0cedc
EW
2791 $self->chg_file($fbat, $m);
2792 $self->close_file($fbat,undef,$self->{pool});
2793}
2794
2795sub T { shift->M(@_) }
2796
2797sub change_file_prop {
2798 my ($self, $fbat, $pname, $pval) = @_;
2799 $self->SUPER::change_file_prop($fbat, $pname, $pval, $self->{pool});
2800}
2801
2802sub chg_file {
2803 my ($self, $fbat, $m) = @_;
2804 if ($m->{mode_b} =~ /755$/ && $m->{mode_a} !~ /755$/) {
2805 $self->change_file_prop($fbat,'svn:executable','*');
2806 } elsif ($m->{mode_b} !~ /755$/ && $m->{mode_a} =~ /755$/) {
2807 $self->change_file_prop($fbat,'svn:executable',undef);
2808 }
2809 my $fh = IO::File->new_tmpfile or croak $!;
2810 if ($m->{mode_b} =~ /^120/) {
2811 print $fh 'link ' or croak $!;
2812 $self->change_file_prop($fbat,'svn:special','*');
2813 } elsif ($m->{mode_a} =~ /^120/ && $m->{mode_b} !~ /^120/) {
2814 $self->change_file_prop($fbat,'svn:special',undef);
2815 }
2816 defined(my $pid = fork) or croak $!;
2817 if (!$pid) {
2818 open STDOUT, '>&', $fh or croak $!;
2819 exec qw/git-cat-file blob/, $m->{sha1_b} or croak $!;
2820 }
2821 waitpid $pid, 0;
2822 croak $? if $?;
2823 $fh->flush == 0 or croak $!;
2824 seek $fh, 0, 0 or croak $!;
2825
2826 my $md5 = Digest::MD5->new;
2827 $md5->addfile($fh) or croak $!;
2828 seek $fh, 0, 0 or croak $!;
2829
2830 my $exp = $md5->hexdigest;
f7197dff
EW
2831 my $pool = SVN::Pool->new;
2832 my $atd = $self->apply_textdelta($fbat, undef, $pool);
2833 my $got = SVN::TxDelta::send_stream($fh, @$atd, $pool);
a5e0cedc 2834 die "Checksum mismatch\nexpected: $exp\ngot: $got\n" if ($got ne $exp);
f7197dff 2835 $pool->clear;
a5e0cedc
EW
2836
2837 close $fh or croak $!;
2838}
2839
2840sub D {
44320b9e 2841 my ($self, $m) = @_;
a5e0cedc
EW
2842 my ($dir, $file) = split_path($m->{file_b});
2843 my $pbat = $self->ensure_path($dir);
44320b9e 2844 print "\tD\t$m->{file_b}\n" unless $::_q;
a5e0cedc
EW
2845 $self->delete_entry($m->{file_b}, $pbat);
2846}
2847
2848sub close_edit {
2849 my ($self) = @_;
2850 my ($p,$bat) = ($self->{pool}, $self->{bat});
2851 foreach (sort { $b =~ tr#/#/# <=> $a =~ tr#/#/# } keys %$bat) {
6442754d 2852 next if $_ eq '';
a5e0cedc
EW
2853 $self->close_directory($bat->{$_}, $p);
2854 }
6442754d 2855 $self->close_directory($bat->{''}, $p);
a5e0cedc
EW
2856 $self->SUPER::close_edit($p);
2857 $p->clear;
2858}
2859
2860sub abort_edit {
2861 my ($self) = @_;
2862 $self->SUPER::abort_edit($self->{pool});
61395354
EW
2863}
2864
2865sub DESTROY {
2866 my $self = shift;
2867 $self->SUPER::DESTROY(@_);
a5e0cedc
EW
2868 $self->{pool}->clear;
2869}
2870
44320b9e
EW
2871# this drives the editor
2872sub apply_diff {
61395354
EW
2873 my ($self) = @_;
2874 my $mods = $self->{mods};
44320b9e 2875 my %o = ( D => 1, R => 0, C => -1, A => 3, M => 3, T => 3 );
6e8548cc 2876 foreach my $m (sort { $o{$a->{chg}} <=> $o{$b->{chg}} } @$mods) {
44320b9e
EW
2877 my $f = $m->{chg};
2878 if (defined $o{$f}) {
2879 $self->$f($m);
2880 } else {
2881 fatal("Invalid change type: $f\n");
2882 }
2883 }
24e22aa8 2884 $self->rmdirs if $_rmdir;
6e8548cc 2885 if (@$mods == 0) {
44320b9e
EW
2886 $self->abort_edit;
2887 } else {
2888 $self->close_edit;
2889 }
6e8548cc 2890 return scalar @$mods;
44320b9e
EW
2891}
2892
d81bf827 2893package Git::SVN::Ra;
6af1db44 2894use vars qw/@ISA $config_dir $_log_window_size/;
d81bf827
EW
2895use strict;
2896use warnings;
a6a15a99 2897my ($can_do_switch, %ignored_err, $RA);
d81bf827
EW
2898
2899BEGIN {
2900 # enforce temporary pool usage for some simple functions
2901 my $e;
0dc03d6a 2902 foreach (qw/rev_proplist get_latest_revnum get_uuid get_repos_root/) {
d81bf827
EW
2903 $e .= "sub $_ {
2904 my \$self = shift;
2905 my \$pool = SVN::Pool->new;
2906 my \@ret = \$self->SUPER::$_(\@_,\$pool);
2907 \$pool->clear;
2908 wantarray ? \@ret : \$ret[0]; }\n";
2909 }
74a81227 2910
0dc03d6a 2911 eval "$e; 1;" or die $@;
d81bf827
EW
2912}
2913
2914sub new {
2915 my ($class, $url) = @_;
f6f09876 2916 $url =~ s!/+$!!;
5d3b7cd5 2917 return $RA if ($RA && $RA->{url} eq $url);
f6f09876 2918
d81bf827
EW
2919 SVN::_Core::svn_config_ensure($config_dir, undef);
2920 my ($baton, $callbacks) = SVN::Core::auth_open_helper([
2921 SVN::Client::get_simple_provider(),
2922 SVN::Client::get_ssl_server_trust_file_provider(),
2923 SVN::Client::get_simple_prompt_provider(
2924 \&Git::SVN::Prompt::simple, 2),
2925 SVN::Client::get_ssl_client_cert_prompt_provider(
2926 \&Git::SVN::Prompt::ssl_client_cert, 2),
2927 SVN::Client::get_ssl_client_cert_pw_prompt_provider(
2928 \&Git::SVN::Prompt::ssl_client_cert_pw, 2),
2929 SVN::Client::get_username_provider(),
2930 SVN::Client::get_ssl_server_trust_prompt_provider(
2931 \&Git::SVN::Prompt::ssl_server_trust),
2932 SVN::Client::get_username_prompt_provider(
2933 \&Git::SVN::Prompt::username, 2),
2934 ]);
2935 my $config = SVN::Core::config_get_config($config_dir);
2936 my $self = SVN::Ra->new(url => $url, auth => $baton,
2937 config => $config,
2938 pool => SVN::Pool->new,
2939 auth_provider_callbacks => $callbacks);
2940 $self->{svn_path} = $url;
2941 $self->{repos_root} = $self->get_repos_root;
4e9f6cc7 2942 $self->{svn_path} =~ s#^\Q$self->{repos_root}\E(/|$)##;
0dc03d6a
EW
2943 $self->{cache} = { check_path => { r => 0, data => {} },
2944 get_dir => { r => 0, data => {} } };
5d3b7cd5 2945 $RA = bless $self, $class;
d81bf827
EW
2946}
2947
0dc03d6a
EW
2948sub check_path {
2949 my ($self, $path, $r) = @_;
2950 my $cache = $self->{cache}->{check_path};
2951 if ($r == $cache->{r} && exists $cache->{data}->{$path}) {
2952 return $cache->{data}->{$path};
2953 }
2954 my $pool = SVN::Pool->new;
2955 my $t = $self->SUPER::check_path($path, $r, $pool);
2956 $pool->clear;
2957 if ($r != $cache->{r}) {
2958 %{$cache->{data}} = ();
2959 $cache->{r} = $r;
2960 }
2961 $cache->{data}->{$path} = $t;
2962}
2963
2964sub get_dir {
2965 my ($self, $dir, $r) = @_;
2966 my $cache = $self->{cache}->{get_dir};
2967 if ($r == $cache->{r}) {
2968 if (my $x = $cache->{data}->{$dir}) {
2969 return wantarray ? @$x : $x->[0];
2970 }
2971 }
2972 my $pool = SVN::Pool->new;
2973 my ($d, undef, $props) = $self->SUPER::get_dir($dir, $r, $pool);
2974 my %dirents = map { $_ => { kind => $d->{$_}->kind } } keys %$d;
2975 $pool->clear;
2976 if ($r != $cache->{r}) {
2977 %{$cache->{data}} = ();
2978 $cache->{r} = $r;
2979 }
2980 $cache->{data}->{$dir} = [ \%dirents, $r, $props ];
2981 wantarray ? (\%dirents, $r, $props) : \%dirents;
2982}
2983
d81bf827 2984sub DESTROY {
5d3b7cd5 2985 # do not call the real DESTROY since we store ourselves in $RA
d81bf827
EW
2986}
2987
d81bf827
EW
2988sub get_log {
2989 my ($self, @args) = @_;
2990 my $pool = SVN::Pool->new;
d81bf827
EW
2991 splice(@args, 3, 1) if ($SVN::Core::VERSION le '1.2.0');
2992 my $ret = $self->SUPER::get_log(@args, $pool);
2993 $pool->clear;
2994 $ret;
2995}
2996
2997sub get_commit_editor {
44320b9e 2998 my ($self, $log, $cb, $pool) = @_;
d81bf827 2999 my @lock = $SVN::Core::VERSION ge '1.2.0' ? (undef, 0) : ();
44320b9e 3000 $self->SUPER::get_commit_editor($log, $cb, @lock, $pool);
d81bf827
EW
3001}
3002
d81bf827 3003sub gs_do_update {
8a603774
EW
3004 my ($self, $rev_a, $rev_b, $gs, $editor) = @_;
3005 my $new = ($rev_a == $rev_b);
3006 my $path = $gs->{path};
3007
2e5e2480
EW
3008 if ($new && -e $gs->{index}) {
3009 unlink $gs->{index} or die
3010 "Couldn't unlink index: $gs->{index}: $!\n";
3011 }
d81bf827 3012 my $pool = SVN::Pool->new;
8b8fc068 3013 $editor->set_path_strip($path);
2b27f6c8
EW
3014 my (@pc) = split m#/#, $path;
3015 my $reporter = $self->do_update($rev_b, (@pc ? shift @pc : ''),
8a603774 3016 1, $editor, $pool);
d81bf827 3017 my @lock = $SVN::Core::VERSION ge '1.2.0' ? (undef) : ();
2b27f6c8
EW
3018
3019 # Since we can't rely on svn_ra_reparent being available, we'll
3020 # just have to do some magic with set_path to make it so
3021 # we only want a partial path.
3022 my $sp = '';
3023 my $final = join('/', @pc);
3024 while (@pc) {
3025 $reporter->set_path($sp, $rev_b, 0, @lock, $pool);
3026 $sp .= '/' if length $sp;
3027 $sp .= shift @pc;
3028 }
3029 die "BUG: '$sp' != '$final'\n" if ($sp ne $final);
3030
2b27f6c8
EW
3031 $reporter->set_path($sp, $rev_a, $new, @lock, $pool);
3032
d81bf827
EW
3033 $reporter->finish_report($pool);
3034 $pool->clear;
3035 $editor->{git_commit_ok};
3036}
3037
2b27f6c8
EW
3038# this requires SVN 1.4.3 or later (do_switch didn't work before 1.4.3, and
3039# svn_ra_reparent didn't work before 1.4)
d81bf827 3040sub gs_do_switch {
8a603774
EW
3041 my ($self, $rev_a, $rev_b, $gs, $url_b, $editor) = @_;
3042 my $path = $gs->{path};
d81bf827 3043 my $pool = SVN::Pool->new;
2b27f6c8
EW
3044
3045 my $full_url = $self->{url};
3046 my $old_url = $full_url;
3047 $full_url .= "/$path" if length $path;
5d3b7cd5
EW
3048 my ($ra, $reparented);
3049 if ($old_url ne $full_url) {
3050 if ($old_url !~ m#^svn(\+ssh)?://#) {
3051 SVN::_Ra::svn_ra_reparent($self->{session}, $full_url,
3052 $pool);
3053 $self->{url} = $full_url;
3054 $reparented = 1;
3055 } else {
3056 $ra = Git::SVN::Ra->new($full_url);
3057 }
3058 }
3059 $ra ||= $self;
8a603774 3060 my $reporter = $ra->do_switch($rev_b, '', 1, $url_b, $editor, $pool);
d81bf827 3061 my @lock = $SVN::Core::VERSION ge '1.2.0' ? (undef) : ();
8b8fc068 3062 $reporter->set_path('', $rev_a, 0, @lock, $pool);
d81bf827 3063 $reporter->finish_report($pool);
2b27f6c8 3064
5d3b7cd5
EW
3065 if ($reparented) {
3066 SVN::_Ra::svn_ra_reparent($self->{session}, $old_url, $pool);
3067 $self->{url} = $old_url;
3068 }
2b27f6c8 3069
d81bf827
EW
3070 $pool->clear;
3071 $editor->{git_commit_ok};
3072}
3073
0af9c9f9 3074sub gs_fetch_loop_common {
e518192f
EW
3075 my ($self, $base, $head, $gsv, $globs) = @_;
3076 return if ($base > $head);
6af1db44 3077 my $inc = $_log_window_size;
0af9c9f9 3078 my ($min, $max) = ($base, $head < $base + $inc ? $head : $base + $inc);
d2ae1434 3079 my %common;
e518192f
EW
3080 my $common_max = scalar @$gsv;
3081
3082 foreach my $gs (@$gsv) {
d2ae1434
EW
3083 my @tmp = split m#/#, $gs->{path};
3084 my $p = '';
3085 foreach (@tmp) {
3086 $p .= length($p) ? "/$_" : $_;
3087 $common{$p} ||= 0;
3088 $common{$p}++;
3089 }
3090 }
e518192f
EW
3091 $globs ||= [];
3092 $common_max += scalar @$globs;
3093 foreach my $glob (@$globs) {
3094 my @tmp = split m#/#, $glob->{path}->{left};
3095 my $p = '';
3096 foreach (@tmp) {
3097 $p .= length($p) ? "/$_" : $_;
3098 $common{$p} ||= 0;
3099 $common{$p}++;
3100 }
3101 }
3102
d2ae1434
EW
3103 my $longest_path = '';
3104 foreach (sort {length $b <=> length $a} keys %common) {
e518192f 3105 if ($common{$_} == $common_max) {
d2ae1434
EW
3106 $longest_path = $_;
3107 last;
3108 }
0af9c9f9
EW
3109 }
3110 while (1) {
d4eff2bd 3111 my %revs;
d2ae1434 3112 my $err;
f7c3fc4a 3113 my $err_handler = $SVN::Error::handler;
d2ae1434
EW
3114 $SVN::Error::handler = sub {
3115 ($err) = @_;
3116 skip_unknown_revs($err);
3117 };
3118 sub _cb {
3119 my ($paths, $r, $author, $date, $log) = @_;
3120 [ dup_changed_paths($paths),
3121 { author => $author, date => $date, log => $log } ];
3122 }
3123 $self->get_log([$longest_path], $min, $max, 0, 1, 1,
3124 sub { $revs{$_[1]} = _cb(@_) });
3125 if ($err && $max >= $head) {
3126 print STDERR "Path '$longest_path' ",
3127 "was probably deleted:\n",
3128 $err->expanded_message,
3129 "\nWill attempt to follow ",
3130 "revisions r$min .. r$max ",
3131 "committed before the deletion\n";
3132 my $hi = $max;
3133 while (--$hi >= $min) {
3134 my $ok;
3135 $self->get_log([$longest_path], $min, $hi,
3136 0, 1, 1, sub {
3137 $ok ||= $_[1];
3138 $revs{$_[1]} = _cb(@_) });
3139 if ($ok) {
3140 print STDERR "r$min .. r$ok OK\n";
3141 last;
3142 }
3143 }
3144 }
d4eff2bd 3145 $SVN::Error::handler = $err_handler;
fbcc1737 3146
e518192f 3147 my %exists = map { $_->{path} => $_ } @$gsv;
d4eff2bd 3148 foreach my $r (sort {$a <=> $b} keys %revs) {
fbcc1737 3149 my ($paths, $logged) = @{$revs{$r}};
e518192f
EW
3150
3151 foreach my $gs ($self->match_globs(\%exists, $paths,
3152 $globs, $r)) {
fbcc1737
EW
3153 if ($gs->rev_db_max >= $r) {
3154 next;
3155 }
3156 next unless $gs->match_paths($paths, $r);
3157 $gs->{logged_rev_props} = $logged;
e8d120bd
EW
3158 if (my $last_commit = $gs->last_commit) {
3159 $gs->assert_index_clean($last_commit);
3160 }
fbcc1737
EW
3161 my $log_entry = $gs->do_fetch($paths, $r);
3162 if ($log_entry) {
0af9c9f9
EW
3163 $gs->do_git_commit($log_entry);
3164 }
3165 }
e518192f 3166 foreach my $g (@$globs) {
93f2689c
EW
3167 my $k = "svn-remote.$g->{remote}." .
3168 "$g->{t}-maxRev";
3169 Git::SVN::tmp_config($k, $r);
e518192f 3170 }
0af9c9f9 3171 }
9c93fee5
EW
3172 # pre-fill the .rev_db since it'll eventually get filled in
3173 # with '0' x40 if something new gets committed
e518192f 3174 foreach my $gs (@$gsv) {
9c93fee5
EW
3175 next if defined $gs->rev_db_get($max);
3176 $gs->rev_db_set($max, 0 x40);
3177 }
c3560e53
EW
3178 foreach my $g (@$globs) {
3179 my $k = "svn-remote.$g->{remote}.$g->{t}-maxRev";
3180 Git::SVN::tmp_config($k, $max);
3181 }
0af9c9f9
EW
3182 last if $max >= $head;
3183 $min = $max + 1;
3184 $max += $inc;
3185 $max = $head if ($max > $head);
3186 }
0af9c9f9
EW
3187}
3188
e518192f
EW
3189sub match_globs {
3190 my ($self, $exists, $paths, $globs, $r) = @_;
74a81227
EW
3191
3192 sub get_dir_check {
3193 my ($self, $exists, $g, $r) = @_;
3194 my @x = eval { $self->get_dir($g->{path}->{left}, $r) };
3195 return unless scalar @x == 3;
3196 my $dirents = $x[0];
3197 foreach my $de (keys %$dirents) {
0dc03d6a 3198 next if $dirents->{$de}->{kind} != $SVN::Node::dir;
74a81227
EW
3199 my $p = $g->{path}->full_path($de);
3200 next if $exists->{$p};
3201 next if (length $g->{path}->{right} &&
3202 ($self->check_path($p, $r) !=
3203 $SVN::Node::dir));
3204 $exists->{$p} = Git::SVN->init($self->{url}, $p, undef,
3205 $g->{ref}->full_path($de), 1);
3206 }
3207 }
e518192f 3208 foreach my $g (@$globs) {
74a81227
EW
3209 if (my $path = $paths->{"/$g->{path}->{left}"}) {
3210 if ($path->{action} =~ /^[AR]$/) {
3211 get_dir_check($self, $exists, $g, $r);
3212 }
3213 }
e518192f 3214 foreach (keys %$paths) {
28710f74
EW
3215 if (/$g->{path}->{left_regex}/ &&
3216 !/$g->{path}->{regex}/) {
74a81227
EW
3217 next if $paths->{$_}->{action} !~ /^[AR]$/;
3218 get_dir_check($self, $exists, $g, $r);
3219 }
e518192f
EW
3220 next unless /$g->{path}->{regex}/;
3221 my $p = $1;
3222 my $pathname = $g->{path}->full_path($p);
3223 next if $exists->{$pathname};
0c1ec5a1
EW
3224 next if ($self->check_path($pathname, $r) !=
3225 $SVN::Node::dir);
e518192f
EW
3226 $exists->{$pathname} = Git::SVN->init(
3227 $self->{url}, $pathname, undef,
3228 $g->{ref}->full_path($p), 1);
3229 }
3230 my $c = '';
3231 foreach (split m#/#, $g->{path}->{left}) {
3232 $c .= "/$_";
3233 next unless ($paths->{$c} &&
74a81227
EW
3234 ($paths->{$c}->{action} =~ /^[AR]$/));
3235 get_dir_check($self, $exists, $g, $r);
e518192f
EW
3236 }
3237 }
3238 values %$exists;
3239}
3240
e6434f87
EW
3241sub minimize_url {
3242 my ($self) = @_;
3243 return $self->{url} if ($self->{url} eq $self->{repos_root});
3244 my $url = $self->{repos_root};
3245 my @components = split(m!/!, $self->{svn_path});
3246 my $c = '';
3247 do {
3248 $url .= "/$c" if length $c;
3249 eval { (ref $self)->new($url)->get_latest_revnum };
3250 } while ($@ && ($c = shift @components));
3251 $url;
3252}
3253
d81bf827
EW
3254sub can_do_switch {
3255 my $self = shift;
3256 unless (defined $can_do_switch) {
3257 my $pool = SVN::Pool->new;
3258 my $rep = eval {
3259 $self->do_switch(1, '', 0, $self->{url},
3260 SVN::Delta::Editor->new, $pool);
3261 };
3262 if ($@) {
3263 $can_do_switch = 0;
3264 } else {
3265 $rep->abort_report($pool);
3266 $can_do_switch = 1;
3267 }
3268 $pool->clear;
3269 }
3270 $can_do_switch;
3271}
3272
0af9c9f9
EW
3273sub skip_unknown_revs {
3274 my ($err) = @_;
3275 my $errno = $err->apr_err();
3276 # Maybe the branch we're tracking didn't
3277 # exist when the repo started, so it's
3278 # not an error if it doesn't, just continue
3279 #
3280 # Wonderfully consistent library, eh?
3281 # 160013 - svn:// and file://
3282 # 175002 - http(s)://
3283 # 175007 - http(s):// (this repo required authorization, too...)
3284 # More codes may be discovered later...
3285 if ($errno == 175007 || $errno == 175002 || $errno == 160013) {
a6a15a99
EW
3286 my $err_key = $err->expanded_message;
3287 # revision numbers change every time, filter them out
3288 $err_key =~ s/\d+/\0/g;
3289 $err_key = "$errno\0$err_key";
3290 unless ($ignored_err{$err_key}) {
3291 warn "W: Ignoring error from SVN, path probably ",
3292 "does not exist: ($errno): ",
3293 $err->expanded_message,"\n";
3294 $ignored_err{$err_key} = 1;
3295 }
0af9c9f9
EW
3296 return;
3297 }
3298 die "Error from SVN, ($errno): ", $err->expanded_message,"\n";
3299}
3300
3301# svn_log_changed_path_t objects passed to get_log are likely to be
3302# overwritten even if only the refs are copied to an external variable,
3303# so we should dup the structures in their entirety. Using an externally
3304# passed pool (instead of our temporary and quickly cleared pool in
3305# Git::SVN::Ra) does not help matters at all...
3306sub dup_changed_paths {
3307 my ($paths) = @_;
3308 return undef unless $paths;
3309 my %ret;
3310 foreach my $p (keys %$paths) {
3311 my $i = $paths->{$p};
3312 my %s = map { $_ => $i->$_ }
3313 qw/copyfrom_path copyfrom_rev action/;
3314 $ret{$p} = \%s;
3315 }
3316 \%ret;
3317}
3318
f8c9d1d2
EW
3319package Git::SVN::Log;
3320use strict;
3321use warnings;
3322use POSIX qw/strftime/;
3323use vars qw/$TZ $limit $color $pager $non_recursive $verbose $oneline
3324 %rusers $show_commit $incremental/;
3325my $l_fmt;
3326
3327sub cmt_showable {
3328 my ($c) = @_;
3329 return 1 if defined $c->{r};
c16d0871
EW
3330
3331 # big commit message got truncated by the 16k pretty buffer in rev-list
f8c9d1d2
EW
3332 if ($c->{l} && $c->{l}->[-1] eq "...\n" &&
3333 $c->{a_raw} =~ /\@([a-f\d\-]+)>$/) {
c16d0871 3334 @{$c->{l}} = ();
44320b9e 3335 my @log = command(qw/cat-file commit/, $c->{c});
c16d0871
EW
3336
3337 # shift off the headers
3338 shift @log while ($log[0] ne '');
44320b9e 3339 shift @log;
c16d0871
EW
3340
3341 # TODO: make $c->{l} not have a trailing newline in the future
3342 @{$c->{l}} = map { "$_\n" } grep !/^git-svn-id: /, @log;
f8c9d1d2
EW
3343
3344 (undef, $c->{r}, undef) = ::extract_metadata(
44320b9e 3345 (grep(/^git-svn-id: /, @log))[-1]);
f8c9d1d2
EW
3346 }
3347 return defined $c->{r};
3348}
3349
3350sub log_use_color {
3351 return 1 if $color;
3352 my ($dc, $dcvar);
3353 $dcvar = 'color.diff';
3354 $dc = `git-config --get $dcvar`;
3355 if ($dc eq '') {
3356 # nothing at all; fallback to "diff.color"
3357 $dcvar = 'diff.color';
3358 $dc = `git-config --get $dcvar`;
3359 }
3360 chomp($dc);
3361 if ($dc eq 'auto') {
3362 my $pc;
3363 $pc = `git-config --get color.pager`;
3364 if ($pc eq '') {
3365 # does not have it -- fallback to pager.color
3366 $pc = `git-config --bool --get pager.color`;
3367 }
3368 else {
3369 $pc = `git-config --bool --get color.pager`;
3370 if ($?) {
3371 $pc = 'false';
3372 }
3373 }
3374 chomp($pc);
3375 if (-t *STDOUT || (defined $pager && $pc eq 'true')) {
3376 return ($ENV{TERM} && $ENV{TERM} ne 'dumb');
3377 }
3378 return 0;
3379 }
3380 return 0 if $dc eq 'never';
3381 return 1 if $dc eq 'always';
3382 chomp($dc = `git-config --bool --get $dcvar`);
3383 return ($dc eq 'true');
3384}
3385
3386sub git_svn_log_cmd {
3bc718ba
EW
3387 my ($r_min, $r_max, @args) = @_;
3388 my $head = 'HEAD';
3389 foreach my $x (@args) {
3390 last if $x eq '--';
3391 next unless ::verify_ref("$x^0");
3392 $head = $x;
3393 last;
3394 }
3395
13c823fb
EW
3396 my ($url, $rev, $uuid, $gs) = ::working_head_info($head);
3397 $gs ||= Git::SVN->_new;
f8c9d1d2
EW
3398 my @cmd = (qw/log --abbrev-commit --pretty=raw --default/,
3399 $gs->refname);
3400 push @cmd, '-r' unless $non_recursive;
3401 push @cmd, qw/--raw --name-status/ if $verbose;
3402 push @cmd, '--color' if log_use_color();
3403 return @cmd unless defined $r_max;
3404 if ($r_max == $r_min) {
3405 push @cmd, '--max-count=1';
3406 if (my $c = $gs->rev_db_get($r_max)) {
3407 push @cmd, $c;
3408 }
3409 } else {
3410 my ($c_min, $c_max);
3411 $c_max = $gs->rev_db_get($r_max);
3412 $c_min = $gs->rev_db_get($r_min);
3413 if (defined $c_min && defined $c_max) {
3414 if ($r_max > $r_max) {
3415 push @cmd, "$c_min..$c_max";
3416 } else {
3417 push @cmd, "$c_max..$c_min";
3418 }
3419 } elsif ($r_max > $r_min) {
3420 push @cmd, $c_max;
3421 } else {
3422 push @cmd, $c_min;
3423 }
3424 }
3425 return @cmd;
3426}
3427
3428# adapted from pager.c
3429sub config_pager {
3430 $pager ||= $ENV{GIT_PAGER} || $ENV{PAGER};
3431 if (!defined $pager) {
3432 $pager = 'less';
3433 } elsif (length $pager == 0 || $pager eq 'cat') {
3434 $pager = undef;
3435 }
3436}
3437
3438sub run_pager {
3439 return unless -t *STDOUT;
3440 pipe my $rfd, my $wfd or return;
3441 defined(my $pid = fork) or ::fatal "Can't fork: $!\n";
3442 if (!$pid) {
3443 open STDOUT, '>&', $wfd or
3444 ::fatal "Can't redirect to stdout: $!\n";
3445 return;
3446 }
3447 open STDIN, '<&', $rfd or ::fatal "Can't redirect stdin: $!\n";
3448 $ENV{LESS} ||= 'FRSX';
3449 exec $pager or ::fatal "Can't run pager: $! ($pager)\n";
3450}
3451
21819a37
EW
3452sub tz_to_s_offset {
3453 my ($tz) = @_;
3454 $tz =~ s/(\d\d)$//;
3455 return ($1 * 60) + ($tz * 3600);
3456}
3457
f8c9d1d2
EW
3458sub get_author_info {
3459 my ($dest, $author, $t, $tz) = @_;
3460 $author =~ s/(?:^\s*|\s*$)//g;
3461 $dest->{a_raw} = $author;
3462 my $au;
1c8443b0 3463 if ($::_authors) {
f8c9d1d2
EW
3464 $au = $rusers{$author} || undef;
3465 }
3466 if (!$au) {
3467 ($au) = ($author =~ /<([^>]+)\@[^>]+>$/);
3468 }
3469 $dest->{t} = $t;
3470 $dest->{tz} = $tz;
3471 $dest->{a} = $au;
3472 # Date::Parse isn't in the standard Perl distro :(
3473 if ($tz =~ s/^\+//) {
21819a37 3474 $t += tz_to_s_offset($tz);
f8c9d1d2 3475 } elsif ($tz =~ s/^\-//) {
21819a37 3476 $t -= tz_to_s_offset($tz);
f8c9d1d2
EW
3477 }
3478 $dest->{t_utc} = $t;
3479}
3480
3481sub process_commit {
3482 my ($c, $r_min, $r_max, $defer) = @_;
3483 if (defined $r_min && defined $r_max) {
3484 if ($r_min == $c->{r} && $r_min == $r_max) {
3485 show_commit($c);
3486 return 0;
3487 }
3488 return 1 if $r_min == $r_max;
3489 if ($r_min < $r_max) {
3490 # we need to reverse the print order
3491 return 0 if (defined $limit && --$limit < 0);
3492 push @$defer, $c;
3493 return 1;
3494 }
3495 if ($r_min != $r_max) {
3496 return 1 if ($r_min < $c->{r});
3497 return 1 if ($r_max > $c->{r});
3498 }
3499 }
3500 return 0 if (defined $limit && --$limit < 0);
3501 show_commit($c);
3502 return 1;
3503}
3504
3505sub show_commit {
3506 my $c = shift;
3507 if ($oneline) {
3508 my $x = "\n";
3509 if (my $l = $c->{l}) {
3510 while ($l->[0] =~ /^\s*$/) { shift @$l }
3511 $x = $l->[0];
3512 }
3513 $l_fmt ||= 'A' . length($c->{r});
3514 print 'r',pack($l_fmt, $c->{r}),' | ';
3515 print "$c->{c} | " if $show_commit;
3516 print $x;
3517 } else {
3518 show_commit_normal($c);
3519 }
3520}
3521
3522sub show_commit_changed_paths {
3523 my ($c) = @_;
3524 return unless $c->{changed};
3525 print "Changed paths:\n", @{$c->{changed}};
3526}
3527
3528sub show_commit_normal {
3529 my ($c) = @_;
3530 print '-' x72, "\nr$c->{r} | ";
3531 print "$c->{c} | " if $show_commit;
3532 print "$c->{a} | ", strftime("%Y-%m-%d %H:%M:%S %z (%a, %d %b %Y)",
3533 localtime($c->{t_utc})), ' | ';
3534 my $nr_line = 0;
3535
3536 if (my $l = $c->{l}) {
3537 while ($l->[$#$l] eq "\n" && $#$l > 0
3538 && $l->[($#$l - 1)] eq "\n") {
3539 pop @$l;
3540 }
3541 $nr_line = scalar @$l;
3542 if (!$nr_line) {
3543 print "1 line\n\n\n";
3544 } else {
3545 if ($nr_line == 1) {
3546 $nr_line = '1 line';
3547 } else {
3548 $nr_line .= ' lines';
3549 }
3550 print $nr_line, "\n";
3551 show_commit_changed_paths($c);
3552 print "\n";
3553 print $_ foreach @$l;
3554 }
3555 } else {
3556 print "1 line\n";
3557 show_commit_changed_paths($c);
3558 print "\n";
3559
3560 }
488a63ec 3561 foreach my $x (qw/raw stat diff/) {
f8c9d1d2
EW
3562 if ($c->{$x}) {
3563 print "\n";
3564 print $_ foreach @{$c->{$x}}
3565 }
3566 }
3567}
3568
3569sub cmd_show_log {
3570 my (@args) = @_;
3571 my ($r_min, $r_max);
3572 my $r_last = -1; # prevent dupes
3573 if (defined $TZ) {
3574 $ENV{TZ} = $TZ;
3575 } else {
3576 delete $ENV{TZ};
3577 }
3578 if (defined $::_revision) {
3579 if ($::_revision =~ /^(\d+):(\d+)$/) {
3580 ($r_min, $r_max) = ($1, $2);
3581 } elsif ($::_revision =~ /^\d+$/) {
3582 $r_min = $r_max = $::_revision;
3583 } else {
3584 ::fatal "-r$::_revision is not supported, use ",
3585 "standard \'git log\' arguments instead\n";
3586 }
3587 }
3588
3589 config_pager();
3bc718ba 3590 @args = (git_svn_log_cmd($r_min, $r_max, @args), @args);
f8c9d1d2
EW
3591 my $log = command_output_pipe(@args);
3592 run_pager();
488a63ec 3593 my (@k, $c, $d, $stat);
f8c9d1d2
EW
3594 my $esc_color = qr/(?:\033\[(?:(?:\d+;)*\d*)?m)*/;
3595 while (<$log>) {
3596 if (/^${esc_color}commit ($::sha1_short)/o) {
3597 my $cmt = $1;
3598 if ($c && cmt_showable($c) && $c->{r} != $r_last) {
3599 $r_last = $c->{r};
3600 process_commit($c, $r_min, $r_max, \@k) or
3601 goto out;
3602 }
3603 $d = undef;
3604 $c = { c => $cmt };
3605 } elsif (/^${esc_color}author (.+) (\d+) ([\-\+]?\d+)$/o) {
3606 get_author_info($c, $1, $2, $3);
3607 } elsif (/^${esc_color}(?:tree|parent|committer) /o) {
3608 # ignore
3609 } elsif (/^${esc_color}:\d{6} \d{6} $::sha1_short/o) {
3610 push @{$c->{raw}}, $_;
3611 } elsif (/^${esc_color}[ACRMDT]\t/) {
3612 # we could add $SVN->{svn_path} here, but that requires
3613 # remote access at the moment (repo_path_split)...
3614 s#^(${esc_color})([ACRMDT])\t#$1 $2 #o;
3615 push @{$c->{changed}}, $_;
3616 } elsif (/^${esc_color}diff /o) {
3617 $d = 1;
3618 push @{$c->{diff}}, $_;
3619 } elsif ($d) {
3620 push @{$c->{diff}}, $_;
488a63ec
EW
3621 } elsif (/^\ .+\ \|\s*\d+\ $esc_color[\+\-]*
3622 $esc_color*[\+\-]*$esc_color$/x) {
3623 $stat = 1;
3624 push @{$c->{stat}}, $_;
3625 } elsif ($stat && /^ \d+ files changed, \d+ insertions/) {
3626 push @{$c->{stat}}, $_;
3627 $stat = undef;
f8c9d1d2
EW
3628 } elsif (/^${esc_color} (git-svn-id:.+)$/o) {
3629 ($c->{url}, $c->{r}, undef) = ::extract_metadata($1);
3630 } elsif (s/^${esc_color} //o) {
3631 push @{$c->{l}}, $_;
3632 }
3633 }
3634 if ($c && defined $c->{r} && $c->{r} != $r_last) {
3635 $r_last = $c->{r};
3636 process_commit($c, $r_min, $r_max, \@k);
3637 }
3638 if (@k) {
3639 my $swap = $r_max;
3640 $r_max = $r_min;
3641 $r_min = $swap;
3642 process_commit($_, $r_min, $r_max) foreach reverse @k;
3643 }
3644out:
c843c464 3645 close $log;
f8c9d1d2
EW
3646 print '-' x72,"\n" unless $incremental || $oneline;
3647}
3648
706587fc
EW
3649package Git::SVN::Migration;
3650# these version numbers do NOT correspond to actual version numbers
3651# of git nor git-svn. They are just relative.
3652#
3653# v0 layout: .git/$id/info/url, refs/heads/$id-HEAD
3654#
3655# v1 layout: .git/$id/info/url, refs/remotes/$id
3656#
3657# v2 layout: .git/svn/$id/info/url, refs/remotes/$id
3658#
3659# v3 layout: .git/svn/$id, refs/remotes/$id
3660# - info/url may remain for backwards compatibility
3661# - this is what we migrate up to this layout automatically,
3662# - this will be used by git svn init on single branches
26a62d57
EW
3663# v3.1 layout (auto migrated):
3664# - .rev_db => .rev_db.$UUID, .rev_db will remain as a symlink
3665# for backwards compatibility
706587fc
EW
3666#
3667# v4 layout: .git/svn/$repo_id/$id, refs/remotes/$repo_id/$id
3668# - this is only created for newly multi-init-ed
3669# repositories. Similar in spirit to the
3670# --use-separate-remotes option in git-clone (now default)
3671# - we do not automatically migrate to this (following
3672# the example set by core git)
3673use strict;
3674use warnings;
3675use Carp qw/croak/;
3676use File::Path qw/mkpath/;
47e39c55
EW
3677use File::Basename qw/dirname basename/;
3678use vars qw/$_minimize/;
706587fc
EW
3679
3680sub migrate_from_v0 {
3681 my $git_dir = $ENV{GIT_DIR};
3682 return undef unless -d $git_dir;
3683 my ($fh, $ctx) = command_output_pipe(qw/rev-parse --symbolic --all/);
3684 my $migrated = 0;
3685 while (<$fh>) {
3686 chomp;
3687 my ($id, $orig_ref) = ($_, $_);
3688 next unless $id =~ s#^refs/heads/(.+)-HEAD$#$1#;
3689 next unless -f "$git_dir/$id/info/url";
3690 my $new_ref = "refs/remotes/$id";
3691 if (::verify_ref("$new_ref^0")) {
3692 print STDERR "W: $orig_ref is probably an old ",
3693 "branch used by an ancient version of ",
3694 "git-svn.\n",
3695 "However, $new_ref also exists.\n",
3696 "We will not be able ",
3697 "to use this branch until this ",
3698 "ambiguity is resolved.\n";
3699 next;
3700 }
3701 print STDERR "Migrating from v0 layout...\n" if !$migrated;
3702 print STDERR "Renaming ref: $orig_ref => $new_ref\n";
3703 command_noisy('update-ref', $new_ref, $orig_ref);
3704 command_noisy('update-ref', '-d', $orig_ref, $orig_ref);
3705 $migrated++;
3706 }
3707 command_close_pipe($fh, $ctx);
3708 print STDERR "Done migrating from v0 layout...\n" if $migrated;
3709 $migrated;
3710}
3711
3712sub migrate_from_v1 {
3713 my $git_dir = $ENV{GIT_DIR};
3714 my $migrated = 0;
3715 return $migrated unless -d $git_dir;
3716 my $svn_dir = "$git_dir/svn";
3717
3718 # just in case somebody used 'svn' as their $id at some point...
3719 return $migrated if -d $svn_dir && ! -f "$svn_dir/info/url";
3720
3721 print STDERR "Migrating from a git-svn v1 layout...\n";
3722 mkpath([$svn_dir]);
3723 print STDERR "Data from a previous version of git-svn exists, but\n\t",
3724 "$svn_dir\n\t(required for this version ",
3725 "($::VERSION) of git-svn) does not. exist\n";
3726 my ($fh, $ctx) = command_output_pipe(qw/rev-parse --symbolic --all/);
3727 while (<$fh>) {
3728 my $x = $_;
3729 next unless $x =~ s#^refs/remotes/##;
3730 chomp $x;
3731 next unless -f "$git_dir/$x/info/url";
3732 my $u = eval { ::file_to_s("$git_dir/$x/info/url") };
3733 next unless $u;
3734 my $dn = dirname("$git_dir/svn/$x");
3735 mkpath([$dn]) unless -d $dn;
3736 if ($x eq 'svn') { # they used 'svn' as GIT_SVN_ID:
3737 mkpath(["$git_dir/svn/svn"]);
3738 print STDERR " - $git_dir/$x/info => ",
3739 "$git_dir/svn/$x/info\n";
3740 rename "$git_dir/$x/info", "$git_dir/svn/$x/info" or
3741 croak "$!: $x";
3742 # don't worry too much about these, they probably
3743 # don't exist with repos this old (save for index,
3744 # and we can easily regenerate that)
3745 foreach my $f (qw/unhandled.log index .rev_db/) {
3746 rename "$git_dir/$x/$f", "$git_dir/svn/$x/$f";
3747 }
3748 } else {
3749 print STDERR " - $git_dir/$x => $git_dir/svn/$x\n";
3750 rename "$git_dir/$x", "$git_dir/svn/$x" or
3751 croak "$!: $x";
3752 }
3753 $migrated++;
3754 }
3755 command_close_pipe($fh, $ctx);
3756 print STDERR "Done migrating from a git-svn v1 layout\n";
3757 $migrated;
3758}
3759
3760sub read_old_urls {
3761 my ($l_map, $pfx, $path) = @_;
3762 my @dir;
3763 foreach (<$path/*>) {
3764 if (-r "$_/info/url") {
3765 $pfx .= '/' if $pfx && $pfx !~ m!/$!;
3766 my $ref_id = $pfx . basename $_;
3767 my $url = ::file_to_s("$_/info/url");
3768 $l_map->{$ref_id} = $url;
3769 } elsif (-d $_) {
3770 push @dir, $_;
3771 }
3772 }
3773 foreach (@dir) {
3774 my $x = $_;
3775 $x =~ s!^\Q$ENV{GIT_DIR}\E/svn/!!o;
3776 read_old_urls($l_map, $x, $_);
3777 }
3778}
3779
3780sub migrate_from_v2 {
3781 my @cfg = command(qw/config -l/);
3782 return if grep /^svn-remote\..+\.url=/, @cfg;
3783 my %l_map;
3784 read_old_urls(\%l_map, '', "$ENV{GIT_DIR}/svn");
3785 my $migrated = 0;
3786
3787 foreach my $ref_id (sort keys %l_map) {
471bc000
EW
3788 eval { Git::SVN->init($l_map{$ref_id}, '', undef, $ref_id) };
3789 if ($@) {
3790 Git::SVN->init($l_map{$ref_id}, '', $ref_id, $ref_id);
3791 }
706587fc
EW
3792 $migrated++;
3793 }
3794 $migrated;
3795}
3796
47e39c55
EW
3797sub minimize_connections {
3798 my $r = Git::SVN::read_all_remotes();
3799 my $new_urls = {};
3800 my $root_repos = {};
3801 foreach my $repo_id (keys %$r) {
3802 my $url = $r->{$repo_id}->{url} or next;
3803 my $fetch = $r->{$repo_id}->{fetch} or next;
3804 my $ra = Git::SVN::Ra->new($url);
3805
3806 # skip existing cases where we already connect to the root
3807 if (($ra->{url} eq $ra->{repos_root}) ||
3808 (Git::SVN::sanitize_remote_name($ra->{repos_root}) eq
3809 $repo_id)) {
3810 $root_repos->{$ra->{url}} = $repo_id;
3811 next;
3812 }
3813
3814 my $root_ra = Git::SVN::Ra->new($ra->{repos_root});
3815 my $root_path = $ra->{url};
4e9f6cc7 3816 $root_path =~ s#^\Q$ra->{repos_root}\E(/|$)##;
47e39c55
EW
3817 foreach my $path (keys %$fetch) {
3818 my $ref_id = $fetch->{$path};
3819 my $gs = Git::SVN->new($ref_id, $repo_id, $path);
3820
3821 # make sure we can read when connecting to
3822 # a higher level of a repository
3823 my ($last_rev, undef) = $gs->last_rev_commit;
3824 if (!defined $last_rev) {
3825 $last_rev = eval {
3826 $root_ra->get_latest_revnum;
3827 };
3828 next if $@;
3829 }
3830 my $new = $root_path;
3831 $new .= length $path ? "/$path" : '';
3832 eval {
3833 $root_ra->get_log([$new], $last_rev, $last_rev,
3834 0, 0, 1, sub { });
3835 };
3836 next if $@;
3837 $new_urls->{$ra->{repos_root}}->{$new} =
3838 { ref_id => $ref_id,
3839 old_repo_id => $repo_id,
3840 old_path => $path };
3841 }
3842 }
3843
3844 my @emptied;
3845 foreach my $url (keys %$new_urls) {
3846 # see if we can re-use an existing [svn-remote "repo_id"]
3847 # instead of creating a(n ugly) new section:
3848 my $repo_id = $root_repos->{$url} ||
3849 Git::SVN::sanitize_remote_name($url);
3850
3851 my $fetch = $new_urls->{$url};
3852 foreach my $path (keys %$fetch) {
3853 my $x = $fetch->{$path};
3854 Git::SVN->init($url, $path, $repo_id, $x->{ref_id});
3855 my $pfx = "svn-remote.$x->{old_repo_id}";
3856
3857 my $old_fetch = quotemeta("$x->{old_path}:".
3858 "refs/remotes/$x->{ref_id}");
8b8fc068 3859 command_noisy(qw/config --unset/,
47e39c55
EW
3860 "$pfx.fetch", '^'. $old_fetch . '$');
3861 delete $r->{$x->{old_repo_id}}->
3862 {fetch}->{$x->{old_path}};
3863 if (!keys %{$r->{$x->{old_repo_id}}->{fetch}}) {
8b8fc068 3864 command_noisy(qw/config --unset/,
47e39c55
EW
3865 "$pfx.url");
3866 push @emptied, $x->{old_repo_id}
3867 }
3868 }
3869 }
3870 if (@emptied) {
3871 my $file = $ENV{GIT_CONFIG} || $ENV{GIT_CONFIG_LOCAL} ||
3872 "$ENV{GIT_DIR}/config";
3873 print STDERR <<EOF;
3874The following [svn-remote] sections in your config file ($file) are empty
3875and can be safely removed:
3876EOF
3877 print STDERR "[svn-remote \"$_\"]\n" foreach @emptied;
3878 }
3879}
3880
706587fc
EW
3881sub migration_check {
3882 migrate_from_v0();
3883 migrate_from_v1();
3884 migrate_from_v2();
47e39c55 3885 minimize_connections() if $_minimize;
706587fc
EW
3886}
3887
ef3cfaad
EW
3888package Git::IndexInfo;
3889use strict;
3890use warnings;
3891use Git qw/command_input_pipe command_close_pipe/;
3892
3893sub new {
3894 my ($class) = @_;
3895 my ($gui, $ctx) = command_input_pipe(qw/update-index -z --index-info/);
3896 bless { gui => $gui, ctx => $ctx, nr => 0}, $class;
3897}
3898
3899sub remove {
3900 my ($self, $path) = @_;
3901 if (print { $self->{gui} } '0 ', 0 x 40, "\t", $path, "\0") {
3902 return ++$self->{nr};
3903 }
3904 undef;
3905}
3906
3907sub update {
3908 my ($self, $mode, $hash, $path) = @_;
3909 if (print { $self->{gui} } $mode, ' ', $hash, "\t", $path, "\0") {
3910 return ++$self->{nr};
3911 }
3912 undef;
3913}
3914
3915sub DESTROY {
3916 my ($self) = @_;
3917 command_close_pipe($self->{gui}, $self->{ctx});
3918}
3919
4bb9ed04
EW
3920package Git::SVN::GlobSpec;
3921use strict;
3922use warnings;
3923
3924sub new {
3925 my ($class, $glob) = @_;
4bb9ed04
EW
3926 my $re = $glob;
3927 $re =~ s!/+$!!g; # no need for trailing slashes
4e9f6cc7 3928 my $nr = ($re =~ s!^(.*)\*(.*)$!\(\[^/\]+\)!g);
4bb9ed04
EW
3929 my ($left, $right) = ($1, $2);
3930 if ($nr > 1) {
e518192f
EW
3931 die "Only one '*' wildcard expansion ",
3932 "is supported (got $nr): '$glob'\n";
4bb9ed04 3933 } elsif ($nr == 0) {
e518192f 3934 die "One '*' is needed for glob: '$glob'\n";
4bb9ed04
EW
3935 }
3936 $re = quotemeta($left) . $re . quotemeta($right);
4e9f6cc7
EW
3937 if (length $left && !($left =~ s!/+$!!g)) {
3938 die "Missing trailing '/' on left side of: '$glob' ($left)\n";
3939 }
3940 if (length $right && !($right =~ s!^/+!!g)) {
3941 die "Missing leading '/' on right side of: '$glob' ($right)\n";
3942 }
74a81227
EW
3943 my $left_re = qr/^\/\Q$left\E(\/|$)/;
3944 bless { left => $left, right => $right, left_regex => $left_re,
4bb9ed04
EW
3945 regex => qr/$re/, glob => $glob }, $class;
3946}
3947
3948sub full_path {
3949 my ($self, $path) = @_;
3950 return (length $self->{left} ? "$self->{left}/" : '') .
3951 $path . (length $self->{right} ? "/$self->{right}" : '');
3952}
3953
3397f9df
EW
3954__END__
3955
3956Data structures:
3957
4bb9ed04
EW
3958
3959$remotes = { # returned by read_all_remotes()
3960 'svn' => {
3961 # svn-remote.svn.url=https://svn.musicpd.org
3962 url => 'https://svn.musicpd.org',
3963 # svn-remote.svn.fetch=mpd/trunk:trunk
3964 fetch => {
3965 'mpd/trunk' => 'trunk',
3966 },
3967 # svn-remote.svn.tags=mpd/tags/*:tags/*
3968 tags => {
3969 path => {
3970 left => 'mpd/tags',
3971 right => '',
3972 regex => qr!mpd/tags/([^/]+)$!,
3973 glob => 'tags/*',
3974 },
3975 ref => {
3976 left => 'tags',
3977 right => '',
3978 regex => qr!tags/([^/]+)$!,
3979 glob => 'tags/*',
3980 },
3981 }
3982 }
3983};
3984
44320b9e 3985$log_entry hashref as returned by libsvn_log_entry()
3397f9df 3986{
44320b9e 3987 log => 'whitespace-formatted log entry
3397f9df
EW
3988', # trailing newline is preserved
3989 revision => '8', # integer
3990 date => '2004-02-24T17:01:44.108345Z', # commit date
3991 author => 'committer name'
3992};
3993
6e8548cc
EW
3994
3995# this is generated by generate_diff();
3397f9df
EW
3996@mods = array of diff-index line hashes, each element represents one line
3997 of diff-index output
3998
3999diff-index line ($m hash)
4000{
4001 mode_a => first column of diff-index output, no leading ':',
4002 mode_b => second column of diff-index output,
4003 sha1_b => sha1sum of the final blob,
ac8e0b91 4004 chg => change type [MCRADT],
3397f9df
EW
4005 file_a => original file name of a file (iff chg is 'C' or 'R')
4006 file_b => new/current file name of a file (any chg)
4007}
4008;
a5e0cedc 4009
a00439ac
EW
4010# retval of read_url_paths{,_all}();
4011$l_map = {
4012 # repository root url
4013 'https://svn.musicpd.org' => {
4014 # repository path # GIT_SVN_ID
4015 'mpd/trunk' => 'trunk',
4016 'mpd/tags/0.11.5' => 'tags/0.11.5',
4017 },
4018}
4019
a5e0cedc
EW
4020Notes:
4021 I don't trust the each() function on unless I created %hash myself
4022 because the internal iterator may not have started at base.