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