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