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