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