git-svn: avoid crashing svnserve when creating new directories
[git/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 }
8164b652 488 $_prefix = '' unless defined $_prefix;
dadc6d2a
EW
489 if (defined $url) {
490 $url =~ s#/+$##;
491 init_subdir(@_);
492 }
f30603fc 493 do_git_init_db();
98327e58 494 if (defined $_trunk) {
706587fc
EW
495 my $trunk_ref = $_prefix . 'trunk';
496 # try both old-style and new-style lookups:
497 my $gs_trunk = eval { Git::SVN->new($trunk_ref) };
8164b652 498 unless ($gs_trunk) {
706587fc
EW
499 my ($trunk_url, $trunk_path) =
500 complete_svn_url($url, $_trunk);
501 $gs_trunk = Git::SVN->init($trunk_url, $trunk_path,
502 undef, $trunk_ref);
98327e58 503 }
c35b96e7 504 }
706587fc 505 return unless defined $_branches || defined $_tags;
e7db67e6
EW
506 my $ra = $url ? Git::SVN::Ra->new($url) : undef;
507 complete_url_ls_init($ra, $_branches, '--branches/-b', $_prefix);
508 complete_url_ls_init($ra, $_tags, '--tags/-t', $_prefix . 'tags/');
9d55b41a
EW
509}
510
1c8443b0 511sub cmd_multi_fetch {
0af9c9f9
EW
512 my $remotes = Git::SVN::read_all_remotes();
513 foreach my $repo_id (sort keys %$remotes) {
db03cd24 514 if ($remotes->{$repo_id}->{url}) {
4bb9ed04
EW
515 Git::SVN::fetch_all($repo_id, $remotes);
516 }
9d55b41a 517 }
9d55b41a
EW
518}
519
44320b9e
EW
520# this command is special because it requires no metadata
521sub cmd_commit_diff {
522 my ($ta, $tb, $url) = @_;
523 my $usage = "Usage: $0 commit-diff -r<revision> ".
524 "<tree-ish> <tree-ish> [<URL>]\n";
525 fatal($usage) if (!defined $ta || !defined $tb);
d3a840dc 526 my $svn_path;
44320b9e
EW
527 if (!defined $url) {
528 my $gs = eval { Git::SVN->new };
529 if (!$gs) {
530 fatal("Needed URL or usable git-svn --id in ",
531 "the command-line\n", $usage);
532 }
533 $url = $gs->{url};
d3a840dc 534 $svn_path = $gs->{path};
44320b9e
EW
535 }
536 unless (defined $_revision) {
537 fatal("-r|--revision is a required argument\n", $usage);
538 }
539 if (defined $_message && defined $_file) {
540 fatal("Both --message/-m and --file/-F specified ",
541 "for the commit message.\n",
542 "I have no idea what you mean\n");
543 }
544 if (defined $_file) {
545 $_message = file_to_s($_file);
546 } else {
547 $_message ||= get_commit_entry($tb)->{log};
548 }
549 my $ra ||= Git::SVN::Ra->new($url);
d3a840dc 550 $svn_path ||= $ra->{svn_path};
44320b9e
EW
551 my $r = $_revision;
552 if ($r eq 'HEAD') {
553 $r = $ra->get_latest_revnum;
554 } elsif ($r !~ /^\d+$/) {
555 die "revision argument: $r not understood by git-svn\n";
556 }
61395354
EW
557 my %ed_opts = ( r => $r,
558 log => $_message,
559 ra => $ra,
560 tree_a => $ta,
561 tree_b => $tb,
562 editor_cb => sub { print "Committed r$_[0]\n" },
563 svn_path => $svn_path );
564 if (!SVN::Git::Editor->new(\%ed_opts)->apply_diff) {
44320b9e
EW
565 print "No changes\n$ta == $tb\n";
566 }
44320b9e
EW
567}
568
3397f9df
EW
569########################### utility functions #########################
570
905f8b7d
EW
571sub rebase_cmd {
572 my @cmd = qw/rebase/;
573 push @cmd, '-v' if $_verbose;
574 push @cmd, qw/--merge/ if $_merge;
575 push @cmd, "--strategy=$_strategy" if $_strategy;
576 @cmd;
577}
578
1e889ef3
EW
579sub post_fetch_checkout {
580 return if $_no_checkout;
581 my $gs = $Git::SVN::_head or return;
582 return if verify_ref('refs/heads/master^0');
583
584 my $valid_head = verify_ref('HEAD^0');
585 command_noisy(qw(update-ref refs/heads/master), $gs->refname);
586 return if ($valid_head || !verify_ref('HEAD^0'));
587
588 return if $ENV{GIT_DIR} !~ m#^(?:.*/)?\.git$#;
589 my $index = $ENV{GIT_INDEX_FILE} || "$ENV{GIT_DIR}/index";
590 return if -f $index;
591
592 chomp(my $bare = `git config --bool --get core.bare`);
593 return if $bare eq 'true';
594 return if command_oneline(qw/rev-parse --is-inside-git-dir/) eq 'true';
595 command_noisy(qw/read-tree -m -u -v HEAD HEAD/);
596 print STDERR "Checked out HEAD:\n ",
597 $gs->full_url, " r", $gs->last_rev, "\n";
598}
599
98327e58
EW
600sub complete_svn_url {
601 my ($url, $path) = @_;
602 $path =~ s#/+$##;
98327e58 603 if ($path !~ m#^[a-z\+]+://#) {
98327e58
EW
604 if (!defined $url || $url !~ m#^[a-z\+]+://#) {
605 fatal("E: '$path' is not a complete URL ",
606 "and a separate URL is not specified\n");
607 }
706587fc 608 return ($url, $path);
98327e58 609 }
706587fc 610 return ($path, '');
98327e58
EW
611}
612
9d55b41a 613sub complete_url_ls_init {
706587fc
EW
614 my ($ra, $repo_path, $switch, $pfx) = @_;
615 unless ($repo_path) {
9d55b41a
EW
616 print STDERR "W: $switch not specified\n";
617 return;
618 }
706587fc
EW
619 $repo_path =~ s#/+$##;
620 if ($repo_path =~ m#^[a-z\+]+://#) {
621 $ra = Git::SVN::Ra->new($repo_path);
622 $repo_path = '';
e7db67e6 623 } else {
706587fc 624 $repo_path =~ s#^/+##;
e7db67e6 625 unless ($ra) {
706587fc 626 fatal("E: '$repo_path' is not a complete URL ",
e7db67e6 627 "and a separate URL is not specified\n");
8164b652 628 }
e7db67e6 629 }
706587fc 630 my $url = $ra->{url};
b4d57e5e
EW
631 my $gs = Git::SVN->init($url, undef, undef, undef, 1);
632 my $k = "svn-remote.$gs->{repo_id}.url";
633 my $orig_url = eval { command_oneline(qw/config --get/, $k) };
634 if ($orig_url && ($orig_url ne $gs->{url})) {
635 die "$k already set: $orig_url\n",
636 "wanted to set to: $gs->{url}\n";
88cf4107 637 }
b4d57e5e
EW
638 command_oneline('config', $k, $gs->{url}) unless $orig_url;
639 my $remote_path = "$ra->{svn_path}/$repo_path/*";
640 $remote_path =~ s#/+#/#g;
641 $remote_path =~ s#^/##g;
642 my ($n) = ($switch =~ /^--(\w+)/);
643 if (length $pfx && $pfx !~ m#/$#) {
644 die "--prefix='$pfx' must have a trailing slash '/'\n";
9d55b41a 645 }
b4d57e5e
EW
646 command_noisy('config', "svn-remote.$gs->{repo_id}.$n",
647 "$remote_path:refs/remotes/$pfx*");
9d55b41a
EW
648}
649
aef4e921
EW
650sub verify_ref {
651 my ($ref) = @_;
2c5c1d53
EW
652 eval { command_oneline([ 'rev-parse', '--verify', $ref ],
653 { STDERR => 0 }); };
aef4e921
EW
654}
655
a5e0cedc 656sub get_tree_from_treeish {
cf52b8f0 657 my ($treeish) = @_;
44320b9e 658 # $treeish can be a symbolic ref, too:
aef4e921 659 my $type = command_oneline(qw/cat-file -t/, $treeish);
cf52b8f0
EW
660 my $expected;
661 while ($type eq 'tag') {
aef4e921 662 ($treeish, $type) = command(qw/cat-file tag/, $treeish);
cf52b8f0
EW
663 }
664 if ($type eq 'commit') {
aef4e921
EW
665 $expected = (grep /^tree /, command(qw/cat-file commit/,
666 $treeish))[0];
44320b9e 667 ($expected) = ($expected =~ /^tree ($sha1)$/o);
cf52b8f0
EW
668 die "Unable to get tree from $treeish\n" unless $expected;
669 } elsif ($type eq 'tree') {
670 $expected = $treeish;
671 } else {
672 die "$treeish is a $type, expected tree, tag or commit\n";
673 }
a5e0cedc
EW
674 return $expected;
675}
676
44320b9e
EW
677sub get_commit_entry {
678 my ($treeish) = shift;
679 my %log_entry = ( log => '', tree => get_tree_from_treeish($treeish) );
680 my $commit_editmsg = "$ENV{GIT_DIR}/COMMIT_EDITMSG";
681 my $commit_msg = "$ENV{GIT_DIR}/COMMIT_MSG";
682 open my $log_fh, '>', $commit_editmsg or croak $!;
3397f9df 683
44320b9e 684 my $type = command_oneline(qw/cat-file -t/, $treeish);
4ad4515d 685 if ($type eq 'commit' || $type eq 'tag') {
aef4e921 686 my ($msg_fh, $ctx) = command_output_pipe('cat-file',
44320b9e 687 $type, $treeish);
3397f9df
EW
688 my $in_msg = 0;
689 while (<$msg_fh>) {
690 if (!$in_msg) {
691 $in_msg = 1 if (/^\s*$/);
df746c5a 692 } elsif (/^git-svn-id: /) {
44320b9e
EW
693 # skip this for now, we regenerate the
694 # correct one on re-fetch anyways
695 # TODO: set *:merge properties or like...
3397f9df 696 } else {
44320b9e 697 print $log_fh $_ or croak $!;
3397f9df
EW
698 }
699 }
aef4e921 700 command_close_pipe($msg_fh, $ctx);
3397f9df 701 }
44320b9e 702 close $log_fh or croak $!;
3397f9df
EW
703
704 if ($_edit || ($type eq 'tree')) {
705 my $editor = $ENV{VISUAL} || $ENV{EDITOR} || 'vi';
44320b9e
EW
706 # TODO: strip out spaces, comments, like git-commit.sh
707 system($editor, $commit_editmsg);
3397f9df 708 }
44320b9e
EW
709 rename $commit_editmsg, $commit_msg or croak $!;
710 open $log_fh, '<', $commit_msg or croak $!;
711 { local $/; chomp($log_entry{log} = <$log_fh>); }
712 close $log_fh or croak $!;
713 unlink $commit_msg;
714 \%log_entry;
a5e0cedc
EW
715}
716
3397f9df
EW
717sub s_to_file {
718 my ($str, $file, $mode) = @_;
719 open my $fd,'>',$file or croak $!;
720 print $fd $str,"\n" or croak $!;
721 close $fd or croak $!;
722 chmod ($mode &~ umask, $file) if (defined $mode);
723}
724
725sub file_to_s {
726 my $file = shift;
727 open my $fd,'<',$file or croak "$!: file: $file\n";
728 local $/;
729 my $ret = <$fd>;
730 close $fd or croak $!;
731 $ret =~ s/\s*$//s;
732 return $ret;
733}
734
eeb0abe0
EW
735# '<svn username> = real-name <email address>' mapping based on git-svnimport:
736sub load_authors {
737 open my $authors, '<', $_authors or die "Can't open $_authors $!\n";
f8c9d1d2 738 my $log = $cmd eq 'log';
eeb0abe0
EW
739 while (<$authors>) {
740 chomp;
8815788e 741 next unless /^(\S+?|\(no author\))\s*=\s*(.+?)\s*<(.+)>\s*$/;
eeb0abe0 742 my ($user, $name, $email) = ($1, $2, $3);
f8c9d1d2
EW
743 if ($log) {
744 $Git::SVN::Log::rusers{"$name <$email>"} = $user;
745 } else {
746 $users{$user} = [$name, $email];
747 }
79bb8d88
EW
748 }
749 close $authors or croak $!;
750}
751
e0d10e1c 752# convert GetOpt::Long specs for use by git-config
b8c92cad 753sub read_repo_config {
706587fc 754 return unless -d $ENV{GIT_DIR};
b8c92cad 755 my $opts = shift;
97ae0911 756 my @config_only;
b8c92cad 757 foreach my $o (keys %$opts) {
97ae0911
EW
758 # if we have mixedCase and a long option-only, then
759 # it's a config-only variable that we don't need for
760 # the command-line.
761 push @config_only, $o if ($o =~ /[A-Z]/ && $o =~ /^[a-z]+$/i);
b8c92cad 762 my $v = $opts->{$o};
97ae0911 763 my ($key) = ($o =~ /^([a-zA-Z\-]+)/);
b8c92cad 764 $key =~ s/-//g;
e0d10e1c 765 my $arg = 'git-config';
b8c92cad
EW
766 $arg .= ' --int' if ($o =~ /[:=]i$/);
767 $arg .= ' --bool' if ($o !~ /[:=][sfi]$/);
768 if (ref $v eq 'ARRAY') {
769 chomp(my @tmp = `$arg --get-all svn.$key`);
770 @$v = @tmp if @tmp;
771 } else {
772 chomp(my $tmp = `$arg --get svn.$key`);
7774284a 773 if ($tmp && !($arg =~ / --bool/ && $tmp eq 'false')) {
b8c92cad
EW
774 $$v = $tmp;
775 }
776 }
777 }
97ae0911 778 delete @$opts{@config_only} if @config_only;
b8c92cad
EW
779}
780
79bb8d88 781sub extract_metadata {
c1927a85 782 my $id = shift or return (undef, undef, undef);
79bb8d88
EW
783 my ($url, $rev, $uuid) = ($id =~ /^git-svn-id:\s(\S+?)\@(\d+)
784 \s([a-f\d\-]+)$/x);
e70dc780 785 if (!defined $rev || !$uuid || !$url) {
79bb8d88 786 # some of the original repositories I made had
82e5a82f 787 # identifiers like this:
79bb8d88
EW
788 ($rev, $uuid) = ($id =~/^git-svn-id:\s(\d+)\@([a-f\d\-]+)/);
789 }
790 return ($url, $rev, $uuid);
791}
792
c1927a85
EW
793sub cmt_metadata {
794 return extract_metadata((grep(/^git-svn-id: /,
aef4e921 795 command(qw/cat-file commit/, shift)))[-1]);
c1927a85
EW
796}
797
905f8b7d
EW
798sub working_head_info {
799 my ($head, $refs) = @_;
905f8b7d 800 my ($fh, $ctx) = command_output_pipe('rev-list', $head);
b03c7a63
AR
801 while (my $hash = <$fh>) {
802 chomp($hash);
803 my ($url, $rev, $uuid) = cmt_metadata($hash);
13c823fb
EW
804 if (defined $url && defined $rev) {
805 if (my $gs = Git::SVN->find_by_url($url)) {
806 my $c = $gs->rev_db_get($rev);
b03c7a63 807 if ($c && $c eq $hash) {
13c823fb
EW
808 close $fh; # break the pipe
809 return ($url, $rev, $uuid, $gs);
810 }
811 }
812 }
b03c7a63 813 unshift @$refs, $hash if $refs;
905f8b7d 814 }
13c823fb
EW
815 command_close_pipe($fh, $ctx);
816 (undef, undef, undef, undef);
905f8b7d
EW
817}
818
9b981fc6
EW
819package Git::SVN;
820use strict;
821use warnings;
ecc712dd 822use vars qw/$default_repo_id $default_ref_id $_no_metadata $_follow_parent
62e349d2 823 $_repack $_repack_flags $_use_svm_props $_head
4a1bb4c3 824 $_use_svnsync_props $no_reuse_existing $_minimize_url/;
9b981fc6
EW
825use Carp qw/croak/;
826use File::Path qw/mkpath/;
373274f9 827use File::Copy qw/copy/;
9b981fc6
EW
828use IPC::Open3;
829
ecc712dd 830my $_repack_nr;
9b981fc6
EW
831# properties that we do not log:
832my %SKIP_PROP;
833BEGIN {
834 %SKIP_PROP = map { $_ => 1 } qw/svn:wc:ra_dav:version-url
835 svn:special svn:executable
836 svn:entry:committed-rev
837 svn:entry:last-author
838 svn:entry:uuid
839 svn:entry:committed-date/;
91b03282
EW
840
841 # some options are read globally, but can be overridden locally
842 # per [svn-remote "..."] section. Command-line options will *NOT*
843 # override options set in an [svn-remote "..."] section
844 my $e;
62e349d2
EW
845 foreach (qw/follow_parent no_metadata use_svm_props
846 use_svnsync_props/) {
91b03282
EW
847 my $key = $_;
848 $key =~ tr/_//d;
849 $e .= "sub $_ {
850 my (\$self) = \@_;
851 return \$self->{-$_} if exists \$self->{-$_};
852 my \$k = \"svn-remote.\$self->{repo_id}\.$key\";
853 eval { command_oneline(qw/config --get/, \$k) };
854 if (\$@) {
855 \$self->{-$_} = \$Git::SVN::_$_;
856 } else {
857 my \$v = command_oneline(qw/config --bool/,\$k);
858 \$self->{-$_} = \$v eq 'false' ? 0 : 1;
859 }
860 return \$self->{-$_} }\n";
861 }
862 $e .= "1;\n";
863 eval $e or die $@;
9b981fc6
EW
864}
865
373274f9
EW
866my %LOCKFILES;
867END { unlink keys %LOCKFILES if %LOCKFILES }
868
4bb9ed04
EW
869sub resolve_local_globs {
870 my ($url, $fetch, $glob_spec) = @_;
871 return unless defined $glob_spec;
872 my $ref = $glob_spec->{ref};
873 my $path = $glob_spec->{path};
874 foreach (command(qw#for-each-ref --format=%(refname) refs/remotes#)) {
875 next unless m#^refs/remotes/$ref->{regex}$#;
876 my $p = $1;
877 my $pathname = $path->full_path($p);
878 my $refname = $ref->full_path($p);
879 if (my $existing = $fetch->{$pathname}) {
880 if ($existing ne $refname) {
881 die "Refspec conflict:\n",
882 "existing: refs/remotes/$existing\n",
883 " globbed: refs/remotes/$refname\n";
884 }
885 my $u = (::cmt_metadata("refs/remotes/$refname"))[0];
4e9f6cc7 886 $u =~ s!^\Q$url\E(/|$)!! or die
4bb9ed04
EW
887 "refs/remotes/$refname: '$url' not found in '$u'\n";
888 if ($pathname ne $u) {
889 warn "W: Refspec glob conflict ",
890 "(ref: refs/remotes/$refname):\n",
891 "expected path: $pathname\n",
892 " real path: $u\n",
893 "Continuing ahead with $u\n";
894 next;
895 }
896 } else {
4bb9ed04
EW
897 $fetch->{$pathname} = $refname;
898 }
899 }
900}
901
e98671e5
EW
902sub parse_revision_argument {
903 my ($base, $head) = @_;
904 if (!defined $::_revision || $::_revision eq 'BASE:HEAD') {
905 return ($base, $head);
906 }
907 return ($1, $2) if ($::_revision =~ /^(\d+):(\d+)$/);
908 return ($::_revision, $::_revision) if ($::_revision =~ /^\d+$/);
909 return ($head, $head) if ($::_revision eq 'HEAD');
910 return ($base, $1) if ($::_revision =~ /^BASE:(\d+)$/);
911 return ($1, $head) if ($::_revision =~ /^(\d+):HEAD$/);
912 die "revision argument: $::_revision not understood by git-svn\n";
913}
914
0af9c9f9 915sub fetch_all {
4bb9ed04 916 my ($repo_id, $remotes) = @_;
905f8b7d
EW
917 if (ref $repo_id) {
918 my $gs = $repo_id;
919 $repo_id = undef;
920 $repo_id = $gs->{repo_id};
921 }
922 $remotes ||= read_all_remotes();
7447b4bc
EW
923 my $remote = $remotes->{$repo_id} or
924 die "[svn-remote \"$repo_id\"] unknown\n";
e518192f 925 my $fetch = $remote->{fetch};
7447b4bc 926 my $url = $remote->{url} or die "svn-remote.$repo_id.url not defined\n";
e518192f 927 my (@gs, @globs);
0af9c9f9 928 my $ra = Git::SVN::Ra->new($url);
26a62d57 929 my $uuid = $ra->get_uuid;
0af9c9f9 930 my $head = $ra->get_latest_revnum;
28710f74 931 my $base = defined $fetch ? $head : 0;
e518192f
EW
932
933 # read the max revs for wildcard expansion (branches/*, tags/*)
934 foreach my $t (qw/branches tags/) {
935 defined $remote->{$t} or next;
936 push @globs, $remote->{$t};
93f2689c
EW
937 my $max_rev = eval { tmp_config(qw/--int --get/,
938 "svn-remote.$repo_id.${t}-maxRev") };
939 if (defined $max_rev && ($max_rev < $base)) {
940 $base = $max_rev;
d6d3346b
EW
941 } elsif (!defined $max_rev) {
942 $base = 0;
e518192f
EW
943 }
944 }
945
db03cd24
EW
946 if ($fetch) {
947 foreach my $p (sort keys %$fetch) {
948 my $gs = Git::SVN->new($fetch->{$p}, $repo_id, $p);
949 my $lr = $gs->rev_db_max;
950 if (defined $lr) {
951 $base = $lr if ($lr < $base);
952 }
953 push @gs, $gs;
0af9c9f9 954 }
0af9c9f9 955 }
e98671e5
EW
956
957 ($base, $head) = parse_revision_argument($base, $head);
e518192f 958 $ra->gs_fetch_loop_common($base, $head, \@gs, \@globs);
0af9c9f9
EW
959}
960
47e39c55
EW
961sub read_all_remotes {
962 my $r = {};
8b8fc068 963 foreach (grep { s/^svn-remote\.// } command(qw/config -l/)) {
47e39c55
EW
964 if (m!^(.+)\.fetch=\s*(.*)\s*:\s*refs/remotes/(.+)\s*$!) {
965 $r->{$1}->{fetch}->{$2} = $3;
966 } elsif (m!^(.+)\.url=\s*(.*)\s*$!) {
967 $r->{$1}->{url} = $2;
4bb9ed04
EW
968 } elsif (m!^(.+)\.(branches|tags)=
969 (.*):refs/remotes/(.+)\s*$/!x) {
970 my ($p, $g) = ($3, $4);
971 my $rs = $r->{$1}->{$2} = {
e518192f 972 t => $2,
93f2689c 973 remote => $1,
4bb9ed04
EW
974 path => Git::SVN::GlobSpec->new($p),
975 ref => Git::SVN::GlobSpec->new($g) };
976 if (length($rs->{ref}->{right}) != 0) {
977 die "The '*' glob character must be the last ",
978 "character of '$g'\n";
979 }
47e39c55
EW
980 }
981 }
982 $r;
983}
984
ecc712dd
EW
985sub init_vars {
986 if (defined $_repack) {
987 $_repack = 1000 if ($_repack <= 0);
988 $_repack_nr = $_repack;
989 $_repack_flags ||= '-d';
990 }
991}
992
b805b44a 993sub verify_remotes_sanity {
536c4b09 994 return unless -d $ENV{GIT_DIR};
b805b44a
EW
995 my %seen;
996 foreach (command(qw/config -l/)) {
997 if (m!^svn-remote\.(?:.+)\.fetch=.*:refs/remotes/(\S+)\s*$!) {
998 if ($seen{$1}) {
999 die "Remote ref refs/remote/$1 is tracked by",
1000 "\n \"$_\"\nand\n \"$seen{$1}\"\n",
1001 "Please resolve this ambiguity in ",
1002 "your git configuration file before ",
1003 "continuing\n";
1004 }
1005 $seen{$1} = $_;
1006 }
1007 }
1008}
1009
47e39c55 1010# we allow more chars than remotes2config.sh...
706587fc
EW
1011sub sanitize_remote_name {
1012 my ($name) = @_;
47e39c55 1013 $name =~ tr{A-Za-z0-9:,/+-}{.}c;
706587fc
EW
1014 $name;
1015}
1016
e6434f87
EW
1017sub find_existing_remote {
1018 my ($url, $remotes) = @_;
befc9adc 1019 return undef if $no_reuse_existing;
e6434f87
EW
1020 my $existing;
1021 foreach my $repo_id (keys %$remotes) {
1022 my $u = $remotes->{$repo_id}->{url} or next;
1023 next if $u ne $url;
1024 $existing = $repo_id;
1025 last;
1026 }
1027 $existing;
1028}
b805b44a 1029
e6434f87 1030sub init_remote_config {
d8115c51 1031 my ($self, $url, $no_write) = @_;
e6434f87
EW
1032 $url =~ s!/+$!!; # strip trailing slash
1033 my $r = read_all_remotes();
1034 my $existing = find_existing_remote($url, $r);
1035 if ($existing) {
e518192f
EW
1036 unless ($no_write) {
1037 print STDERR "Using existing ",
1038 "[svn-remote \"$existing\"]\n";
1039 }
e6434f87 1040 $self->{repo_id} = $existing;
4a1bb4c3 1041 } elsif ($_minimize_url) {
e6434f87
EW
1042 my $min_url = Git::SVN::Ra->new($url)->minimize_url;
1043 $existing = find_existing_remote($min_url, $r);
1044 if ($existing) {
e518192f
EW
1045 unless ($no_write) {
1046 print STDERR "Using existing ",
1047 "[svn-remote \"$existing\"]\n";
1048 }
e6434f87
EW
1049 $self->{repo_id} = $existing;
1050 }
1051 if ($min_url ne $url) {
e518192f
EW
1052 unless ($no_write) {
1053 print STDERR "Using higher level of URL: ",
1054 "$url => $min_url\n";
1055 }
e6434f87
EW
1056 my $old_path = $self->{path};
1057 $self->{path} = $url;
4e9f6cc7 1058 $self->{path} =~ s!^\Q$min_url\E(/|$)!!;
e6434f87
EW
1059 if (length $old_path) {
1060 $self->{path} .= "/$old_path";
1061 }
1062 $url = $min_url;
1063 }
1064 }
1065 my $orig_url;
1066 if (!$existing) {
b805b44a 1067 # verify that we aren't overwriting anything:
e6434f87 1068 $orig_url = eval {
706587fc 1069 command_oneline('config', '--get',
e6434f87 1070 "svn-remote.$self->{repo_id}.url")
706587fc 1071 };
b805b44a 1072 if ($orig_url && ($orig_url ne $url)) {
e6434f87 1073 die "svn-remote.$self->{repo_id}.url already set: ",
b805b44a
EW
1074 "$orig_url\nwanted to set to: $url\n";
1075 }
9b981fc6 1076 }
e6434f87
EW
1077 my ($xrepo_id, $xpath) = find_ref($self->refname);
1078 if (defined $xpath) {
1079 die "svn-remote.$xrepo_id.fetch already set to track ",
1080 "$xpath:refs/remotes/", $self->refname, "\n";
1081 }
d8115c51
EW
1082 unless ($no_write) {
1083 command_noisy('config',
1084 "svn-remote.$self->{repo_id}.url", $url);
1085 command_noisy('config', '--add',
1086 "svn-remote.$self->{repo_id}.fetch",
1087 "$self->{path}:".$self->refname);
1088 }
9b981fc6 1089 $self->{url} = $url;
e6434f87
EW
1090}
1091
a8ae2623
EW
1092sub find_by_url { # repos_root and, path are optional
1093 my ($class, $full_url, $repos_root, $path) = @_;
56973d20 1094
1a97a506 1095 return undef unless defined $full_url;
56973d20
AR
1096 remove_username($full_url);
1097 remove_username($repos_root) if defined $repos_root;
a8ae2623
EW
1098 my $remotes = read_all_remotes();
1099 if (defined $full_url && defined $repos_root && !defined $path) {
1100 $path = $full_url;
1101 $path =~ s#^\Q$repos_root\E(?:/|$)##;
1102 }
1103 foreach my $repo_id (keys %$remotes) {
1104 my $u = $remotes->{$repo_id}->{url} or next;
56973d20 1105 remove_username($u);
a8ae2623
EW
1106 next if defined $repos_root && $repos_root ne $u;
1107
1108 my $fetch = $remotes->{$repo_id}->{fetch} || {};
1109 foreach (qw/branches tags/) {
1110 resolve_local_globs($u, $fetch,
1111 $remotes->{$repo_id}->{$_});
1112 }
1113 my $p = $path;
1114 unless (defined $p) {
1115 $p = $full_url;
1116 $p =~ s#^\Q$u\E(?:/|$)## or next;
1117 }
1118 foreach my $f (keys %$fetch) {
1119 next if $f ne $p;
1120 return Git::SVN->new($fetch->{$f}, $repo_id, $f);
1121 }
1122 }
1123 undef;
1124}
1125
e6434f87 1126sub init {
d8115c51 1127 my ($class, $url, $path, $repo_id, $ref_id, $no_write) = @_;
e6434f87
EW
1128 my $self = _new($class, $repo_id, $ref_id, $path);
1129 if (defined $url) {
d8115c51 1130 $self->init_remote_config($url, $no_write);
e6434f87 1131 }
9b981fc6
EW
1132 $self;
1133}
1134
706587fc
EW
1135sub find_ref {
1136 my ($ref_id) = @_;
1137 foreach (command(qw/config -l/)) {
1138 next unless m!^svn-remote\.(.+)\.fetch=
1139 \s*(.*)\s*:\s*refs/remotes/(.+)\s*$!x;
1140 my ($repo_id, $path, $ref) = ($1, $2, $3);
1141 if ($ref eq $ref_id) {
1142 $path = '' if ($path =~ m#^\./?#);
1143 return ($repo_id, $path);
1144 }
1145 }
1146 (undef, undef, undef);
1147}
1148
9b981fc6 1149sub new {
706587fc
EW
1150 my ($class, $ref_id, $repo_id, $path) = @_;
1151 if (defined $ref_id && !defined $repo_id && !defined $path) {
1152 ($repo_id, $path) = find_ref($ref_id);
1153 if (!defined $repo_id) {
1154 die "Could not find a \"svn-remote.*.fetch\" key ",
1155 "in the repository configuration matching: ",
1156 "refs/remotes/$ref_id\n";
1157 }
1158 }
1159 my $self = _new($class, $repo_id, $ref_id, $path);
8b8fc068
EW
1160 if (!defined $self->{path} || !length $self->{path}) {
1161 my $fetch = command_oneline('config', '--get',
1162 "svn-remote.$repo_id.fetch",
1163 ":refs/remotes/$ref_id\$") or
1164 die "Failed to read \"svn-remote.$repo_id.fetch\" ",
1165 "\":refs/remotes/$ref_id\$\" in config\n";
1166 ($self->{path}, undef) = split(/\s*:\s*/, $fetch);
1167 }
706587fc
EW
1168 $self->{url} = command_oneline('config', '--get',
1169 "svn-remote.$repo_id.url") or
1170 die "Failed to read \"svn-remote.$repo_id.url\" in config\n";
d6d3346b 1171 $self->rebuild;
9b981fc6
EW
1172 $self;
1173}
1174
706587fc 1175sub refname { "refs/remotes/$_[0]->{ref_id}" }
9b981fc6 1176
26a62d57
EW
1177sub svm_uuid {
1178 my ($self) = @_;
1179 return $self->{svm}->{uuid} if $self->svm;
1180 $self->ra;
1181 unless ($self->{svm}) {
1182 die "SVM UUID not cached, and reading remotely failed\n";
1183 }
1184 $self->{svm}->{uuid};
1185}
8a49ee97 1186
26a62d57
EW
1187sub svm {
1188 my ($self) = @_;
1189 return $self->{svm} if $self->{svm};
1190 my $svm;
8a49ee97
EW
1191 # see if we have it in our config, first:
1192 eval {
26a62d57
EW
1193 my $section = "svn-remote.$self->{repo_id}";
1194 $svm = {
93f2689c
EW
1195 source => tmp_config('--get', "$section.svm-source"),
1196 uuid => tmp_config('--get', "$section.svm-uuid"),
befc9adc 1197 replace => tmp_config('--get', "$section.svm-replace"),
8a49ee97
EW
1198 }
1199 };
befc9adc
EW
1200 if ($svm && $svm->{source} && $svm->{uuid} && $svm->{replace}) {
1201 $self->{svm} = $svm;
1202 }
26a62d57
EW
1203 $self->{svm};
1204}
1205
1206sub _set_svm_vars {
1207 my ($self, $ra) = @_;
db03cd24
EW
1208 return $ra if $self->svm;
1209
1210 my @err = ( "useSvmProps set, but failed to read SVM properties\n",
befc9adc 1211 "(svm:source, svm:uuid) ",
db03cd24
EW
1212 "from the following URLs:\n" );
1213 sub read_svm_props {
befc9adc
EW
1214 my ($self, $ra, $path, $r) = @_;
1215 my $props = ($ra->get_dir($path, $r))[2];
db03cd24 1216 my $src = $props->{'svm:source'};
db03cd24 1217 my $uuid = $props->{'svm:uuid'};
befc9adc 1218 return undef if (!$src || !$uuid);
26a62d57 1219
befc9adc 1220 chomp($src, $uuid);
26a62d57 1221
db03cd24
EW
1222 $uuid =~ m{^[0-9a-f\-]{30,}$}
1223 or die "doesn't look right - svm:uuid is '$uuid'\n";
befc9adc
EW
1224
1225 # the '!' is used to mark the repos_root!/relative/path
1226 $src =~ s{/?!/?}{/};
db03cd24 1227 $src =~ s{/+$}{}; # no trailing slashes please
befc9adc 1228 # username is of no interest
8a49ee97 1229 $src =~ s{(^[a-z\+]*://)[^/@]*@}{$1};
8a49ee97 1230
befc9adc
EW
1231 my $replace = $ra->{url};
1232 $replace .= "/$path" if length $path;
1233
db03cd24 1234 my $section = "svn-remote.$self->{repo_id}";
befc9adc
EW
1235 tmp_config("$section.svm-source", $src);
1236 tmp_config("$section.svm-replace", $replace);
1237 tmp_config("$section.svm-uuid", $uuid);
1238 $self->{svm} = {
1239 source => $src,
1240 uuid => $uuid,
1241 replace => $replace
1242 };
db03cd24
EW
1243 }
1244
1245 my $r = $ra->get_latest_revnum;
1246 my $path = $self->{path};
befc9adc 1247 my %tried;
db03cd24 1248 while (length $path) {
befc9adc
EW
1249 unless ($tried{"$self->{url}/$path"}) {
1250 return $ra if $self->read_svm_props($ra, $path, $r);
1251 $tried{"$self->{url}/$path"} = 1;
db03cd24 1252 }
befc9adc 1253 $path =~ s#/?[^/]+$##;
8a49ee97 1254 }
befc9adc
EW
1255 die "Path: '$path' should be ''\n" if $path ne '';
1256 return $ra if $self->read_svm_props($ra, $path, $r);
1257 $tried{"$self->{url}/$path"} = 1;
db03cd24
EW
1258
1259 if ($ra->{repos_root} eq $self->{url}) {
befc9adc 1260 die @err, (map { " $_\n" } keys %tried), "\n";
db03cd24
EW
1261 }
1262
1263 # nope, make sure we're connected to the repository root:
1264 my $ok;
1265 my @tried_b;
1266 $path = $ra->{svn_path};
db03cd24
EW
1267 $ra = Git::SVN::Ra->new($ra->{repos_root});
1268 while (length $path) {
befc9adc
EW
1269 unless ($tried{"$ra->{url}/$path"}) {
1270 $ok = $self->read_svm_props($ra, $path, $r);
1271 last if $ok;
1272 $tried{"$ra->{url}/$path"} = 1;
1273 }
1274 $path =~ s#/?[^/]+$##;
db03cd24 1275 }
befc9adc
EW
1276 die "Path: '$path' should be ''\n" if $path ne '';
1277 $ok ||= $self->read_svm_props($ra, $path, $r);
1278 $tried{"$ra->{url}/$path"} = 1;
db03cd24 1279 if (!$ok) {
befc9adc 1280 die @err, (map { " $_\n" } keys %tried), "\n";
db03cd24
EW
1281 }
1282 Git::SVN::Ra->new($self->{url});
8a49ee97
EW
1283}
1284
62e349d2
EW
1285sub svnsync {
1286 my ($self) = @_;
1287 return $self->{svnsync} if $self->{svnsync};
1288
1289 if ($self->no_metadata) {
1290 die "Can't have both 'noMetadata' and ",
1291 "'useSvnsyncProps' options set!\n";
1292 }
1293 if ($self->rewrite_root) {
1294 die "Can't have both 'useSvnsyncProps' and 'rewriteRoot' ",
1295 "options set!\n";
1296 }
1297
1298 my $svnsync;
1299 # see if we have it in our config, first:
1300 eval {
1301 my $section = "svn-remote.$self->{repo_id}";
1302 $svnsync = {
1303 url => tmp_config('--get', "$section.svnsync-url"),
1304 uuid => tmp_config('--get', "$section.svnsync-uuid"),
1305 }
1306 };
1307 if ($svnsync && $svnsync->{url} && $svnsync->{uuid}) {
1308 return $self->{svnsync} = $svnsync;
1309 }
1310
1311 my $err = "useSvnsyncProps set, but failed to read " .
1312 "svnsync property: svn:sync-from-";
1313 my $rp = $self->ra->rev_proplist(0);
1314
1315 my $url = $rp->{'svn:sync-from-url'} or die $err . "url\n";
1316 $url =~ m{^[a-z\+]+://} or
1317 die "doesn't look right - svn:sync-from-url is '$url'\n";
1318
1319 my $uuid = $rp->{'svn:sync-from-uuid'} or die $err . "uuid\n";
1320 $uuid =~ m{^[0-9a-f\-]{30,}$} or
1321 die "doesn't look right - svn:sync-from-uuid is '$uuid'\n";
1322
1323 my $section = "svn-remote.$self->{repo_id}";
1324 tmp_config('--add', "$section.svnsync-uuid", $uuid);
1325 tmp_config('--add', "$section.svnsync-url", $url);
1326 return $self->{svnsync} = { url => $url, uuid => $uuid };
1327}
1328
26a62d57
EW
1329# this allows us to memoize our SVN::Ra UUID locally and avoid a
1330# remote lookup (useful for 'git svn log').
1331sub ra_uuid {
1332 my ($self) = @_;
1333 unless ($self->{ra_uuid}) {
1334 my $key = "svn-remote.$self->{repo_id}.uuid";
1335 my $uuid = eval { tmp_config('--get', $key) };
1336 if (!$@ && $uuid && $uuid =~ /^([a-f\d\-]{30,})$/) {
1337 $self->{ra_uuid} = $uuid;
1338 } else {
1339 die "ra_uuid called without URL\n" unless $self->{url};
1340 $self->{ra_uuid} = $self->ra->get_uuid;
1341 tmp_config('--add', $key, $self->{ra_uuid});
1342 }
1343 }
1344 $self->{ra_uuid};
1345}
1346
9b981fc6
EW
1347sub ra {
1348 my ($self) = shift;
8a49ee97 1349 my $ra = Git::SVN::Ra->new($self->{url});
91b03282
EW
1350 if ($self->use_svm_props && !$self->{svm}) {
1351 if ($self->no_metadata) {
97ae0911
EW
1352 die "Can't have both 'noMetadata' and ",
1353 "'useSvmProps' options set!\n";
62e349d2
EW
1354 } elsif ($self->use_svnsync_props) {
1355 die "Can't have both 'useSvnsyncProps' and ",
1356 "'useSvmProps' options set!\n";
91b03282 1357 }
26a62d57 1358 $ra = $self->_set_svm_vars($ra);
8a49ee97
EW
1359 $self->{-want_revprops} = 1;
1360 }
1361 $ra;
9b981fc6
EW
1362}
1363
15710b6f
EW
1364sub rel_path {
1365 my ($self) = @_;
1366 my $repos_root = $self->ra->{repos_root};
1367 return $self->{path} if ($self->{url} eq $repos_root);
0b59451c
EW
1368 my $url = $self->{url} .
1369 (length $self->{path} ? "/$self->{path}" : $self->{path});
1370 $url =~ s!^\Q$repos_root\E(?:/+|$)!!g;
1371 $url;
15710b6f
EW
1372}
1373
9b981fc6
EW
1374sub traverse_ignore {
1375 my ($self, $fh, $path, $r) = @_;
1376 $path =~ s#^/+##g;
5d3b7cd5
EW
1377 my $ra = $self->ra;
1378 my ($dirent, undef, $props) = $ra->get_dir($path, $r);
9b981fc6 1379 my $p = $path;
102a0a2d 1380 $p =~ s#^\Q$self->{path}\E(/|$)##;
9b981fc6
EW
1381 print $fh length $p ? "\n# $p\n" : "\n# /\n";
1382 if (my $s = $props->{'svn:ignore'}) {
1383 $s =~ s/[\r\n]+/\n/g;
1384 chomp $s;
1385 if (length $p == 0) {
1386 $s =~ s#\n#\n/$p#g;
1387 print $fh "/$s\n";
1388 } else {
1389 $s =~ s#\n#\n/$p/#g;
1390 print $fh "/$p/$s\n";
1391 }
1392 }
1393 foreach (sort keys %$dirent) {
0dc03d6a 1394 next if $dirent->{$_}->{kind} != $SVN::Node::dir;
9b981fc6
EW
1395 $self->traverse_ignore($fh, "$path/$_", $r);
1396 }
1397}
1398
3ebe8df7
EW
1399sub last_rev { ($_[0]->last_rev_commit)[0] }
1400sub last_commit { ($_[0]->last_rev_commit)[1] }
1401
9b981fc6
EW
1402# returns the newest SVN revision number and newest commit SHA1
1403sub last_rev_commit {
1404 my ($self) = @_;
1405 if (defined $self->{last_rev} && defined $self->{last_commit}) {
1406 return ($self->{last_rev}, $self->{last_commit});
1407 }
d2866f9e 1408 my $c = ::verify_ref($self->refname.'^0');
91b03282 1409 if ($c && !$self->use_svm_props && !$self->no_metadata) {
d2866f9e 1410 my $rev = (::cmt_metadata($c))[1];
9b981fc6
EW
1411 if (defined $rev) {
1412 ($self->{last_rev}, $self->{last_commit}) = ($rev, $c);
1413 return ($rev, $c);
1414 }
1415 }
26a62d57
EW
1416 my $db_path = $self->db_path;
1417 unless (-e $db_path) {
1418 ($self->{last_rev}, $self->{last_commit}) = (undef, undef);
1419 return (undef, undef);
1420 }
9b981fc6
EW
1421 my $offset = -41; # from tail
1422 my $rl;
26a62d57 1423 open my $fh, '<', $db_path or croak "$db_path not readable: $!\n";
ce4b4af7
EW
1424 sysseek($fh, $offset, 2); # don't care for errors
1425 sysread($fh, $rl, 41) == 41 or return (undef, undef);
9b981fc6 1426 chomp $rl;
ce4b4af7 1427 while (('0' x40) eq $rl && sysseek($fh, 0, 1) != 0) {
9b981fc6 1428 $offset -= 41;
ce4b4af7
EW
1429 sysseek($fh, $offset, 2); # don't care for errors
1430 sysread($fh, $rl, 41) == 41 or return (undef, undef);
9b981fc6
EW
1431 chomp $rl;
1432 }
91b03282 1433 if ($c && $c ne $rl) {
26a62d57 1434 die "$db_path and ", $self->refname,
9c93fee5
EW
1435 " inconsistent!:\n$c != $rl\n";
1436 }
ce4b4af7 1437 my $rev = sysseek($fh, 0, 1) or croak $!;
9b981fc6
EW
1438 $rev = ($rev - 41) / 41;
1439 close $fh or croak $!;
1440 ($self->{last_rev}, $self->{last_commit}) = ($rev, $c);
1441 return ($rev, $c);
1442}
1443
3ebe8df7
EW
1444sub get_fetch_range {
1445 my ($self, $min, $max) = @_;
1446 $max ||= $self->ra->get_latest_revnum;
9c93fee5 1447 $min ||= $self->rev_db_max;
3ebe8df7 1448 (++$min, $max);
9b981fc6
EW
1449}
1450
8a49ee97 1451sub tmp_config {
93f2689c 1452 my (@args) = @_;
b7e5348c
EW
1453 my $old_def_config = "$ENV{GIT_DIR}/svn/config";
1454 my $config = "$ENV{GIT_DIR}/svn/.metadata";
1455 if (-e $old_def_config && ! -e $config) {
1456 rename $old_def_config, $config or
1457 die "Failed rename $old_def_config => $config: $!\n";
1458 }
8a49ee97 1459 my $old_config = $ENV{GIT_CONFIG};
93f2689c 1460 $ENV{GIT_CONFIG} = $config;
8a49ee97 1461 $@ = undef;
b4d57e5e
EW
1462 my @ret = eval {
1463 unless (-f $config) {
1464 mkfile($config);
1465 open my $fh, '>', $config or
1466 die "Can't open $config: $!\n";
1467 print $fh "; This file is used internally by ",
1468 "git-svn\n" or die
1469 "Couldn't write to $config: $!\n";
1470 print $fh "; You should not have to edit it\n" or
1471 die "Couldn't write to $config: $!\n";
1472 close $fh or die "Couldn't close $config: $!\n";
1473 }
1474 command('config', @args);
1475 };
8a49ee97
EW
1476 my $err = $@;
1477 if (defined $old_config) {
1478 $ENV{GIT_CONFIG} = $old_config;
1479 } else {
1480 delete $ENV{GIT_CONFIG};
1481 }
1482 die $err if $err;
1483 wantarray ? @ret : $ret[0];
1484}
1485
9b981fc6
EW
1486sub tmp_index_do {
1487 my ($self, $sub) = @_;
1488 my $old_index = $ENV{GIT_INDEX_FILE};
1489 $ENV{GIT_INDEX_FILE} = $self->{index};
8a49ee97 1490 $@ = undef;
b4d57e5e
EW
1491 my @ret = eval {
1492 my ($dir, $base) = ($self->{index} =~ m#^(.*?)/?([^/]+)$#);
1493 mkpath([$dir]) unless -d $dir;
1494 &$sub;
1495 };
8a49ee97
EW
1496 my $err = $@;
1497 if (defined $old_index) {
9b981fc6
EW
1498 $ENV{GIT_INDEX_FILE} = $old_index;
1499 } else {
1500 delete $ENV{GIT_INDEX_FILE};
1501 }
8a49ee97 1502 die $err if $err;
9b981fc6
EW
1503 wantarray ? @ret : $ret[0];
1504}
1505
1506sub assert_index_clean {
1507 my ($self, $treeish) = @_;
1508
1509 $self->tmp_index_do(sub {
1510 command_noisy('read-tree', $treeish) unless -e $self->{index};
1511 my $x = command_oneline('write-tree');
1512 my ($y) = (command(qw/cat-file commit/, $treeish) =~
1513 /^tree ($::sha1)/mo);
e8d120bd
EW
1514 return if $y eq $x;
1515
1516 warn "Index mismatch: $y != $x\nrereading $treeish\n";
1517 unlink $self->{index} or die "unlink $self->{index}: $!\n";
1518 command_noisy('read-tree', $treeish);
9b981fc6
EW
1519 $x = command_oneline('write-tree');
1520 if ($y ne $x) {
1521 ::fatal "trees ($treeish) $y != $x\n",
1522 "Something is seriously wrong...\n";
1523 }
1524 });
1525}
1526
1527sub get_commit_parents {
0af9c9f9 1528 my ($self, $log_entry) = @_;
9b981fc6 1529 my (%seen, @ret, @tmp);
0af9c9f9
EW
1530 # legacy support for 'set-tree'; this is only used by set_tree_cb:
1531 if (my $ip = $self->{inject_parents}) {
1532 if (my $commit = delete $ip->{$log_entry->{revision}}) {
1533 push @tmp, $commit;
9b981fc6
EW
1534 }
1535 }
d2866f9e 1536 if (my $cur = ::verify_ref($self->refname.'^0')) {
9b981fc6
EW
1537 push @tmp, $cur;
1538 }
44320b9e 1539 push @tmp, $_ foreach (@{$log_entry->{parents}}, @tmp);
9b981fc6
EW
1540 while (my $p = shift @tmp) {
1541 next if $seen{$p};
1542 $seen{$p} = 1;
1543 push @ret, $p;
1544 # MAXPARENT is defined to 16 in commit-tree.c:
1545 last if @ret >= 16;
1546 }
1547 if (@tmp) {
44320b9e 1548 die "r$log_entry->{revision}: No room for parents:\n\t",
9b981fc6
EW
1549 join("\n\t", @tmp), "\n";
1550 }
1551 @ret;
1552}
1553
aea736cc
EW
1554sub rewrite_root {
1555 my ($self) = @_;
1556 return $self->{-rewrite_root} if exists $self->{-rewrite_root};
1557 my $k = "svn-remote.$self->{repo_id}.rewriteRoot";
1558 my $rwr = eval { command_oneline(qw/config --get/, $k) };
1559 if ($rwr) {
1560 $rwr =~ s#/+$##;
1561 if ($rwr !~ m#^[a-z\+]+://#) {
1562 die "$rwr is not a valid URL (key: $k)\n";
1563 }
1564 }
1565 $self->{-rewrite_root} = $rwr;
1566}
1567
1568sub metadata_url {
1569 my ($self) = @_;
1570 ($self->rewrite_root || $self->{url}) .
1571 (length $self->{path} ? '/' . $self->{path} : '');
1572}
1573
706587fc 1574sub full_url {
9b981fc6 1575 my ($self) = @_;
5d3b7cd5 1576 $self->{url} . (length $self->{path} ? '/' . $self->{path} : '');
9b981fc6
EW
1577}
1578
1579sub do_git_commit {
0af9c9f9 1580 my ($self, $log_entry) = @_;
8a603774
EW
1581 my $lr = $self->last_rev;
1582 if (defined $lr && $lr >= $log_entry->{revision}) {
1583 die "Last fetched revision of ", $self->refname,
1584 " was r$lr, but we are about to fetch: ",
1585 "r$log_entry->{revision}!\n";
1586 }
44320b9e
EW
1587 if (my $c = $self->rev_db_get($log_entry->{revision})) {
1588 croak "$log_entry->{revision} = $c already exists! ",
9b981fc6
EW
1589 "Why are we refetching it?\n";
1590 }
db03cd24
EW
1591 $ENV{GIT_AUTHOR_NAME} = $ENV{GIT_COMMITTER_NAME} = $log_entry->{name};
1592 $ENV{GIT_AUTHOR_EMAIL} = $ENV{GIT_COMMITTER_EMAIL} =
1593 $log_entry->{email};
44320b9e 1594 $ENV{GIT_AUTHOR_DATE} = $ENV{GIT_COMMITTER_DATE} = $log_entry->{date};
9b981fc6 1595
44320b9e 1596 my $tree = $log_entry->{tree};
9b981fc6
EW
1597 if (!defined $tree) {
1598 $tree = $self->tmp_index_do(sub {
1599 command_oneline('write-tree') });
1600 }
1601 die "Tree is not a valid sha1: $tree\n" if $tree !~ /^$::sha1$/o;
1602
1603 my @exec = ('git-commit-tree', $tree);
0af9c9f9 1604 foreach ($self->get_commit_parents($log_entry)) {
9b981fc6
EW
1605 push @exec, '-p', $_;
1606 }
1607 defined(my $pid = open3(my $msg_fh, my $out_fh, '>&STDERR', @exec))
1608 or croak $!;
44320b9e 1609 print $msg_fh $log_entry->{log} or croak $!;
91b03282 1610 unless ($self->no_metadata) {
8a49ee97
EW
1611 print $msg_fh "\ngit-svn-id: $log_entry->{metadata}\n"
1612 or croak $!;
9760adcc 1613 }
9b981fc6
EW
1614 $msg_fh->flush == 0 or croak $!;
1615 close $msg_fh or croak $!;
1616 chomp(my $commit = do { local $/; <$out_fh> });
1617 close $out_fh or croak $!;
1618 waitpid $pid, 0;
1619 croak $? if $?;
1620 if ($commit !~ /^$::sha1$/o) {
1621 die "Failed to commit, invalid sha1: $commit\n";
1622 }
1623
373274f9 1624 $self->rev_db_set($log_entry->{revision}, $commit, 1);
9b981fc6 1625
44320b9e 1626 $self->{last_rev} = $log_entry->{revision};
9b981fc6 1627 $self->{last_commit} = $commit;
8a49ee97
EW
1628 print "r$log_entry->{revision}";
1629 if (defined $log_entry->{svm_revision}) {
1630 print " (\@$log_entry->{svm_revision})";
26a62d57
EW
1631 $self->rev_db_set($log_entry->{svm_revision}, $commit,
1632 0, $self->svm_uuid);
8a49ee97
EW
1633 }
1634 print " = $commit ($self->{ref_id})\n";
ecc712dd
EW
1635 if (defined $_repack && (--$_repack_nr == 0)) {
1636 $_repack_nr = $_repack;
1637 # repack doesn't use any arguments with spaces in them, does it?
1638 print "Running git repack $_repack_flags ...\n";
1639 command_noisy('repack', split(/\s+/, $_repack_flags));
1640 print "Done repacking\n";
1641 }
9b981fc6
EW
1642 return $commit;
1643}
1644
fbcc1737
EW
1645sub match_paths {
1646 my ($self, $paths, $r) = @_;
4e9f6cc7 1647 return 1 if $self->{path} eq '';
d542aedb
EW
1648 if (my $path = $paths->{"/$self->{path}"}) {
1649 return ($path->{action} eq 'D') ? 0 : 1;
1650 }
4e9f6cc7 1651 $self->{path_regex} ||= qr/^\/\Q$self->{path}\E\//;
fbcc1737
EW
1652 if (grep /$self->{path_regex}/, keys %$paths) {
1653 return 1;
1654 }
1655 my $c = '';
1656 foreach (split m#/#, $self->{path}) {
1657 $c .= "/$_";
74a81227
EW
1658 next unless ($paths->{$c} &&
1659 ($paths->{$c}->{action} =~ /^[AR]$/));
e518192f
EW
1660 if ($self->ra->check_path($self->{path}, $r) ==
1661 $SVN::Node::dir) {
fbcc1737
EW
1662 return 1;
1663 }
1664 }
1665 return 0;
1666}
1667
15710b6f
EW
1668sub find_parent_branch {
1669 my ($self, $paths, $rev) = @_;
91b03282 1670 return undef unless $self->follow_parent;
e5a0b240 1671 unless (defined $paths) {
c7eba716
EW
1672 my $err_handler = $SVN::Error::handler;
1673 $SVN::Error::handler = \&Git::SVN::Ra::skip_unknown_revs;
d4eff2bd
EW
1674 $self->ra->get_log([$self->{path}], $rev, $rev, 0, 1, 1, sub {
1675 $paths =
1676 Git::SVN::Ra::dup_changed_paths($_[0]) });
c7eba716 1677 $SVN::Error::handler = $err_handler;
e5a0b240
EW
1678 }
1679 return undef unless defined $paths;
15710b6f
EW
1680
1681 # look for a parent from another branch:
7f578c55
EW
1682 my @b_path_components = split m#/#, $self->rel_path;
1683 my @a_path_components;
1684 my $i;
1685 while (@b_path_components) {
1686 $i = $paths->{'/'.join('/', @b_path_components)};
74a81227 1687 last if $i && defined $i->{copyfrom_path};
7f578c55
EW
1688 unshift(@a_path_components, pop(@b_path_components));
1689 }
74a81227
EW
1690 return undef unless defined $i && defined $i->{copyfrom_path};
1691 my $branch_from = $i->{copyfrom_path};
7f578c55
EW
1692 if (@a_path_components) {
1693 print STDERR "branch_from: $branch_from => ";
1694 $branch_from .= '/'.join('/', @a_path_components);
1695 print STDERR $branch_from, "\n";
1696 }
3ebe8df7 1697 my $r = $i->{copyfrom_rev};
15710b6f
EW
1698 my $repos_root = $self->ra->{repos_root};
1699 my $url = $self->ra->{url};
1700 my $new_url = $repos_root . $branch_from;
1701 print STDERR "Found possible branch point: ",
1702 "$new_url => ", $self->full_url, ", $r\n";
1703 $branch_from =~ s#^/##;
a8ae2623 1704 my $gs = Git::SVN->find_by_url($new_url, $repos_root, $branch_from);
15710b6f 1705 unless ($gs) {
ce2a0f2f
EW
1706 my $ref_id = $self->{ref_id};
1707 $ref_id =~ s/\@\d+$//;
1708 $ref_id .= "\@$r";
15710b6f
EW
1709 # just grow a tail if we're not unique enough :x
1710 $ref_id .= '-' while find_ref($ref_id);
ce2a0f2f 1711 print STDERR "Initializing parent: $ref_id\n";
d8115c51 1712 $gs = Git::SVN->init($new_url, '', $ref_id, $ref_id, 1);
15710b6f
EW
1713 }
1714 my ($r0, $parent) = $gs->find_rev_before($r, 1);
91b03282 1715 if (!defined $r0 || !defined $parent) {
d627de6b
EW
1716 my ($base, $head) = parse_revision_argument(0, $r);
1717 if ($base <= $r) {
1718 $gs->fetch($base, $r);
1719 }
15710b6f
EW
1720 ($r0, $parent) = $gs->last_rev_commit;
1721 }
ef70de96 1722 if (defined $r0 && defined $parent) {
15710b6f 1723 print STDERR "Found branch parent: ($self->{ref_id}) $parent\n";
15710b6f
EW
1724 my $ed;
1725 if ($self->ra->can_do_switch) {
2e5e2480 1726 $self->assert_index_clean($parent);
8b8fc068 1727 print STDERR "Following parent with do_switch\n";
15710b6f 1728 # do_switch works with svn/trunk >= r22312, but that
2b27f6c8 1729 # is not included with SVN 1.4.3 (the latest version
15710b6f
EW
1730 # at the moment), so we can't rely on it
1731 $self->{last_commit} = $parent;
1732 $ed = SVN::Git::Fetcher->new($self);
8a603774 1733 $gs->ra->gs_do_switch($r0, $rev, $gs,
15710b6f
EW
1734 $self->full_url, $ed)
1735 or die "SVN connection failed somewhere...\n";
1736 } else {
8b8fc068 1737 print STDERR "Following parent with do_update\n";
15710b6f 1738 $ed = SVN::Git::Fetcher->new($self);
8a603774 1739 $self->ra->gs_do_update($rev, $rev, $self, $ed)
15710b6f
EW
1740 or die "SVN connection failed somewhere...\n";
1741 }
f7c3fc4a 1742 print STDERR "Successfully followed parent\n";
15710b6f
EW
1743 return $self->make_log_entry($rev, [$parent], $ed);
1744 }
15710b6f
EW
1745 return undef;
1746}
1747
9b981fc6 1748sub do_fetch {
706587fc 1749 my ($self, $paths, $rev) = @_;
15710b6f 1750 my $ed;
9b981fc6 1751 my ($last_rev, @parents);
b9dffd8c
EW
1752 if (my $lc = $self->last_commit) {
1753 # we can have a branch that was deleted, then re-added
1754 # under the same name but copied from another path, in
1755 # which case we'll have multiple parents (we don't
1756 # want to break the original ref, nor lose copypath info):
1757 if (my $log_entry = $self->find_parent_branch($paths, $rev)) {
1758 push @{$log_entry->{parents}}, $lc;
1759 return $log_entry;
1760 }
15710b6f 1761 $ed = SVN::Git::Fetcher->new($self);
9b981fc6 1762 $last_rev = $self->{last_rev};
b9dffd8c
EW
1763 $ed->{c} = $lc;
1764 @parents = ($lc);
9b981fc6
EW
1765 } else {
1766 $last_rev = $rev;
15710b6f
EW
1767 if (my $log_entry = $self->find_parent_branch($paths, $rev)) {
1768 return $log_entry;
1769 }
1770 $ed = SVN::Git::Fetcher->new($self);
9b981fc6 1771 }
8a603774 1772 unless ($self->ra->gs_do_update($last_rev, $rev, $self, $ed)) {
9b981fc6
EW
1773 die "SVN connection failed somewhere...\n";
1774 }
1775 $self->make_log_entry($rev, \@parents, $ed);
1776}
1777
97f6987a
EW
1778sub get_untracked {
1779 my ($self, $ed) = @_;
1780 my @out;
1781 my $h = $ed->{empty};
9b981fc6
EW
1782 foreach (sort keys %$h) {
1783 my $act = $h->{$_} ? '+empty_dir' : '-empty_dir';
97f6987a 1784 push @out, " $act: " . uri_encode($_);
9b981fc6
EW
1785 warn "W: $act: $_\n";
1786 }
1787 foreach my $t (qw/dir_prop file_prop/) {
97f6987a 1788 $h = $ed->{$t} or next;
9b981fc6
EW
1789 foreach my $path (sort keys %$h) {
1790 my $ppath = $path eq '' ? '.' : $path;
1791 foreach my $prop (sort keys %{$h->{$path}}) {
1ce255dc 1792 next if $SKIP_PROP{$prop};
9b981fc6 1793 my $v = $h->{$path}->{$prop};
97f6987a
EW
1794 my $t_ppath_prop = "$t: " .
1795 uri_encode($ppath) . ' ' .
1796 uri_encode($prop);
9b981fc6 1797 if (defined $v) {
97f6987a
EW
1798 push @out, " +$t_ppath_prop " .
1799 uri_encode($v);
9b981fc6 1800 } else {
97f6987a 1801 push @out, " -$t_ppath_prop";
9b981fc6
EW
1802 }
1803 }
1804 }
1805 }
1806 foreach my $t (qw/absent_file absent_directory/) {
97f6987a 1807 $h = $ed->{$t} or next;
9b981fc6
EW
1808 foreach my $parent (sort keys %$h) {
1809 foreach my $path (sort @{$h->{$parent}}) {
97f6987a
EW
1810 push @out, " $t: " .
1811 uri_encode("$parent/$path");
9b981fc6
EW
1812 warn "W: $t: $parent/$path ",
1813 "Insufficient permissions?\n";
1814 }
1815 }
1816 }
97f6987a 1817 \@out;
9b981fc6
EW
1818}
1819
1c8443b0
EW
1820sub parse_svn_date {
1821 my $date = shift || return '+0000 1970-01-01 00:00:00';
1822 my ($Y,$m,$d,$H,$M,$S) = ($date =~ /^(\d{4})\-(\d\d)\-(\d\d)T
1823 (\d\d)\:(\d\d)\:(\d\d).\d+Z$/x) or
1824 croak "Unable to parse date: $date\n";
1825 "+0000 $Y-$m-$d $H:$M:$S";
1826}
1827
1828sub check_author {
1829 my ($author) = @_;
1830 if (!defined $author || length $author == 0) {
1831 $author = '(no author)';
1832 }
1833 if (defined $::_authors && ! defined $::users{$author}) {
1834 die "Author: $author not defined in $::_authors file\n";
1835 }
1836 $author;
1837}
1838
9b981fc6 1839sub make_log_entry {
97f6987a
EW
1840 my ($self, $rev, $parents, $ed) = @_;
1841 my $untracked = $self->get_untracked($ed);
1842
9b981fc6 1843 open my $un, '>>', "$self->{dir}/unhandled.log" or croak $!;
97f6987a
EW
1844 print $un "r$rev\n" or croak $!;
1845 print $un $_, "\n" foreach @$untracked;
1846 my %log_entry = ( parents => $parents || [], revision => $rev,
1847 log => '');
fbcc1737 1848
8a49ee97 1849 my $headrev;
fbcc1737 1850 my $logged = delete $self->{logged_rev_props};
8a49ee97 1851 if (!$logged || $self->{-want_revprops}) {
fbcc1737
EW
1852 my $rp = $self->ra->rev_proplist($rev);
1853 foreach (sort keys %$rp) {
1854 my $v = $rp->{$_};
1855 if (/^svn:(author|date|log)$/) {
1856 $log_entry{$1} = $v;
8a49ee97
EW
1857 } elsif ($_ eq 'svm:headrev') {
1858 $headrev = $v;
fbcc1737
EW
1859 } else {
1860 print $un " rev_prop: ", uri_encode($_), ' ',
1861 uri_encode($v), "\n";
1862 }
9b981fc6 1863 }
fbcc1737
EW
1864 } else {
1865 map { $log_entry{$_} = $logged->{$_} } keys %$logged;
9b981fc6
EW
1866 }
1867 close $un or croak $!;
97f6987a 1868
9b981fc6 1869 $log_entry{date} = parse_svn_date($log_entry{date});
9b981fc6 1870 $log_entry{log} .= "\n";
db03cd24
EW
1871 my $author = $log_entry{author} = check_author($log_entry{author});
1872 my ($name, $email) = defined $::users{$author} ? @{$::users{$author}}
1873 : ($author, undef);
91b03282 1874 if (defined $headrev && $self->use_svm_props) {
aea736cc
EW
1875 if ($self->rewrite_root) {
1876 die "Can't have both 'useSvmProps' and 'rewriteRoot' ",
1877 "options set!\n";
1878 }
8a49ee97 1879 my ($uuid, $r) = $headrev =~ m{^([a-f\d\-]{30,}):(\d+)$};
befc9adc
EW
1880 # we don't want "SVM: initializing mirror for junk" ...
1881 return undef if $r == 0;
1882 my $svm = $self->svm;
1883 if ($uuid ne $svm->{uuid}) {
8a49ee97 1884 die "UUID mismatch on SVM path:\n",
befc9adc 1885 "expected: $svm->{uuid}\n",
8a49ee97
EW
1886 " got: $uuid\n";
1887 }
befc9adc
EW
1888 my $full_url = $self->full_url;
1889 $full_url =~ s#^\Q$svm->{replace}\E(/|$)#$svm->{source}$1# or
1890 die "Failed to replace '$svm->{replace}' with ",
1891 "'$svm->{source}' in $full_url\n";
18ea92bd
SV
1892 # throw away username for storing in records
1893 remove_username($full_url);
8a49ee97
EW
1894 $log_entry{metadata} = "$full_url\@$r $uuid";
1895 $log_entry{svm_revision} = $r;
db03cd24 1896 $email ||= "$author\@$uuid"
62e349d2
EW
1897 } elsif ($self->use_svnsync_props) {
1898 my $full_url = $self->svnsync->{url};
1899 $full_url .= "/$self->{path}" if length $self->{path};
ce118739 1900 remove_username($full_url);
62e349d2
EW
1901 my $uuid = $self->svnsync->{uuid};
1902 $log_entry{metadata} = "$full_url\@$rev $uuid";
1903 $email ||= "$author\@$uuid"
8a49ee97 1904 } else {
ce118739
AR
1905 my $url = $self->metadata_url;
1906 remove_username($url);
1907 $log_entry{metadata} = "$url\@$rev " .
26a62d57 1908 $self->ra->get_uuid;
db03cd24 1909 $email ||= "$author\@" . $self->ra->get_uuid;
8a49ee97 1910 }
db03cd24
EW
1911 $log_entry{name} = $name;
1912 $log_entry{email} = $email;
9b981fc6
EW
1913 \%log_entry;
1914}
1915
1916sub fetch {
3ebe8df7 1917 my ($self, $min_rev, $max_rev, @parents) = @_;
9b981fc6 1918 my ($last_rev, $last_commit) = $self->last_rev_commit;
3ebe8df7 1919 my ($base, $head) = $self->get_fetch_range($min_rev, $max_rev);
e518192f 1920 $self->ra->gs_fetch_loop_common($base, $head, [$self]);
9b981fc6
EW
1921}
1922
1923sub set_tree_cb {
1924 my ($self, $log_entry, $tree, $rev, $date, $author) = @_;
490f49ea
EW
1925 $self->{inject_parents} = { $rev => $tree };
1926 $self->fetch(undef, undef);
9b981fc6
EW
1927}
1928
1929sub set_tree {
1930 my ($self, $tree) = (shift, shift);
1ce255dc 1931 my $log_entry = ::get_commit_entry($tree);
9b981fc6
EW
1932 unless ($self->{last_rev}) {
1933 fatal("Must have an existing revision to commit\n");
1934 }
61395354
EW
1935 my %ed_opts = ( r => $self->{last_rev},
1936 log => $log_entry->{log},
1937 ra => $self->ra,
1938 tree_a => $self->{last_commit},
1939 tree_b => $tree,
1940 editor_cb => sub {
1941 $self->set_tree_cb($log_entry, $tree, @_) },
1942 svn_path => $self->{path} );
1943 if (!SVN::Git::Editor->new(\%ed_opts)->apply_diff) {
9b981fc6
EW
1944 print "No changes\nr$self->{last_rev} = $tree\n";
1945 }
9b981fc6
EW
1946}
1947
f0ecca10
EW
1948sub rebuild {
1949 my ($self) = @_;
26a62d57 1950 my $db_path = $self->db_path;
d6d3346b
EW
1951 return if (-e $db_path && ! -z $db_path);
1952 return unless ::verify_ref($self->refname.'^0');
26a62d57
EW
1953 if (-f $self->{db_root}) {
1954 rename $self->{db_root}, $db_path or die
1955 "rename $self->{db_root} => $db_path failed: $!\n";
1956 my ($dir, $base) = ($db_path =~ m#^(.*?)/?([^/]+)$#);
1957 symlink $base, $self->{db_root} or die
1958 "symlink $base => $self->{db_root} failed: $!\n";
1959 return;
1960 }
1961 print "Rebuilding $db_path ...\n";
f0ecca10
EW
1962 my ($rev_list, $ctx) = command_output_pipe("rev-list", $self->refname);
1963 my $latest;
1964 my $full_url = $self->full_url;
18ea92bd 1965 remove_username($full_url);
f0ecca10
EW
1966 my $svn_uuid;
1967 while (<$rev_list>) {
1968 chomp;
1969 my $c = $_;
1970 die "Non-SHA1: $c\n" unless $c =~ /^$::sha1$/o;
1971 my ($url, $rev, $uuid) = ::cmt_metadata($c);
18ea92bd 1972 remove_username($url);
f0ecca10
EW
1973
1974 # ignore merges (from set-tree)
1975 next if (!defined $rev || !$uuid);
1976
1977 # if we merged or otherwise started elsewhere, this is
1978 # how we break out of it
1979 if ((defined $svn_uuid && ($uuid ne $svn_uuid)) ||
1980 ($full_url && $url && ($url ne $full_url))) {
1981 next;
1982 }
1983 $latest ||= $rev;
1984 $svn_uuid ||= $uuid;
1985
1986 $self->rev_db_set($rev, $c);
1987 print "r$rev = $c\n";
1988 }
1989 command_close_pipe($rev_list, $ctx);
26a62d57 1990 print "Done rebuilding $db_path\n";
f0ecca10
EW
1991}
1992
9b981fc6
EW
1993# rev_db:
1994# Tie::File seems to be prone to offset errors if revisions get sparse,
1995# it's not that fast, either. Tie::File is also not in Perl 5.6. So
1996# one of my favorite modules is out :< Next up would be one of the DBM
1997# modules, but I'm not sure which is most portable... So I'll just
1998# go with something that's plain-text, but still capable of
1999# being randomly accessed. So here's my ultra-simple fixed-width
2000# database. All records are 40 characters + "\n", so it's easy to seek
2001# to a revision: (41 * rev) is the byte offset.
2002# A record of 40 0s denotes an empty revision.
2003# And yes, it's still pretty fast (faster than Tie::File).
97ae0911 2004# These files are disposable unless noMetadata or useSvmProps is set
9b981fc6 2005
26a62d57
EW
2006sub _rev_db_set {
2007 my ($fh, $rev, $commit) = @_;
2008 my $offset = $rev * 41;
2009 # assume that append is the common case:
2010 seek $fh, 0, 2 or croak $!;
2011 my $pos = tell $fh;
2012 if ($pos < $offset) {
2013 for (1 .. (($offset - $pos) / 41)) {
2014 print $fh (('0' x 40),"\n") or croak $!;
2015 }
2016 }
2017 seek $fh, $offset, 0 or croak $!;
2018 print $fh $commit,"\n" or croak $!;
2019}
2020
2021sub mkfile {
2022 my ($path) = @_;
2023 unless (-e $path) {
2024 my ($dir, $base) = ($path =~ m#^(.*?)/?([^/]+)$#);
2025 mkpath([$dir]) unless -d $dir;
2026 open my $fh, '>>', $path or die "Couldn't create $path: $!\n";
2027 close $fh or die "Couldn't close (create) $path: $!\n";
2028 }
2029}
2030
9b981fc6 2031sub rev_db_set {
26a62d57
EW
2032 my ($self, $rev, $commit, $update_ref, $uuid) = @_;
2033 length $commit == 40 or die "arg3 must be a full SHA1 hexsum\n";
2034 my $db = $self->db_path($uuid);
2035 my $db_lock = "$db.lock";
373274f9
EW
2036 my $sig;
2037 if ($update_ref) {
2038 $SIG{INT} = $SIG{HUP} = $SIG{TERM} = $SIG{ALRM} = $SIG{PIPE} =
2039 $SIG{USR1} = $SIG{USR2} = sub { $sig = $_[0] };
2040 }
26a62d57
EW
2041 mkfile($db);
2042
373274f9 2043 $LOCKFILES{$db_lock} = 1;
97ae0911 2044 my $sync;
97ae0911
EW
2045 # both of these options make our .rev_db file very, very important
2046 # and we can't afford to lose it because rebuild() won't work
2047 if ($self->use_svm_props || $self->no_metadata) {
2048 $sync = 1;
373274f9 2049 copy($db, $db_lock) or die "rev_db_set(@_): ",
26a62d57 2050 "Failed to copy: ",
373274f9
EW
2051 "$db => $db_lock ($!)\n";
2052 } else {
2053 rename $db, $db_lock or die "rev_db_set(@_): ",
26a62d57 2054 "Failed to rename: ",
373274f9
EW
2055 "$db => $db_lock ($!)\n";
2056 }
26a62d57
EW
2057 open my $fh, '+<', $db_lock or die "Couldn't open $db_lock: $!\n";
2058 _rev_db_set($fh, $rev, $commit);
97ae0911
EW
2059 if ($sync) {
2060 $fh->flush or die "Couldn't flush $db_lock: $!\n";
2061 $fh->sync or die "Couldn't sync $db_lock: $!\n";
2062 }
9b981fc6 2063 close $fh or croak $!;
373274f9 2064 if ($update_ref) {
1e889ef3 2065 $_head = $self;
373274f9
EW
2066 command_noisy('update-ref', '-m', "r$rev",
2067 $self->refname, $commit);
2068 }
2069 rename $db_lock, $db or die "rev_db_set(@_): ", "Failed to rename: ",
2070 "$db_lock => $db ($!)\n";
2071 delete $LOCKFILES{$db_lock};
2072 if ($update_ref) {
2073 $SIG{INT} = $SIG{HUP} = $SIG{TERM} = $SIG{ALRM} = $SIG{PIPE} =
2074 $SIG{USR1} = $SIG{USR2} = 'DEFAULT';
2075 kill $sig, $$ if defined $sig;
2076 }
9b981fc6
EW
2077}
2078
9c93fee5
EW
2079sub rev_db_max {
2080 my ($self) = @_;
d6d3346b 2081 $self->rebuild;
26a62d57
EW
2082 my $db_path = $self->db_path;
2083 my @stat = stat $db_path or return 0;
2084 ($stat[7] % 41) == 0 or die "$db_path inconsistent size: $stat[7]\n";
9c93fee5
EW
2085 my $max = $stat[7] / 41;
2086 (($max > 0) ? $max - 1 : 0);
2087}
2088
9b981fc6 2089sub rev_db_get {
26a62d57 2090 my ($self, $rev, $uuid) = @_;
9b981fc6
EW
2091 my $ret;
2092 my $offset = $rev * 41;
26a62d57
EW
2093 my $db_path = $self->db_path($uuid);
2094 return undef unless -e $db_path;
2095 open my $fh, '<', $db_path or croak $!;
ce4b4af7
EW
2096 if (sysseek($fh, $offset, 0) == $offset) {
2097 my $read = sysread($fh, $ret, 40);
2098 $ret = undef if ($read != 40 || $ret eq ('0'x40));
9b981fc6
EW
2099 }
2100 close $fh or croak $!;
2101 $ret;
2102}
2103
15710b6f
EW
2104sub find_rev_before {
2105 my ($self, $rev, $eq_ok) = @_;
2106 --$rev unless $eq_ok;
2107 while ($rev > 0) {
2108 if (my $c = $self->rev_db_get($rev)) {
2109 return ($rev, $c);
2110 }
2111 --$rev;
2112 }
2113 return (undef, undef);
2114}
2115
9b981fc6 2116sub _new {
706587fc
EW
2117 my ($class, $repo_id, $ref_id, $path) = @_;
2118 unless (defined $repo_id && length $repo_id) {
2119 $repo_id = $Git::SVN::default_repo_id;
2120 }
2121 unless (defined $ref_id && length $ref_id) {
8b8fc068 2122 $_[2] = $ref_id = $Git::SVN::default_ref_id;
706587fc
EW
2123 }
2124 $_[1] = $repo_id = sanitize_remote_name($repo_id);
2125 my $dir = "$ENV{GIT_DIR}/svn/$ref_id";
2126 $_[3] = $path = '' unless (defined $path);
b4d57e5e 2127 mkpath(["$ENV{GIT_DIR}/svn"]);
26a62d57
EW
2128 bless {
2129 ref_id => $ref_id, dir => $dir, index => "$dir/index",
8a49ee97 2130 path => $path, config => "$ENV{GIT_DIR}/svn/config",
26a62d57
EW
2131 db_root => "$dir/.rev_db", repo_id => $repo_id }, $class;
2132}
2133
2134sub db_path {
2135 my ($self, $uuid) = @_;
2136 $uuid ||= $self->ra_uuid;
2137 "$self->{db_root}.$uuid";
9b981fc6
EW
2138}
2139
1c8443b0
EW
2140sub uri_encode {
2141 my ($f) = @_;
2142 $f =~ s#([^a-zA-Z0-9\*!\:_\./\-])#uc sprintf("%%%02x",ord($1))#eg;
2143 $f
2144}
9b981fc6 2145
18ea92bd
SV
2146sub remove_username {
2147 $_[0] =~ s{^([^:]*://)[^@]+@}{$1};
2148}
2149
d976acfd
EW
2150package Git::SVN::Prompt;
2151use strict;
2152use warnings;
2153require SVN::Core;
2154use vars qw/$_no_auth_cache $_username/;
2155
2156sub simple {
30d055aa
EW
2157 my ($cred, $realm, $default_username, $may_save, $pool) = @_;
2158 $may_save = undef if $_no_auth_cache;
2159 $default_username = $_username if defined $_username;
2160 if (defined $default_username && length $default_username) {
2161 if (defined $realm && length $realm) {
6f729591
EW
2162 print STDERR "Authentication realm: $realm\n";
2163 STDERR->flush;
30d055aa
EW
2164 }
2165 $cred->username($default_username);
2166 } else {
d976acfd 2167 username($cred, $realm, $may_save, $pool);
30d055aa
EW
2168 }
2169 $cred->password(_read_password("Password for '" .
2170 $cred->username . "': ", $realm));
2171 $cred->may_save($may_save);
2172 $SVN::_Core::SVN_NO_ERROR;
2173}
2174
d976acfd 2175sub ssl_server_trust {
30d055aa
EW
2176 my ($cred, $realm, $failures, $cert_info, $may_save, $pool) = @_;
2177 $may_save = undef if $_no_auth_cache;
6f729591 2178 print STDERR "Error validating server certificate for '$realm':\n";
30d055aa 2179 if ($failures & $SVN::Auth::SSL::UNKNOWNCA) {
6f729591 2180 print STDERR " - The certificate is not issued by a trusted ",
30d055aa
EW
2181 "authority. Use the\n",
2182 " fingerprint to validate the certificate manually!\n";
2183 }
2184 if ($failures & $SVN::Auth::SSL::CNMISMATCH) {
6f729591 2185 print STDERR " - The certificate hostname does not match.\n";
30d055aa
EW
2186 }
2187 if ($failures & $SVN::Auth::SSL::NOTYETVALID) {
6f729591 2188 print STDERR " - The certificate is not yet valid.\n";
30d055aa
EW
2189 }
2190 if ($failures & $SVN::Auth::SSL::EXPIRED) {
6f729591 2191 print STDERR " - The certificate has expired.\n";
30d055aa
EW
2192 }
2193 if ($failures & $SVN::Auth::SSL::OTHER) {
6f729591 2194 print STDERR " - The certificate has an unknown error.\n";
30d055aa 2195 }
6f729591
EW
2196 printf STDERR
2197 "Certificate information:\n".
30d055aa
EW
2198 " - Hostname: %s\n".
2199 " - Valid: from %s until %s\n".
2200 " - Issuer: %s\n".
2201 " - Fingerprint: %s\n",
2202 map $cert_info->$_, qw(hostname valid_from valid_until
6f729591 2203 issuer_dname fingerprint);
30d055aa
EW
2204 my $choice;
2205prompt:
6f729591 2206 print STDERR $may_save ?
30d055aa
EW
2207 "(R)eject, accept (t)emporarily or accept (p)ermanently? " :
2208 "(R)eject or accept (t)emporarily? ";
6f729591 2209 STDERR->flush;
30d055aa
EW
2210 $choice = lc(substr(<STDIN> || 'R', 0, 1));
2211 if ($choice =~ /^t$/i) {
2212 $cred->may_save(undef);
2213 } elsif ($choice =~ /^r$/i) {
2214 return -1;
2215 } elsif ($may_save && $choice =~ /^p$/i) {
2216 $cred->may_save($may_save);
2217 } else {
2218 goto prompt;
2219 }
2220 $cred->accepted_failures($failures);
2221 $SVN::_Core::SVN_NO_ERROR;
2222}
2223
d976acfd 2224sub ssl_client_cert {
30d055aa
EW
2225 my ($cred, $realm, $may_save, $pool) = @_;
2226 $may_save = undef if $_no_auth_cache;
6f729591
EW
2227 print STDERR "Client certificate filename: ";
2228 STDERR->flush;
30d055aa
EW
2229 chomp(my $filename = <STDIN>);
2230 $cred->cert_file($filename);
2231 $cred->may_save($may_save);
2232 $SVN::_Core::SVN_NO_ERROR;
2233}
2234
d976acfd 2235sub ssl_client_cert_pw {
30d055aa
EW
2236 my ($cred, $realm, $may_save, $pool) = @_;
2237 $may_save = undef if $_no_auth_cache;
2238 $cred->password(_read_password("Password: ", $realm));
2239 $cred->may_save($may_save);
2240 $SVN::_Core::SVN_NO_ERROR;
2241}
2242
d976acfd 2243sub username {
30d055aa
EW
2244 my ($cred, $realm, $may_save, $pool) = @_;
2245 $may_save = undef if $_no_auth_cache;
2246 if (defined $realm && length $realm) {
6f729591 2247 print STDERR "Authentication realm: $realm\n";
30d055aa
EW
2248 }
2249 my $username;
2250 if (defined $_username) {
2251 $username = $_username;
2252 } else {
6f729591
EW
2253 print STDERR "Username: ";
2254 STDERR->flush;
30d055aa
EW
2255 chomp($username = <STDIN>);
2256 }
2257 $cred->username($username);
2258 $cred->may_save($may_save);
2259 $SVN::_Core::SVN_NO_ERROR;
2260}
2261
2262sub _read_password {
2263 my ($prompt, $realm) = @_;
6f729591
EW
2264 print STDERR $prompt;
2265 STDERR->flush;
30d055aa
EW
2266 require Term::ReadKey;
2267 Term::ReadKey::ReadMode('noecho');
2268 my $password = '';
2269 while (defined(my $key = Term::ReadKey::ReadKey(0))) {
2270 last if $key =~ /[\012\015]/; # \n\r
2271 $password .= $key;
2272 }
2273 Term::ReadKey::ReadMode('restore');
6f729591
EW
2274 print STDERR "\n";
2275 STDERR->flush;
30d055aa
EW
2276 $password;
2277}
2278
d976acfd
EW
2279package main;
2280
b9c85187
EW
2281{
2282 my $kill_stupid_warnings = $SVN::Node::none.$SVN::Node::file.
2283 $SVN::Node::dir.$SVN::Node::unknown.
2284 $SVN::Node::none.$SVN::Node::file.
2285 $SVN::Node::dir.$SVN::Node::unknown.
2286 $SVN::Auth::SSL::CNMISMATCH.
2287 $SVN::Auth::SSL::NOTYETVALID.
2288 $SVN::Auth::SSL::EXPIRED.
2289 $SVN::Auth::SSL::UNKNOWNCA.
2290 $SVN::Auth::SSL::OTHER;
2291}
2292
27a1a801
EW
2293package SVN::Git::Fetcher;
2294use vars qw/@ISA/;
2295use strict;
2296use warnings;
2297use Carp qw/croak/;
2298use IO::File qw//;
90c1b15d 2299use Digest::MD5;
27a1a801
EW
2300
2301# file baton members: path, mode_a, mode_b, pool, fh, blob, base
2302sub new {
2303 my ($class, $git_svn) = @_;
2304 my $self = SVN::Delta::Editor->new;
2305 bless $self, $class;
1c8443b0 2306 $self->{c} = $git_svn->{last_commit} if exists $git_svn->{last_commit};
d2a9a87b
EW
2307 $self->{empty} = {};
2308 $self->{dir_prop} = {};
2309 $self->{file_prop} = {};
2310 $self->{absent_dir} = {};
2311 $self->{absent_file} = {};
ef3cfaad 2312 $self->{gii} = $git_svn->tmp_index_do(sub { Git::IndexInfo->new });
27a1a801
EW
2313 $self;
2314}
2315
8b8fc068
EW
2316sub set_path_strip {
2317 my ($self, $path) = @_;
4e9f6cc7 2318 $self->{path_strip} = qr/^\Q$path\E(\/|$)/ if length $path;
8b8fc068
EW
2319}
2320
d2a9a87b
EW
2321sub open_root {
2322 { path => '' };
2323}
2324
2325sub open_directory {
2326 my ($self, $path, $pb, $rev) = @_;
2327 { path => $path };
2328}
2329
706587fc
EW
2330sub git_path {
2331 my ($self, $path) = @_;
2b27f6c8
EW
2332 if ($self->{path_strip}) {
2333 $path =~ s!$self->{path_strip}!! or
2334 die "Failed to strip path '$path' ($self->{path_strip})\n";
2335 }
706587fc
EW
2336 $path;
2337}
2338
27a1a801
EW
2339sub delete_entry {
2340 my ($self, $path, $rev, $pb) = @_;
4a87db0e 2341
706587fc 2342 my $gpath = $self->git_path($path);
8a603774
EW
2343 return undef if ($gpath eq '');
2344
4a87db0e 2345 # remove entire directories.
706587fc 2346 if (command('ls-tree', $self->{c}, '--', $gpath) =~ /^040000 tree/) {
4a87db0e
EW
2347 my ($ls, $ctx) = command_output_pipe(qw/ls-tree
2348 -r --name-only -z/,
706587fc 2349 $self->{c}, '--', $gpath);
4a87db0e
EW
2350 local $/ = "\0";
2351 while (<$ls>) {
ef3cfaad
EW
2352 chomp;
2353 $self->{gii}->remove($_);
9e3cdbd4 2354 print "\tD\t$_\n" unless $::_q;
4a87db0e 2355 }
9e3cdbd4 2356 print "\tD\t$gpath/\n" unless $::_q;
4a87db0e
EW
2357 command_close_pipe($ls, $ctx);
2358 $self->{empty}->{$path} = 0
2359 } else {
ef3cfaad 2360 $self->{gii}->remove($gpath);
9e3cdbd4 2361 print "\tD\t$gpath\n" unless $::_q;
4a87db0e 2362 }
27a1a801
EW
2363 undef;
2364}
2365
2366sub open_file {
2367 my ($self, $path, $pb, $rev) = @_;
706587fc
EW
2368 my $gpath = $self->git_path($path);
2369 my ($mode, $blob) = (command('ls-tree', $self->{c}, '--', $gpath)
27a1a801 2370 =~ /^(\d{6}) blob ([a-f\d]{40})\t/);
006ede5e
EW
2371 unless (defined $mode && defined $blob) {
2372 die "$path was not found in commit $self->{c} (r$rev)\n";
2373 }
27a1a801 2374 { path => $path, mode_a => $mode, mode_b => $mode, blob => $blob,
0864e3ba 2375 pool => SVN::Pool->new, action => 'M' };
27a1a801
EW
2376}
2377
2378sub add_file {
2379 my ($self, $path, $pb, $cp_path, $cp_rev) = @_;
d2a9a87b
EW
2380 my ($dir, $file) = ($path =~ m#^(.*?)/?([^/]+)$#);
2381 delete $self->{empty}->{$dir};
27a1a801 2382 { path => $path, mode_a => 100644, mode_b => 100644,
0864e3ba 2383 pool => SVN::Pool->new, action => 'A' };
27a1a801
EW
2384}
2385
d2a9a87b
EW
2386sub add_directory {
2387 my ($self, $path, $cp_path, $cp_rev) = @_;
2388 my ($dir, $file) = ($path =~ m#^(.*?)/?([^/]+)$#);
2389 delete $self->{empty}->{$dir};
2390 $self->{empty}->{$path} = 1;
2391 { path => $path };
2392}
2393
2394sub change_dir_prop {
2395 my ($self, $db, $prop, $value) = @_;
2396 $self->{dir_prop}->{$db->{path}} ||= {};
2397 $self->{dir_prop}->{$db->{path}}->{$prop} = $value;
2398 undef;
2399}
2400
2401sub absent_directory {
2402 my ($self, $path, $pb) = @_;
2403 $self->{absent_dir}->{$pb->{path}} ||= [];
2404 push @{$self->{absent_dir}->{$pb->{path}}}, $path;
2405 undef;
2406}
2407
2408sub absent_file {
2409 my ($self, $path, $pb) = @_;
2410 $self->{absent_file}->{$pb->{path}} ||= [];
2411 push @{$self->{absent_file}->{$pb->{path}}}, $path;
2412 undef;
2413}
2414
27a1a801
EW
2415sub change_file_prop {
2416 my ($self, $fb, $prop, $value) = @_;
2417 if ($prop eq 'svn:executable') {
2418 if ($fb->{mode_b} != 120000) {
2419 $fb->{mode_b} = defined $value ? 100755 : 100644;
2420 }
2421 } elsif ($prop eq 'svn:special') {
2422 $fb->{mode_b} = defined $value ? 120000 : 100644;
d2a9a87b
EW
2423 } else {
2424 $self->{file_prop}->{$fb->{path}} ||= {};
2425 $self->{file_prop}->{$fb->{path}}->{$prop} = $value;
27a1a801
EW
2426 }
2427 undef;
2428}
2429
2430sub apply_textdelta {
2431 my ($self, $fb, $exp) = @_;
2432 my $fh = IO::File->new_tmpfile;
2433 $fh->autoflush(1);
2434 # $fh gets auto-closed() by SVN::TxDelta::apply(),
2435 # (but $base does not,) so dup() it for reading in close_file
2436 open my $dup, '<&', $fh or croak $!;
2437 my $base = IO::File->new_tmpfile;
2438 $base->autoflush(1);
2439 if ($fb->{blob}) {
2440 defined (my $pid = fork) or croak $!;
2441 if (!$pid) {
2442 open STDOUT, '>&', $base or croak $!;
2443 print STDOUT 'link ' if ($fb->{mode_a} == 120000);
2444 exec qw/git-cat-file blob/, $fb->{blob} or croak $!;
2445 }
2446 waitpid $pid, 0;
2447 croak $? if $?;
2448
2449 if (defined $exp) {
2450 seek $base, 0, 0 or croak $!;
2451 my $md5 = Digest::MD5->new;
2452 $md5->addfile($base);
2453 my $got = $md5->hexdigest;
2454 die "Checksum mismatch: $fb->{path} $fb->{blob}\n",
2455 "expected: $exp\n",
2456 " got: $got\n" if ($got ne $exp);
2457 }
2458 }
2459 seek $base, 0, 0 or croak $!;
2460 $fb->{fh} = $dup;
2461 $fb->{base} = $base;
2462 [ SVN::TxDelta::apply($base, $fh, undef, $fb->{path}, $fb->{pool}) ];
2463}
2464
2465sub close_file {
2466 my ($self, $fb, $exp) = @_;
2467 my $hash;
706587fc 2468 my $path = $self->git_path($fb->{path});
27a1a801
EW
2469 if (my $fh = $fb->{fh}) {
2470 seek($fh, 0, 0) or croak $!;
2471 my $md5 = Digest::MD5->new;
2472 $md5->addfile($fh);
2473 my $got = $md5->hexdigest;
2474 die "Checksum mismatch: $path\n",
2475 "expected: $exp\n got: $got\n" if ($got ne $exp);
bcd8ee5b 2476 sysseek($fh, 0, 0) or croak $!;
27a1a801 2477 if ($fb->{mode_b} == 120000) {
bcd8ee5b 2478 sysread($fh, my $buf, 5) == 5 or croak $!;
27a1a801
EW
2479 $buf eq 'link ' or die "$path has mode 120000",
2480 "but is not a link\n";
2481 }
2482 defined(my $pid = open my $out,'-|') or die "Can't fork: $!\n";
2483 if (!$pid) {
2484 open STDIN, '<&', $fh or croak $!;
2485 exec qw/git-hash-object -w --stdin/ or croak $!;
2486 }
2487 chomp($hash = do { local $/; <$out> });
2488 close $out or croak $!;
2489 close $fh or croak $!;
2490 $hash =~ /^[a-f\d]{40}$/ or die "not a sha1: $hash\n";
2491 close $fb->{base} or croak $!;
2492 } else {
2493 $hash = $fb->{blob} or die "no blob information\n";
2494 }
2495 $fb->{pool}->clear;
ef3cfaad 2496 $self->{gii}->update($fb->{mode_b}, $hash, $path) or croak $!;
9e3cdbd4 2497 print "\t$fb->{action}\t$path\n" if $fb->{action} && ! $::_q;
27a1a801
EW
2498 undef;
2499}
2500
2501sub abort_edit {
2502 my $self = shift;
ef3cfaad
EW
2503 $self->{nr} = $self->{gii}->{nr};
2504 delete $self->{gii};
27a1a801
EW
2505 $self->SUPER::abort_edit(@_);
2506}
2507
2508sub close_edit {
2509 my $self = shift;
dad73c0b 2510 $self->{git_commit_ok} = 1;
ef3cfaad
EW
2511 $self->{nr} = $self->{gii}->{nr};
2512 delete $self->{gii};
27a1a801
EW
2513 $self->SUPER::close_edit(@_);
2514}
1a82e793 2515
a5e0cedc 2516package SVN::Git::Editor;
24e22aa8 2517use vars qw/@ISA $_rmdir $_cp_similarity $_find_copies_harder $_rename_limit/;
a5e0cedc
EW
2518use strict;
2519use warnings;
2520use Carp qw/croak/;
2521use IO::File;
90c1b15d 2522use Digest::MD5;
a5e0cedc
EW
2523
2524sub new {
61395354
EW
2525 my ($class, $opts) = @_;
2526 foreach (qw/svn_path r ra tree_a tree_b log editor_cb/) {
2527 die "$_ required!\n" unless (defined $opts->{$_});
2528 }
2529
2530 my $pool = SVN::Pool->new;
2531 my $mods = generate_diff($opts->{tree_a}, $opts->{tree_b});
2532 my $types = check_diff_paths($opts->{ra}, $opts->{svn_path},
2533 $opts->{r}, $mods);
2534
2535 # $opts->{ra} functions should not be used after this:
2536 my @ce = $opts->{ra}->get_commit_editor($opts->{log},
2537 $opts->{editor_cb}, $pool);
2538 my $self = SVN::Delta::Editor->new(@ce, $pool);
a5e0cedc 2539 bless $self, $class;
61395354
EW
2540 foreach (qw/svn_path r tree_a tree_b/) {
2541 $self->{$_} = $opts->{$_};
a5e0cedc 2542 }
61395354
EW
2543 $self->{url} = $opts->{ra}->{url};
2544 $self->{mods} = $mods;
2545 $self->{types} = $types;
2546 $self->{pool} = $pool;
a5e0cedc
EW
2547 $self->{bat} = { '' => $self->open_root($self->{r}, $self->{pool}) };
2548 $self->{rm} = { };
d3a840dc
EW
2549 $self->{path_prefix} = length $self->{svn_path} ?
2550 "$self->{svn_path}/" : '';
a5e0cedc
EW
2551 return $self;
2552}
2553
61395354
EW
2554sub generate_diff {
2555 my ($tree_a, $tree_b) = @_;
2556 my @diff_tree = qw(diff-tree -z -r);
24e22aa8
EW
2557 if ($_cp_similarity) {
2558 push @diff_tree, "-C$_cp_similarity";
61395354
EW
2559 } else {
2560 push @diff_tree, '-C';
2561 }
24e22aa8
EW
2562 push @diff_tree, '--find-copies-harder' if $_find_copies_harder;
2563 push @diff_tree, "-l$_rename_limit" if defined $_rename_limit;
61395354
EW
2564 push @diff_tree, $tree_a, $tree_b;
2565 my ($diff_fh, $ctx) = command_output_pipe(@diff_tree);
2566 local $/ = "\0";
2567 my $state = 'meta';
2568 my @mods;
2569 while (<$diff_fh>) {
2570 chomp $_; # this gets rid of the trailing "\0"
2571 if ($state eq 'meta' && /^:(\d{6})\s(\d{6})\s
2572 $::sha1\s($::sha1)\s
2573 ([MTCRAD])\d*$/xo) {
2574 push @mods, { mode_a => $1, mode_b => $2,
2575 sha1_b => $3, chg => $4 };
2576 if ($4 =~ /^(?:C|R)$/) {
2577 $state = 'file_a';
2578 } else {
2579 $state = 'file_b';
2580 }
2581 } elsif ($state eq 'file_a') {
2582 my $x = $mods[$#mods] or croak "Empty array\n";
2583 if ($x->{chg} !~ /^(?:C|R)$/) {
2584 croak "Error parsing $_, $x->{chg}\n";
2585 }
2586 $x->{file_a} = $_;
2587 $state = 'file_b';
2588 } elsif ($state eq 'file_b') {
2589 my $x = $mods[$#mods] or croak "Empty array\n";
2590 if (exists $x->{file_a} && $x->{chg} !~ /^(?:C|R)$/) {
2591 croak "Error parsing $_, $x->{chg}\n";
2592 }
2593 if (!exists $x->{file_a} && $x->{chg} =~ /^(?:C|R)$/) {
2594 croak "Error parsing $_, $x->{chg}\n";
2595 }
2596 $x->{file_b} = $_;
2597 $state = 'meta';
2598 } else {
2599 croak "Error parsing $_\n";
2600 }
2601 }
2602 command_close_pipe($diff_fh, $ctx);
2603 \@mods;
2604}
2605
2606sub check_diff_paths {
2607 my ($ra, $pfx, $rev, $mods) = @_;
2608 my %types;
2609 $pfx .= '/' if length $pfx;
2610
2611 sub type_diff_paths {
2612 my ($ra, $types, $path, $rev) = @_;
2613 my @p = split m#/+#, $path;
2614 my $c = shift @p;
2615 unless (defined $types->{$c}) {
2616 $types->{$c} = $ra->check_path($c, $rev);
2617 }
2618 while (@p) {
2619 $c .= '/' . shift @p;
2620 next if defined $types->{$c};
2621 $types->{$c} = $ra->check_path($c, $rev);
2622 }
2623 }
2624
2625 foreach my $m (@$mods) {
2626 foreach my $f (qw/file_a file_b/) {
2627 next unless defined $m->{$f};
2628 my ($dir) = ($m->{$f} =~ m#^(.*?)/?(?:[^/]+)$#);
2629 if (length $pfx.$dir && ! defined $types{$dir}) {
2630 type_diff_paths($ra, \%types, $pfx.$dir, $rev);
2631 }
2632 }
2633 }
2634 \%types;
2635}
2636
a5e0cedc
EW
2637sub split_path {
2638 return ($_[0] =~ m#^(.*?)/?([^/]+)$#);
2639}
2640
2641sub repo_path {
d3a840dc
EW
2642 my ($self, $path) = @_;
2643 $self->{path_prefix}.(defined $path ? $path : '');
a5e0cedc
EW
2644}
2645
2646sub url_path {
2647 my ($self, $path) = @_;
6e8548cc 2648 $self->{url} . '/' . $self->repo_path($path);
a5e0cedc
EW
2649}
2650
2651sub rmdirs {
61395354 2652 my ($self) = @_;
a5e0cedc
EW
2653 my $rm = $self->{rm};
2654 delete $rm->{''}; # we never delete the url we're tracking
2655 return unless %$rm;
2656
2657 foreach (keys %$rm) {
2658 my @d = split m#/#, $_;
2659 my $c = shift @d;
2660 $rm->{$c} = 1;
2661 while (@d) {
2662 $c .= '/' . shift @d;
2663 $rm->{$c} = 1;
2664 }
2665 }
2666 delete $rm->{$self->{svn_path}};
2667 delete $rm->{''}; # we never delete the url we're tracking
2668 return unless %$rm;
2669
61395354
EW
2670 my ($fh, $ctx) = command_output_pipe(qw/ls-tree --name-only -r -z/,
2671 $self->{tree_b});
a5e0cedc
EW
2672 local $/ = "\0";
2673 while (<$fh>) {
2674 chomp;
747fa12c 2675 my @dn = split m#/#, $_;
c07eee1f
EW
2676 while (pop @dn) {
2677 delete $rm->{join '/', @dn};
2678 }
2679 unless (%$rm) {
22600a25 2680 close $fh;
c07eee1f
EW
2681 return;
2682 }
a5e0cedc 2683 }
aef4e921 2684 command_close_pipe($fh, $ctx);
c07eee1f 2685
a5e0cedc
EW
2686 my ($r, $p, $bat) = ($self->{r}, $self->{pool}, $self->{bat});
2687 foreach my $d (sort { $b =~ tr#/#/# <=> $a =~ tr#/#/# } keys %$rm) {
2688 $self->close_directory($bat->{$d}, $p);
2689 my ($dn) = ($d =~ m#^(.*?)/?(?:[^/]+)$#);
44320b9e 2690 print "\tD+\t$d/\n" unless $::_q;
a5e0cedc
EW
2691 $self->SUPER::delete_entry($d, $r, $bat->{$dn}, $p);
2692 delete $bat->{$d};
2693 }
2694}
2695
2696sub open_or_add_dir {
2697 my ($self, $full_path, $baton) = @_;
6e8548cc
EW
2698 my $t = $self->{types}->{$full_path};
2699 if (!defined $t) {
2700 die "$full_path not known in r$self->{r} or we have a bug!\n";
2701 }
a5e0cedc
EW
2702 if ($t == $SVN::Node::none) {
2703 return $self->add_directory($full_path, $baton,
2704 undef, -1, $self->{pool});
2705 } elsif ($t == $SVN::Node::dir) {
2706 return $self->open_directory($full_path, $baton,
2707 $self->{r}, $self->{pool});
2708 }
2709 print STDERR "$full_path already exists in repository at ",
2710 "r$self->{r} and it is not a directory (",
2711 ($t == $SVN::Node::file ? 'file' : 'unknown'),"/$t)\n";
2712 exit 1;
2713}
2714
2715sub ensure_path {
2716 my ($self, $path) = @_;
2717 my $bat = $self->{bat};
6e8548cc
EW
2718 my $repo_path = $self->repo_path($path);
2719 return $bat->{''} unless (length $repo_path);
2720 my @p = split m#/+#, $repo_path;
a5e0cedc
EW
2721 my $c = shift @p;
2722 $bat->{$c} ||= $self->open_or_add_dir($c, $bat->{''});
2723 while (@p) {
2724 my $c0 = $c;
2725 $c .= '/' . shift @p;
2726 $bat->{$c} ||= $self->open_or_add_dir($c, $bat->{$c0});
2727 }
2728 return $bat->{$c};
2729}
2730
2731sub A {
44320b9e 2732 my ($self, $m) = @_;
a5e0cedc
EW
2733 my ($dir, $file) = split_path($m->{file_b});
2734 my $pbat = $self->ensure_path($dir);
2735 my $fbat = $self->add_file($self->repo_path($m->{file_b}), $pbat,
2736 undef, -1);
44320b9e 2737 print "\tA\t$m->{file_b}\n" unless $::_q;
a5e0cedc
EW
2738 $self->chg_file($fbat, $m);
2739 $self->close_file($fbat,undef,$self->{pool});
2740}
2741
2742sub C {
44320b9e 2743 my ($self, $m) = @_;
a5e0cedc
EW
2744 my ($dir, $file) = split_path($m->{file_b});
2745 my $pbat = $self->ensure_path($dir);
2746 my $fbat = $self->add_file($self->repo_path($m->{file_b}), $pbat,
2747 $self->url_path($m->{file_a}), $self->{r});
44320b9e 2748 print "\tC\t$m->{file_a} => $m->{file_b}\n" unless $::_q;
a5e0cedc
EW
2749 $self->chg_file($fbat, $m);
2750 $self->close_file($fbat,undef,$self->{pool});
2751}
2752
2753sub delete_entry {
2754 my ($self, $path, $pbat) = @_;
2755 my $rpath = $self->repo_path($path);
2756 my ($dir, $file) = split_path($rpath);
2757 $self->{rm}->{$dir} = 1;
2758 $self->SUPER::delete_entry($rpath, $self->{r}, $pbat, $self->{pool});
2759}
2760
2761sub R {
44320b9e 2762 my ($self, $m) = @_;
a5e0cedc
EW
2763 my ($dir, $file) = split_path($m->{file_b});
2764 my $pbat = $self->ensure_path($dir);
2765 my $fbat = $self->add_file($self->repo_path($m->{file_b}), $pbat,
2766 $self->url_path($m->{file_a}), $self->{r});
44320b9e 2767 print "\tR\t$m->{file_a} => $m->{file_b}\n" unless $::_q;
a5e0cedc
EW
2768 $self->chg_file($fbat, $m);
2769 $self->close_file($fbat,undef,$self->{pool});
2770
2771 ($dir, $file) = split_path($m->{file_a});
2772 $pbat = $self->ensure_path($dir);
2773 $self->delete_entry($m->{file_a}, $pbat);
2774}
2775
2776sub M {
44320b9e 2777 my ($self, $m) = @_;
a5e0cedc
EW
2778 my ($dir, $file) = split_path($m->{file_b});
2779 my $pbat = $self->ensure_path($dir);
2780 my $fbat = $self->open_file($self->repo_path($m->{file_b}),
2781 $pbat,$self->{r},$self->{pool});
44320b9e 2782 print "\t$m->{chg}\t$m->{file_b}\n" unless $::_q;
a5e0cedc
EW
2783 $self->chg_file($fbat, $m);
2784 $self->close_file($fbat,undef,$self->{pool});
2785}
2786
2787sub T { shift->M(@_) }
2788
2789sub change_file_prop {
2790 my ($self, $fbat, $pname, $pval) = @_;
2791 $self->SUPER::change_file_prop($fbat, $pname, $pval, $self->{pool});
2792}
2793
2794sub chg_file {
2795 my ($self, $fbat, $m) = @_;
2796 if ($m->{mode_b} =~ /755$/ && $m->{mode_a} !~ /755$/) {
2797 $self->change_file_prop($fbat,'svn:executable','*');
2798 } elsif ($m->{mode_b} !~ /755$/ && $m->{mode_a} =~ /755$/) {
2799 $self->change_file_prop($fbat,'svn:executable',undef);
2800 }
2801 my $fh = IO::File->new_tmpfile or croak $!;
2802 if ($m->{mode_b} =~ /^120/) {
2803 print $fh 'link ' or croak $!;
2804 $self->change_file_prop($fbat,'svn:special','*');
2805 } elsif ($m->{mode_a} =~ /^120/ && $m->{mode_b} !~ /^120/) {
2806 $self->change_file_prop($fbat,'svn:special',undef);
2807 }
2808 defined(my $pid = fork) or croak $!;
2809 if (!$pid) {
2810 open STDOUT, '>&', $fh or croak $!;
2811 exec qw/git-cat-file blob/, $m->{sha1_b} or croak $!;
2812 }
2813 waitpid $pid, 0;
2814 croak $? if $?;
2815 $fh->flush == 0 or croak $!;
2816 seek $fh, 0, 0 or croak $!;
2817
2818 my $md5 = Digest::MD5->new;
2819 $md5->addfile($fh) or croak $!;
2820 seek $fh, 0, 0 or croak $!;
2821
2822 my $exp = $md5->hexdigest;
f7197dff
EW
2823 my $pool = SVN::Pool->new;
2824 my $atd = $self->apply_textdelta($fbat, undef, $pool);
2825 my $got = SVN::TxDelta::send_stream($fh, @$atd, $pool);
a5e0cedc 2826 die "Checksum mismatch\nexpected: $exp\ngot: $got\n" if ($got ne $exp);
f7197dff 2827 $pool->clear;
a5e0cedc
EW
2828
2829 close $fh or croak $!;
2830}
2831
2832sub D {
44320b9e 2833 my ($self, $m) = @_;
a5e0cedc
EW
2834 my ($dir, $file) = split_path($m->{file_b});
2835 my $pbat = $self->ensure_path($dir);
44320b9e 2836 print "\tD\t$m->{file_b}\n" unless $::_q;
a5e0cedc
EW
2837 $self->delete_entry($m->{file_b}, $pbat);
2838}
2839
2840sub close_edit {
2841 my ($self) = @_;
2842 my ($p,$bat) = ($self->{pool}, $self->{bat});
2843 foreach (sort { $b =~ tr#/#/# <=> $a =~ tr#/#/# } keys %$bat) {
6442754d 2844 next if $_ eq '';
a5e0cedc
EW
2845 $self->close_directory($bat->{$_}, $p);
2846 }
6442754d 2847 $self->close_directory($bat->{''}, $p);
a5e0cedc
EW
2848 $self->SUPER::close_edit($p);
2849 $p->clear;
2850}
2851
2852sub abort_edit {
2853 my ($self) = @_;
2854 $self->SUPER::abort_edit($self->{pool});
61395354
EW
2855}
2856
2857sub DESTROY {
2858 my $self = shift;
2859 $self->SUPER::DESTROY(@_);
a5e0cedc
EW
2860 $self->{pool}->clear;
2861}
2862
44320b9e
EW
2863# this drives the editor
2864sub apply_diff {
61395354
EW
2865 my ($self) = @_;
2866 my $mods = $self->{mods};
44320b9e 2867 my %o = ( D => 1, R => 0, C => -1, A => 3, M => 3, T => 3 );
6e8548cc 2868 foreach my $m (sort { $o{$a->{chg}} <=> $o{$b->{chg}} } @$mods) {
44320b9e
EW
2869 my $f = $m->{chg};
2870 if (defined $o{$f}) {
2871 $self->$f($m);
2872 } else {
2873 fatal("Invalid change type: $f\n");
2874 }
2875 }
24e22aa8 2876 $self->rmdirs if $_rmdir;
6e8548cc 2877 if (@$mods == 0) {
44320b9e
EW
2878 $self->abort_edit;
2879 } else {
2880 $self->close_edit;
2881 }
6e8548cc 2882 return scalar @$mods;
44320b9e
EW
2883}
2884
d81bf827 2885package Git::SVN::Ra;
6af1db44 2886use vars qw/@ISA $config_dir $_log_window_size/;
d81bf827
EW
2887use strict;
2888use warnings;
a6a15a99 2889my ($can_do_switch, %ignored_err, $RA);
d81bf827
EW
2890
2891BEGIN {
2892 # enforce temporary pool usage for some simple functions
2893 my $e;
0dc03d6a 2894 foreach (qw/rev_proplist get_latest_revnum get_uuid get_repos_root/) {
d81bf827
EW
2895 $e .= "sub $_ {
2896 my \$self = shift;
2897 my \$pool = SVN::Pool->new;
2898 my \@ret = \$self->SUPER::$_(\@_,\$pool);
2899 \$pool->clear;
2900 wantarray ? \@ret : \$ret[0]; }\n";
2901 }
74a81227 2902
0dc03d6a 2903 eval "$e; 1;" or die $@;
d81bf827
EW
2904}
2905
2906sub new {
2907 my ($class, $url) = @_;
f6f09876 2908 $url =~ s!/+$!!;
5d3b7cd5 2909 return $RA if ($RA && $RA->{url} eq $url);
f6f09876 2910
d81bf827
EW
2911 SVN::_Core::svn_config_ensure($config_dir, undef);
2912 my ($baton, $callbacks) = SVN::Core::auth_open_helper([
2913 SVN::Client::get_simple_provider(),
2914 SVN::Client::get_ssl_server_trust_file_provider(),
2915 SVN::Client::get_simple_prompt_provider(
2916 \&Git::SVN::Prompt::simple, 2),
2917 SVN::Client::get_ssl_client_cert_prompt_provider(
2918 \&Git::SVN::Prompt::ssl_client_cert, 2),
2919 SVN::Client::get_ssl_client_cert_pw_prompt_provider(
2920 \&Git::SVN::Prompt::ssl_client_cert_pw, 2),
2921 SVN::Client::get_username_provider(),
2922 SVN::Client::get_ssl_server_trust_prompt_provider(
2923 \&Git::SVN::Prompt::ssl_server_trust),
2924 SVN::Client::get_username_prompt_provider(
2925 \&Git::SVN::Prompt::username, 2),
2926 ]);
2927 my $config = SVN::Core::config_get_config($config_dir);
2928 my $self = SVN::Ra->new(url => $url, auth => $baton,
2929 config => $config,
2930 pool => SVN::Pool->new,
2931 auth_provider_callbacks => $callbacks);
2932 $self->{svn_path} = $url;
2933 $self->{repos_root} = $self->get_repos_root;
4e9f6cc7 2934 $self->{svn_path} =~ s#^\Q$self->{repos_root}\E(/|$)##;
0dc03d6a
EW
2935 $self->{cache} = { check_path => { r => 0, data => {} },
2936 get_dir => { r => 0, data => {} } };
5d3b7cd5 2937 $RA = bless $self, $class;
d81bf827
EW
2938}
2939
0dc03d6a
EW
2940sub check_path {
2941 my ($self, $path, $r) = @_;
2942 my $cache = $self->{cache}->{check_path};
2943 if ($r == $cache->{r} && exists $cache->{data}->{$path}) {
2944 return $cache->{data}->{$path};
2945 }
2946 my $pool = SVN::Pool->new;
2947 my $t = $self->SUPER::check_path($path, $r, $pool);
2948 $pool->clear;
2949 if ($r != $cache->{r}) {
2950 %{$cache->{data}} = ();
2951 $cache->{r} = $r;
2952 }
2953 $cache->{data}->{$path} = $t;
2954}
2955
2956sub get_dir {
2957 my ($self, $dir, $r) = @_;
2958 my $cache = $self->{cache}->{get_dir};
2959 if ($r == $cache->{r}) {
2960 if (my $x = $cache->{data}->{$dir}) {
2961 return wantarray ? @$x : $x->[0];
2962 }
2963 }
2964 my $pool = SVN::Pool->new;
2965 my ($d, undef, $props) = $self->SUPER::get_dir($dir, $r, $pool);
2966 my %dirents = map { $_ => { kind => $d->{$_}->kind } } keys %$d;
2967 $pool->clear;
2968 if ($r != $cache->{r}) {
2969 %{$cache->{data}} = ();
2970 $cache->{r} = $r;
2971 }
2972 $cache->{data}->{$dir} = [ \%dirents, $r, $props ];
2973 wantarray ? (\%dirents, $r, $props) : \%dirents;
2974}
2975
d81bf827 2976sub DESTROY {
5d3b7cd5 2977 # do not call the real DESTROY since we store ourselves in $RA
d81bf827
EW
2978}
2979
d81bf827
EW
2980sub get_log {
2981 my ($self, @args) = @_;
2982 my $pool = SVN::Pool->new;
d81bf827
EW
2983 splice(@args, 3, 1) if ($SVN::Core::VERSION le '1.2.0');
2984 my $ret = $self->SUPER::get_log(@args, $pool);
2985 $pool->clear;
2986 $ret;
2987}
2988
2989sub get_commit_editor {
44320b9e 2990 my ($self, $log, $cb, $pool) = @_;
d81bf827 2991 my @lock = $SVN::Core::VERSION ge '1.2.0' ? (undef, 0) : ();
44320b9e 2992 $self->SUPER::get_commit_editor($log, $cb, @lock, $pool);
d81bf827
EW
2993}
2994
d81bf827 2995sub gs_do_update {
8a603774
EW
2996 my ($self, $rev_a, $rev_b, $gs, $editor) = @_;
2997 my $new = ($rev_a == $rev_b);
2998 my $path = $gs->{path};
2999
2e5e2480
EW
3000 if ($new && -e $gs->{index}) {
3001 unlink $gs->{index} or die
3002 "Couldn't unlink index: $gs->{index}: $!\n";
3003 }
d81bf827 3004 my $pool = SVN::Pool->new;
8b8fc068 3005 $editor->set_path_strip($path);
2b27f6c8
EW
3006 my (@pc) = split m#/#, $path;
3007 my $reporter = $self->do_update($rev_b, (@pc ? shift @pc : ''),
8a603774 3008 1, $editor, $pool);
d81bf827 3009 my @lock = $SVN::Core::VERSION ge '1.2.0' ? (undef) : ();
2b27f6c8
EW
3010
3011 # Since we can't rely on svn_ra_reparent being available, we'll
3012 # just have to do some magic with set_path to make it so
3013 # we only want a partial path.
3014 my $sp = '';
3015 my $final = join('/', @pc);
3016 while (@pc) {
3017 $reporter->set_path($sp, $rev_b, 0, @lock, $pool);
3018 $sp .= '/' if length $sp;
3019 $sp .= shift @pc;
3020 }
3021 die "BUG: '$sp' != '$final'\n" if ($sp ne $final);
3022
2b27f6c8
EW
3023 $reporter->set_path($sp, $rev_a, $new, @lock, $pool);
3024
d81bf827
EW
3025 $reporter->finish_report($pool);
3026 $pool->clear;
3027 $editor->{git_commit_ok};
3028}
3029
2b27f6c8
EW
3030# this requires SVN 1.4.3 or later (do_switch didn't work before 1.4.3, and
3031# svn_ra_reparent didn't work before 1.4)
d81bf827 3032sub gs_do_switch {
8a603774
EW
3033 my ($self, $rev_a, $rev_b, $gs, $url_b, $editor) = @_;
3034 my $path = $gs->{path};
d81bf827 3035 my $pool = SVN::Pool->new;
2b27f6c8
EW
3036
3037 my $full_url = $self->{url};
3038 my $old_url = $full_url;
3039 $full_url .= "/$path" if length $path;
5d3b7cd5
EW
3040 my ($ra, $reparented);
3041 if ($old_url ne $full_url) {
3042 if ($old_url !~ m#^svn(\+ssh)?://#) {
3043 SVN::_Ra::svn_ra_reparent($self->{session}, $full_url,
3044 $pool);
3045 $self->{url} = $full_url;
3046 $reparented = 1;
3047 } else {
3048 $ra = Git::SVN::Ra->new($full_url);
3049 }
3050 }
3051 $ra ||= $self;
8a603774 3052 my $reporter = $ra->do_switch($rev_b, '', 1, $url_b, $editor, $pool);
d81bf827 3053 my @lock = $SVN::Core::VERSION ge '1.2.0' ? (undef) : ();
8b8fc068 3054 $reporter->set_path('', $rev_a, 0, @lock, $pool);
d81bf827 3055 $reporter->finish_report($pool);
2b27f6c8 3056
5d3b7cd5
EW
3057 if ($reparented) {
3058 SVN::_Ra::svn_ra_reparent($self->{session}, $old_url, $pool);
3059 $self->{url} = $old_url;
3060 }
2b27f6c8 3061
d81bf827
EW
3062 $pool->clear;
3063 $editor->{git_commit_ok};
3064}
3065
0af9c9f9 3066sub gs_fetch_loop_common {
e518192f
EW
3067 my ($self, $base, $head, $gsv, $globs) = @_;
3068 return if ($base > $head);
6af1db44 3069 my $inc = $_log_window_size;
0af9c9f9 3070 my ($min, $max) = ($base, $head < $base + $inc ? $head : $base + $inc);
d2ae1434 3071 my %common;
e518192f
EW
3072 my $common_max = scalar @$gsv;
3073
3074 foreach my $gs (@$gsv) {
d2ae1434
EW
3075 my @tmp = split m#/#, $gs->{path};
3076 my $p = '';
3077 foreach (@tmp) {
3078 $p .= length($p) ? "/$_" : $_;
3079 $common{$p} ||= 0;
3080 $common{$p}++;
3081 }
3082 }
e518192f
EW
3083 $globs ||= [];
3084 $common_max += scalar @$globs;
3085 foreach my $glob (@$globs) {
3086 my @tmp = split m#/#, $glob->{path}->{left};
3087 my $p = '';
3088 foreach (@tmp) {
3089 $p .= length($p) ? "/$_" : $_;
3090 $common{$p} ||= 0;
3091 $common{$p}++;
3092 }
3093 }
3094
d2ae1434
EW
3095 my $longest_path = '';
3096 foreach (sort {length $b <=> length $a} keys %common) {
e518192f 3097 if ($common{$_} == $common_max) {
d2ae1434
EW
3098 $longest_path = $_;
3099 last;
3100 }
0af9c9f9
EW
3101 }
3102 while (1) {
d4eff2bd 3103 my %revs;
d2ae1434 3104 my $err;
f7c3fc4a 3105 my $err_handler = $SVN::Error::handler;
d2ae1434
EW
3106 $SVN::Error::handler = sub {
3107 ($err) = @_;
3108 skip_unknown_revs($err);
3109 };
3110 sub _cb {
3111 my ($paths, $r, $author, $date, $log) = @_;
3112 [ dup_changed_paths($paths),
3113 { author => $author, date => $date, log => $log } ];
3114 }
3115 $self->get_log([$longest_path], $min, $max, 0, 1, 1,
3116 sub { $revs{$_[1]} = _cb(@_) });
3117 if ($err && $max >= $head) {
3118 print STDERR "Path '$longest_path' ",
3119 "was probably deleted:\n",
3120 $err->expanded_message,
3121 "\nWill attempt to follow ",
3122 "revisions r$min .. r$max ",
3123 "committed before the deletion\n";
3124 my $hi = $max;
3125 while (--$hi >= $min) {
3126 my $ok;
3127 $self->get_log([$longest_path], $min, $hi,
3128 0, 1, 1, sub {
3129 $ok ||= $_[1];
3130 $revs{$_[1]} = _cb(@_) });
3131 if ($ok) {
3132 print STDERR "r$min .. r$ok OK\n";
3133 last;
3134 }
3135 }
3136 }
d4eff2bd 3137 $SVN::Error::handler = $err_handler;
fbcc1737 3138
e518192f 3139 my %exists = map { $_->{path} => $_ } @$gsv;
d4eff2bd 3140 foreach my $r (sort {$a <=> $b} keys %revs) {
fbcc1737 3141 my ($paths, $logged) = @{$revs{$r}};
e518192f
EW
3142
3143 foreach my $gs ($self->match_globs(\%exists, $paths,
3144 $globs, $r)) {
fbcc1737
EW
3145 if ($gs->rev_db_max >= $r) {
3146 next;
3147 }
3148 next unless $gs->match_paths($paths, $r);
3149 $gs->{logged_rev_props} = $logged;
e8d120bd
EW
3150 if (my $last_commit = $gs->last_commit) {
3151 $gs->assert_index_clean($last_commit);
3152 }
fbcc1737
EW
3153 my $log_entry = $gs->do_fetch($paths, $r);
3154 if ($log_entry) {
0af9c9f9
EW
3155 $gs->do_git_commit($log_entry);
3156 }
3157 }
e518192f 3158 foreach my $g (@$globs) {
93f2689c
EW
3159 my $k = "svn-remote.$g->{remote}." .
3160 "$g->{t}-maxRev";
3161 Git::SVN::tmp_config($k, $r);
e518192f 3162 }
0af9c9f9 3163 }
9c93fee5
EW
3164 # pre-fill the .rev_db since it'll eventually get filled in
3165 # with '0' x40 if something new gets committed
e518192f 3166 foreach my $gs (@$gsv) {
9c93fee5
EW
3167 next if defined $gs->rev_db_get($max);
3168 $gs->rev_db_set($max, 0 x40);
3169 }
c3560e53
EW
3170 foreach my $g (@$globs) {
3171 my $k = "svn-remote.$g->{remote}.$g->{t}-maxRev";
3172 Git::SVN::tmp_config($k, $max);
3173 }
0af9c9f9
EW
3174 last if $max >= $head;
3175 $min = $max + 1;
3176 $max += $inc;
3177 $max = $head if ($max > $head);
3178 }
0af9c9f9
EW
3179}
3180
e518192f
EW
3181sub match_globs {
3182 my ($self, $exists, $paths, $globs, $r) = @_;
74a81227
EW
3183
3184 sub get_dir_check {
3185 my ($self, $exists, $g, $r) = @_;
3186 my @x = eval { $self->get_dir($g->{path}->{left}, $r) };
3187 return unless scalar @x == 3;
3188 my $dirents = $x[0];
3189 foreach my $de (keys %$dirents) {
0dc03d6a 3190 next if $dirents->{$de}->{kind} != $SVN::Node::dir;
74a81227
EW
3191 my $p = $g->{path}->full_path($de);
3192 next if $exists->{$p};
3193 next if (length $g->{path}->{right} &&
3194 ($self->check_path($p, $r) !=
3195 $SVN::Node::dir));
3196 $exists->{$p} = Git::SVN->init($self->{url}, $p, undef,
3197 $g->{ref}->full_path($de), 1);
3198 }
3199 }
e518192f 3200 foreach my $g (@$globs) {
74a81227
EW
3201 if (my $path = $paths->{"/$g->{path}->{left}"}) {
3202 if ($path->{action} =~ /^[AR]$/) {
3203 get_dir_check($self, $exists, $g, $r);
3204 }
3205 }
e518192f 3206 foreach (keys %$paths) {
28710f74
EW
3207 if (/$g->{path}->{left_regex}/ &&
3208 !/$g->{path}->{regex}/) {
74a81227
EW
3209 next if $paths->{$_}->{action} !~ /^[AR]$/;
3210 get_dir_check($self, $exists, $g, $r);
3211 }
e518192f
EW
3212 next unless /$g->{path}->{regex}/;
3213 my $p = $1;
3214 my $pathname = $g->{path}->full_path($p);
3215 next if $exists->{$pathname};
0c1ec5a1
EW
3216 next if ($self->check_path($pathname, $r) !=
3217 $SVN::Node::dir);
e518192f
EW
3218 $exists->{$pathname} = Git::SVN->init(
3219 $self->{url}, $pathname, undef,
3220 $g->{ref}->full_path($p), 1);
3221 }
3222 my $c = '';
3223 foreach (split m#/#, $g->{path}->{left}) {
3224 $c .= "/$_";
3225 next unless ($paths->{$c} &&
74a81227
EW
3226 ($paths->{$c}->{action} =~ /^[AR]$/));
3227 get_dir_check($self, $exists, $g, $r);
e518192f
EW
3228 }
3229 }
3230 values %$exists;
3231}
3232
e6434f87
EW
3233sub minimize_url {
3234 my ($self) = @_;
3235 return $self->{url} if ($self->{url} eq $self->{repos_root});
3236 my $url = $self->{repos_root};
3237 my @components = split(m!/!, $self->{svn_path});
3238 my $c = '';
3239 do {
3240 $url .= "/$c" if length $c;
3241 eval { (ref $self)->new($url)->get_latest_revnum };
3242 } while ($@ && ($c = shift @components));
3243 $url;
3244}
3245
d81bf827
EW
3246sub can_do_switch {
3247 my $self = shift;
3248 unless (defined $can_do_switch) {
3249 my $pool = SVN::Pool->new;
3250 my $rep = eval {
3251 $self->do_switch(1, '', 0, $self->{url},
3252 SVN::Delta::Editor->new, $pool);
3253 };
3254 if ($@) {
3255 $can_do_switch = 0;
3256 } else {
3257 $rep->abort_report($pool);
3258 $can_do_switch = 1;
3259 }
3260 $pool->clear;
3261 }
3262 $can_do_switch;
3263}
3264
0af9c9f9
EW
3265sub skip_unknown_revs {
3266 my ($err) = @_;
3267 my $errno = $err->apr_err();
3268 # Maybe the branch we're tracking didn't
3269 # exist when the repo started, so it's
3270 # not an error if it doesn't, just continue
3271 #
3272 # Wonderfully consistent library, eh?
3273 # 160013 - svn:// and file://
3274 # 175002 - http(s)://
3275 # 175007 - http(s):// (this repo required authorization, too...)
3276 # More codes may be discovered later...
3277 if ($errno == 175007 || $errno == 175002 || $errno == 160013) {
a6a15a99
EW
3278 my $err_key = $err->expanded_message;
3279 # revision numbers change every time, filter them out
3280 $err_key =~ s/\d+/\0/g;
3281 $err_key = "$errno\0$err_key";
3282 unless ($ignored_err{$err_key}) {
3283 warn "W: Ignoring error from SVN, path probably ",
3284 "does not exist: ($errno): ",
3285 $err->expanded_message,"\n";
3286 $ignored_err{$err_key} = 1;
3287 }
0af9c9f9
EW
3288 return;
3289 }
3290 die "Error from SVN, ($errno): ", $err->expanded_message,"\n";
3291}
3292
3293# svn_log_changed_path_t objects passed to get_log are likely to be
3294# overwritten even if only the refs are copied to an external variable,
3295# so we should dup the structures in their entirety. Using an externally
3296# passed pool (instead of our temporary and quickly cleared pool in
3297# Git::SVN::Ra) does not help matters at all...
3298sub dup_changed_paths {
3299 my ($paths) = @_;
3300 return undef unless $paths;
3301 my %ret;
3302 foreach my $p (keys %$paths) {
3303 my $i = $paths->{$p};
3304 my %s = map { $_ => $i->$_ }
3305 qw/copyfrom_path copyfrom_rev action/;
3306 $ret{$p} = \%s;
3307 }
3308 \%ret;
3309}
3310
f8c9d1d2
EW
3311package Git::SVN::Log;
3312use strict;
3313use warnings;
3314use POSIX qw/strftime/;
3315use vars qw/$TZ $limit $color $pager $non_recursive $verbose $oneline
3316 %rusers $show_commit $incremental/;
3317my $l_fmt;
3318
3319sub cmt_showable {
3320 my ($c) = @_;
3321 return 1 if defined $c->{r};
c16d0871
EW
3322
3323 # big commit message got truncated by the 16k pretty buffer in rev-list
f8c9d1d2
EW
3324 if ($c->{l} && $c->{l}->[-1] eq "...\n" &&
3325 $c->{a_raw} =~ /\@([a-f\d\-]+)>$/) {
c16d0871 3326 @{$c->{l}} = ();
44320b9e 3327 my @log = command(qw/cat-file commit/, $c->{c});
c16d0871
EW
3328
3329 # shift off the headers
3330 shift @log while ($log[0] ne '');
44320b9e 3331 shift @log;
c16d0871
EW
3332
3333 # TODO: make $c->{l} not have a trailing newline in the future
3334 @{$c->{l}} = map { "$_\n" } grep !/^git-svn-id: /, @log;
f8c9d1d2
EW
3335
3336 (undef, $c->{r}, undef) = ::extract_metadata(
44320b9e 3337 (grep(/^git-svn-id: /, @log))[-1]);
f8c9d1d2
EW
3338 }
3339 return defined $c->{r};
3340}
3341
3342sub log_use_color {
3343 return 1 if $color;
3344 my ($dc, $dcvar);
3345 $dcvar = 'color.diff';
3346 $dc = `git-config --get $dcvar`;
3347 if ($dc eq '') {
3348 # nothing at all; fallback to "diff.color"
3349 $dcvar = 'diff.color';
3350 $dc = `git-config --get $dcvar`;
3351 }
3352 chomp($dc);
3353 if ($dc eq 'auto') {
3354 my $pc;
3355 $pc = `git-config --get color.pager`;
3356 if ($pc eq '') {
3357 # does not have it -- fallback to pager.color
3358 $pc = `git-config --bool --get pager.color`;
3359 }
3360 else {
3361 $pc = `git-config --bool --get color.pager`;
3362 if ($?) {
3363 $pc = 'false';
3364 }
3365 }
3366 chomp($pc);
3367 if (-t *STDOUT || (defined $pager && $pc eq 'true')) {
3368 return ($ENV{TERM} && $ENV{TERM} ne 'dumb');
3369 }
3370 return 0;
3371 }
3372 return 0 if $dc eq 'never';
3373 return 1 if $dc eq 'always';
3374 chomp($dc = `git-config --bool --get $dcvar`);
3375 return ($dc eq 'true');
3376}
3377
3378sub git_svn_log_cmd {
3bc718ba
EW
3379 my ($r_min, $r_max, @args) = @_;
3380 my $head = 'HEAD';
3381 foreach my $x (@args) {
3382 last if $x eq '--';
3383 next unless ::verify_ref("$x^0");
3384 $head = $x;
3385 last;
3386 }
3387
13c823fb
EW
3388 my ($url, $rev, $uuid, $gs) = ::working_head_info($head);
3389 $gs ||= Git::SVN->_new;
f8c9d1d2
EW
3390 my @cmd = (qw/log --abbrev-commit --pretty=raw --default/,
3391 $gs->refname);
3392 push @cmd, '-r' unless $non_recursive;
3393 push @cmd, qw/--raw --name-status/ if $verbose;
3394 push @cmd, '--color' if log_use_color();
3395 return @cmd unless defined $r_max;
3396 if ($r_max == $r_min) {
3397 push @cmd, '--max-count=1';
3398 if (my $c = $gs->rev_db_get($r_max)) {
3399 push @cmd, $c;
3400 }
3401 } else {
3402 my ($c_min, $c_max);
3403 $c_max = $gs->rev_db_get($r_max);
3404 $c_min = $gs->rev_db_get($r_min);
3405 if (defined $c_min && defined $c_max) {
3406 if ($r_max > $r_max) {
3407 push @cmd, "$c_min..$c_max";
3408 } else {
3409 push @cmd, "$c_max..$c_min";
3410 }
3411 } elsif ($r_max > $r_min) {
3412 push @cmd, $c_max;
3413 } else {
3414 push @cmd, $c_min;
3415 }
3416 }
3417 return @cmd;
3418}
3419
3420# adapted from pager.c
3421sub config_pager {
3422 $pager ||= $ENV{GIT_PAGER} || $ENV{PAGER};
3423 if (!defined $pager) {
3424 $pager = 'less';
3425 } elsif (length $pager == 0 || $pager eq 'cat') {
3426 $pager = undef;
3427 }
3428}
3429
3430sub run_pager {
3431 return unless -t *STDOUT;
3432 pipe my $rfd, my $wfd or return;
3433 defined(my $pid = fork) or ::fatal "Can't fork: $!\n";
3434 if (!$pid) {
3435 open STDOUT, '>&', $wfd or
3436 ::fatal "Can't redirect to stdout: $!\n";
3437 return;
3438 }
3439 open STDIN, '<&', $rfd or ::fatal "Can't redirect stdin: $!\n";
3440 $ENV{LESS} ||= 'FRSX';
3441 exec $pager or ::fatal "Can't run pager: $! ($pager)\n";
3442}
3443
21819a37
EW
3444sub tz_to_s_offset {
3445 my ($tz) = @_;
3446 $tz =~ s/(\d\d)$//;
3447 return ($1 * 60) + ($tz * 3600);
3448}
3449
f8c9d1d2
EW
3450sub get_author_info {
3451 my ($dest, $author, $t, $tz) = @_;
3452 $author =~ s/(?:^\s*|\s*$)//g;
3453 $dest->{a_raw} = $author;
3454 my $au;
1c8443b0 3455 if ($::_authors) {
f8c9d1d2
EW
3456 $au = $rusers{$author} || undef;
3457 }
3458 if (!$au) {
3459 ($au) = ($author =~ /<([^>]+)\@[^>]+>$/);
3460 }
3461 $dest->{t} = $t;
3462 $dest->{tz} = $tz;
3463 $dest->{a} = $au;
3464 # Date::Parse isn't in the standard Perl distro :(
3465 if ($tz =~ s/^\+//) {
21819a37 3466 $t += tz_to_s_offset($tz);
f8c9d1d2 3467 } elsif ($tz =~ s/^\-//) {
21819a37 3468 $t -= tz_to_s_offset($tz);
f8c9d1d2
EW
3469 }
3470 $dest->{t_utc} = $t;
3471}
3472
3473sub process_commit {
3474 my ($c, $r_min, $r_max, $defer) = @_;
3475 if (defined $r_min && defined $r_max) {
3476 if ($r_min == $c->{r} && $r_min == $r_max) {
3477 show_commit($c);
3478 return 0;
3479 }
3480 return 1 if $r_min == $r_max;
3481 if ($r_min < $r_max) {
3482 # we need to reverse the print order
3483 return 0 if (defined $limit && --$limit < 0);
3484 push @$defer, $c;
3485 return 1;
3486 }
3487 if ($r_min != $r_max) {
3488 return 1 if ($r_min < $c->{r});
3489 return 1 if ($r_max > $c->{r});
3490 }
3491 }
3492 return 0 if (defined $limit && --$limit < 0);
3493 show_commit($c);
3494 return 1;
3495}
3496
3497sub show_commit {
3498 my $c = shift;
3499 if ($oneline) {
3500 my $x = "\n";
3501 if (my $l = $c->{l}) {
3502 while ($l->[0] =~ /^\s*$/) { shift @$l }
3503 $x = $l->[0];
3504 }
3505 $l_fmt ||= 'A' . length($c->{r});
3506 print 'r',pack($l_fmt, $c->{r}),' | ';
3507 print "$c->{c} | " if $show_commit;
3508 print $x;
3509 } else {
3510 show_commit_normal($c);
3511 }
3512}
3513
3514sub show_commit_changed_paths {
3515 my ($c) = @_;
3516 return unless $c->{changed};
3517 print "Changed paths:\n", @{$c->{changed}};
3518}
3519
3520sub show_commit_normal {
3521 my ($c) = @_;
3522 print '-' x72, "\nr$c->{r} | ";
3523 print "$c->{c} | " if $show_commit;
3524 print "$c->{a} | ", strftime("%Y-%m-%d %H:%M:%S %z (%a, %d %b %Y)",
3525 localtime($c->{t_utc})), ' | ';
3526 my $nr_line = 0;
3527
3528 if (my $l = $c->{l}) {
3529 while ($l->[$#$l] eq "\n" && $#$l > 0
3530 && $l->[($#$l - 1)] eq "\n") {
3531 pop @$l;
3532 }
3533 $nr_line = scalar @$l;
3534 if (!$nr_line) {
3535 print "1 line\n\n\n";
3536 } else {
3537 if ($nr_line == 1) {
3538 $nr_line = '1 line';
3539 } else {
3540 $nr_line .= ' lines';
3541 }
3542 print $nr_line, "\n";
3543 show_commit_changed_paths($c);
3544 print "\n";
3545 print $_ foreach @$l;
3546 }
3547 } else {
3548 print "1 line\n";
3549 show_commit_changed_paths($c);
3550 print "\n";
3551
3552 }
488a63ec 3553 foreach my $x (qw/raw stat diff/) {
f8c9d1d2
EW
3554 if ($c->{$x}) {
3555 print "\n";
3556 print $_ foreach @{$c->{$x}}
3557 }
3558 }
3559}
3560
3561sub cmd_show_log {
3562 my (@args) = @_;
3563 my ($r_min, $r_max);
3564 my $r_last = -1; # prevent dupes
3565 if (defined $TZ) {
3566 $ENV{TZ} = $TZ;
3567 } else {
3568 delete $ENV{TZ};
3569 }
3570 if (defined $::_revision) {
3571 if ($::_revision =~ /^(\d+):(\d+)$/) {
3572 ($r_min, $r_max) = ($1, $2);
3573 } elsif ($::_revision =~ /^\d+$/) {
3574 $r_min = $r_max = $::_revision;
3575 } else {
3576 ::fatal "-r$::_revision is not supported, use ",
3577 "standard \'git log\' arguments instead\n";
3578 }
3579 }
3580
3581 config_pager();
3bc718ba 3582 @args = (git_svn_log_cmd($r_min, $r_max, @args), @args);
f8c9d1d2
EW
3583 my $log = command_output_pipe(@args);
3584 run_pager();
488a63ec 3585 my (@k, $c, $d, $stat);
f8c9d1d2
EW
3586 my $esc_color = qr/(?:\033\[(?:(?:\d+;)*\d*)?m)*/;
3587 while (<$log>) {
3588 if (/^${esc_color}commit ($::sha1_short)/o) {
3589 my $cmt = $1;
3590 if ($c && cmt_showable($c) && $c->{r} != $r_last) {
3591 $r_last = $c->{r};
3592 process_commit($c, $r_min, $r_max, \@k) or
3593 goto out;