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