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