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