git-svn: memoize conversion of SVN merge ticket info to git commit ranges
[git] / git-svn.perl
1 #!/usr/bin/env perl
2 # Copyright (C) 2006, Eric Wong <normalperson@yhbt.net>
3 # License: GPL v2 or later
4 use warnings;
5 use strict;
6 use vars qw/    $AUTHOR $VERSION
7                 $sha1 $sha1_short $_revision $_repository
8                 $_q $_authors $_authors_prog %users/;
9 $AUTHOR = 'Eric Wong <normalperson@yhbt.net>';
10 $VERSION = '@@GIT_VERSION@@';
11
12 # From which subdir have we been invoked?
13 my $cmd_dir_prefix = eval {
14         command_oneline([qw/rev-parse --show-prefix/], STDERR => 0)
15 } || '';
16
17 my $git_dir_user_set = 1 if defined $ENV{GIT_DIR};
18 $ENV{GIT_DIR} ||= '.git';
19 $Git::SVN::default_repo_id = 'svn';
20 $Git::SVN::default_ref_id = $ENV{GIT_SVN_ID} || 'git-svn';
21 $Git::SVN::Ra::_log_window_size = 100;
22 $Git::SVN::_minimize_url = 'unset';
23
24 if (! exists $ENV{SVN_SSH}) {
25         if (exists $ENV{GIT_SSH}) {
26                 $ENV{SVN_SSH} = $ENV{GIT_SSH};
27                 if ($^O eq 'msys') {
28                         $ENV{SVN_SSH} =~ s/\\/\\\\/g;
29                 }
30         }
31 }
32
33 $Git::SVN::Log::TZ = $ENV{TZ};
34 $ENV{TZ} = 'UTC';
35 $| = 1; # unbuffer STDOUT
36
37 sub fatal (@) { print STDERR "@_\n"; exit 1 }
38 require SVN::Core; # use()-ing this causes segfaults for me... *shrug*
39 require SVN::Ra;
40 require SVN::Delta;
41 if ($SVN::Core::VERSION lt '1.1.0') {
42         fatal "Need SVN::Core 1.1.0 or better (got $SVN::Core::VERSION)";
43 }
44 my $can_compress = eval { require Compress::Zlib; 1};
45 push @Git::SVN::Ra::ISA, 'SVN::Ra';
46 push @SVN::Git::Editor::ISA, 'SVN::Delta::Editor';
47 push @SVN::Git::Fetcher::ISA, 'SVN::Delta::Editor';
48 use Carp qw/croak/;
49 use Digest::MD5;
50 use IO::File qw//;
51 use File::Basename qw/dirname basename/;
52 use File::Path qw/mkpath/;
53 use File::Spec;
54 use File::Find;
55 use Getopt::Long qw/:config gnu_getopt no_ignore_case auto_abbrev/;
56 use IPC::Open3;
57 use Git;
58
59 BEGIN {
60         # import functions from Git into our packages, en masse
61         no strict 'refs';
62         foreach (qw/command command_oneline command_noisy command_output_pipe
63                     command_input_pipe command_close_pipe
64                     command_bidi_pipe command_close_bidi_pipe/) {
65                 for my $package ( qw(SVN::Git::Editor SVN::Git::Fetcher
66                         Git::SVN::Migration Git::SVN::Log Git::SVN),
67                         __PACKAGE__) {
68                         *{"${package}::$_"} = \&{"Git::$_"};
69                 }
70         }
71 }
72
73 my ($SVN);
74
75 $sha1 = qr/[a-f\d]{40}/;
76 $sha1_short = qr/[a-f\d]{4,40}/;
77 my ($_stdin, $_help, $_edit,
78         $_message, $_file, $_branch_dest,
79         $_template, $_shared,
80         $_version, $_fetch_all, $_no_rebase, $_fetch_parent,
81         $_merge, $_strategy, $_dry_run, $_local,
82         $_prefix, $_no_checkout, $_url, $_verbose,
83         $_git_format, $_commit_url, $_tag);
84 $Git::SVN::_follow_parent = 1;
85 $_q ||= 0;
86 my %remote_opts = ( 'username=s' => \$Git::SVN::Prompt::_username,
87                     'config-dir=s' => \$Git::SVN::Ra::config_dir,
88                     'no-auth-cache' => \$Git::SVN::Prompt::_no_auth_cache,
89                     'ignore-paths=s' => \$SVN::Git::Fetcher::_ignore_regex );
90 my %fc_opts = ( 'follow-parent|follow!' => \$Git::SVN::_follow_parent,
91                 'authors-file|A=s' => \$_authors,
92                 'authors-prog=s' => \$_authors_prog,
93                 'repack:i' => \$Git::SVN::_repack,
94                 'noMetadata' => \$Git::SVN::_no_metadata,
95                 'useSvmProps' => \$Git::SVN::_use_svm_props,
96                 'useSvnsyncProps' => \$Git::SVN::_use_svnsync_props,
97                 'log-window-size=i' => \$Git::SVN::Ra::_log_window_size,
98                 'no-checkout' => \$_no_checkout,
99                 'quiet|q+' => \$_q,
100                 'repack-flags|repack-args|repack-opts=s' =>
101                    \$Git::SVN::_repack_flags,
102                 'use-log-author' => \$Git::SVN::_use_log_author,
103                 'add-author-from' => \$Git::SVN::_add_author_from,
104                 'localtime' => \$Git::SVN::_localtime,
105                 %remote_opts );
106
107 my ($_trunk, @_tags, @_branches, $_stdlayout);
108 my %icv;
109 my %init_opts = ( 'template=s' => \$_template, 'shared:s' => \$_shared,
110                   'trunk|T=s' => \$_trunk, 'tags|t=s@' => \@_tags,
111                   'branches|b=s@' => \@_branches, 'prefix=s' => \$_prefix,
112                   'stdlayout|s' => \$_stdlayout,
113                   'minimize-url|m!' => \$Git::SVN::_minimize_url,
114                   'no-metadata' => sub { $icv{noMetadata} = 1 },
115                   'use-svm-props' => sub { $icv{useSvmProps} = 1 },
116                   'use-svnsync-props' => sub { $icv{useSvnsyncProps} = 1 },
117                   'rewrite-root=s' => sub { $icv{rewriteRoot} = $_[1] },
118                   %remote_opts );
119 my %cmt_opts = ( 'edit|e' => \$_edit,
120                 'rmdir' => \$SVN::Git::Editor::_rmdir,
121                 'find-copies-harder' => \$SVN::Git::Editor::_find_copies_harder,
122                 'l=i' => \$SVN::Git::Editor::_rename_limit,
123                 'copy-similarity|C=i'=> \$SVN::Git::Editor::_cp_similarity
124 );
125
126 my %cmd = (
127         fetch => [ \&cmd_fetch, "Download new revisions from SVN",
128                         { 'revision|r=s' => \$_revision,
129                           'fetch-all|all' => \$_fetch_all,
130                           'parent|p' => \$_fetch_parent,
131                            %fc_opts } ],
132         clone => [ \&cmd_clone, "Initialize and fetch revisions",
133                         { 'revision|r=s' => \$_revision,
134                            %fc_opts, %init_opts } ],
135         init => [ \&cmd_init, "Initialize a repo for tracking" .
136                           " (requires URL argument)",
137                           \%init_opts ],
138         'multi-init' => [ \&cmd_multi_init,
139                           "Deprecated alias for ".
140                           "'$0 init -T<trunk> -b<branches> -t<tags>'",
141                           \%init_opts ],
142         dcommit => [ \&cmd_dcommit,
143                      'Commit several diffs to merge with upstream',
144                         { 'merge|m|M' => \$_merge,
145                           'strategy|s=s' => \$_strategy,
146                           'verbose|v' => \$_verbose,
147                           'dry-run|n' => \$_dry_run,
148                           'fetch-all|all' => \$_fetch_all,
149                           'commit-url=s' => \$_commit_url,
150                           'revision|r=i' => \$_revision,
151                           'no-rebase' => \$_no_rebase,
152                         %cmt_opts, %fc_opts } ],
153         branch => [ \&cmd_branch,
154                     'Create a branch in the SVN repository',
155                     { 'message|m=s' => \$_message,
156                       'destination|d=s' => \$_branch_dest,
157                       'dry-run|n' => \$_dry_run,
158                       'tag|t' => \$_tag } ],
159         tag => [ sub { $_tag = 1; cmd_branch(@_) },
160                  'Create a tag in the SVN repository',
161                  { 'message|m=s' => \$_message,
162                    'destination|d=s' => \$_branch_dest,
163                    'dry-run|n' => \$_dry_run } ],
164         'set-tree' => [ \&cmd_set_tree,
165                         "Set an SVN repository to a git tree-ish",
166                         { 'stdin' => \$_stdin, %cmt_opts, %fc_opts, } ],
167         'create-ignore' => [ \&cmd_create_ignore,
168                              'Create a .gitignore per svn:ignore',
169                              { 'revision|r=i' => \$_revision
170                              } ],
171         'mkdirs' => [ \&cmd_mkdirs ,
172                       "recreate empty directories after a checkout",
173                       { 'revision|r=i' => \$_revision } ],
174         'propget' => [ \&cmd_propget,
175                        'Print the value of a property on a file or directory',
176                        { 'revision|r=i' => \$_revision } ],
177         'proplist' => [ \&cmd_proplist,
178                        'List all properties of a file or directory',
179                        { 'revision|r=i' => \$_revision } ],
180         'show-ignore' => [ \&cmd_show_ignore, "Show svn:ignore listings",
181                         { 'revision|r=i' => \$_revision
182                         } ],
183         'show-externals' => [ \&cmd_show_externals, "Show svn:externals listings",
184                         { 'revision|r=i' => \$_revision
185                         } ],
186         'multi-fetch' => [ \&cmd_multi_fetch,
187                            "Deprecated alias for $0 fetch --all",
188                            { 'revision|r=s' => \$_revision, %fc_opts } ],
189         'migrate' => [ sub { },
190                        # no-op, we automatically run this anyways,
191                        'Migrate configuration/metadata/layout from
192                         previous versions of git-svn',
193                        { 'minimize' => \$Git::SVN::Migration::_minimize,
194                          %remote_opts } ],
195         'log' => [ \&Git::SVN::Log::cmd_show_log, 'Show commit logs',
196                         { 'limit=i' => \$Git::SVN::Log::limit,
197                           'revision|r=s' => \$_revision,
198                           'verbose|v' => \$Git::SVN::Log::verbose,
199                           'incremental' => \$Git::SVN::Log::incremental,
200                           'oneline' => \$Git::SVN::Log::oneline,
201                           'show-commit' => \$Git::SVN::Log::show_commit,
202                           'non-recursive' => \$Git::SVN::Log::non_recursive,
203                           'authors-file|A=s' => \$_authors,
204                           'color' => \$Git::SVN::Log::color,
205                           'pager=s' => \$Git::SVN::Log::pager
206                         } ],
207         'find-rev' => [ \&cmd_find_rev,
208                         "Translate between SVN revision numbers and tree-ish",
209                         {} ],
210         'rebase' => [ \&cmd_rebase, "Fetch and rebase your working directory",
211                         { 'merge|m|M' => \$_merge,
212                           'verbose|v' => \$_verbose,
213                           'strategy|s=s' => \$_strategy,
214                           'local|l' => \$_local,
215                           'fetch-all|all' => \$_fetch_all,
216                           'dry-run|n' => \$_dry_run,
217                           %fc_opts } ],
218         'commit-diff' => [ \&cmd_commit_diff,
219                            'Commit a diff between two trees',
220                         { 'message|m=s' => \$_message,
221                           'file|F=s' => \$_file,
222                           'revision|r=s' => \$_revision,
223                         %cmt_opts } ],
224         'info' => [ \&cmd_info,
225                     "Show info about the latest SVN revision
226                      on the current branch",
227                     { 'url' => \$_url, } ],
228         'blame' => [ \&Git::SVN::Log::cmd_blame,
229                     "Show what revision and author last modified each line of a file",
230                     { 'git-format' => \$_git_format } ],
231         'reset' => [ \&cmd_reset,
232                      "Undo fetches back to the specified SVN revision",
233                      { 'revision|r=s' => \$_revision,
234                        'parent|p' => \$_fetch_parent } ],
235         'gc' => [ \&cmd_gc,
236                   "Compress unhandled.log files in .git/svn and remove " .
237                   "index files in .git/svn",
238                 {} ],
239 );
240
241 my $cmd;
242 for (my $i = 0; $i < @ARGV; $i++) {
243         if (defined $cmd{$ARGV[$i]}) {
244                 $cmd = $ARGV[$i];
245                 splice @ARGV, $i, 1;
246                 last;
247         } elsif ($ARGV[$i] eq 'help') {
248                 $cmd = $ARGV[$i+1];
249                 usage(0);
250         }
251 };
252
253 # make sure we're always running at the top-level working directory
254 unless ($cmd && $cmd =~ /(?:clone|init|multi-init)$/) {
255         unless (-d $ENV{GIT_DIR}) {
256                 if ($git_dir_user_set) {
257                         die "GIT_DIR=$ENV{GIT_DIR} explicitly set, ",
258                             "but it is not a directory\n";
259                 }
260                 my $git_dir = delete $ENV{GIT_DIR};
261                 my $cdup = undef;
262                 git_cmd_try {
263                         $cdup = command_oneline(qw/rev-parse --show-cdup/);
264                         $git_dir = '.' unless ($cdup);
265                         chomp $cdup if ($cdup);
266                         $cdup = "." unless ($cdup && length $cdup);
267                 } "Already at toplevel, but $git_dir not found\n";
268                 chdir $cdup or die "Unable to chdir up to '$cdup'\n";
269                 unless (-d $git_dir) {
270                         die "$git_dir still not found after going to ",
271                             "'$cdup'\n";
272                 }
273                 $ENV{GIT_DIR} = $git_dir;
274         }
275         $_repository = Git->repository(Repository => $ENV{GIT_DIR});
276 }
277
278 my %opts = %{$cmd{$cmd}->[2]} if (defined $cmd);
279
280 read_git_config(\%opts);
281 if ($cmd && ($cmd eq 'log' || $cmd eq 'blame')) {
282         Getopt::Long::Configure('pass_through');
283 }
284 my $rv = GetOptions(%opts, 'help|H|h' => \$_help, 'version|V' => \$_version,
285                     'minimize-connections' => \$Git::SVN::Migration::_minimize,
286                     'id|i=s' => \$Git::SVN::default_ref_id,
287                     'svn-remote|remote|R=s' => sub {
288                        $Git::SVN::no_reuse_existing = 1;
289                        $Git::SVN::default_repo_id = $_[1] });
290 exit 1 if (!$rv && $cmd && $cmd ne 'log');
291
292 usage(0) if $_help;
293 version() if $_version;
294 usage(1) unless defined $cmd;
295 load_authors() if $_authors;
296 if (defined $_authors_prog) {
297         $_authors_prog = "'" . File::Spec->rel2abs($_authors_prog) . "'";
298 }
299
300 unless ($cmd =~ /^(?:clone|init|multi-init|commit-diff)$/) {
301         Git::SVN::Migration::migration_check();
302 }
303 Git::SVN::init_vars();
304 eval {
305         Git::SVN::verify_remotes_sanity();
306         $cmd{$cmd}->[0]->(@ARGV);
307 };
308 fatal $@ if $@;
309 post_fetch_checkout();
310 exit 0;
311
312 ####################### primary functions ######################
313 sub usage {
314         my $exit = shift || 0;
315         my $fd = $exit ? \*STDERR : \*STDOUT;
316         print $fd <<"";
317 git-svn - bidirectional operations between a single Subversion tree and git
318 Usage: git svn <command> [options] [arguments]\n
319
320         print $fd "Available commands:\n" unless $cmd;
321
322         foreach (sort keys %cmd) {
323                 next if $cmd && $cmd ne $_;
324                 next if /^multi-/; # don't show deprecated commands
325                 print $fd '  ',pack('A17',$_),$cmd{$_}->[1],"\n";
326                 foreach (sort keys %{$cmd{$_}->[2]}) {
327                         # mixed-case options are for .git/config only
328                         next if /[A-Z]/ && /^[a-z]+$/i;
329                         # prints out arguments as they should be passed:
330                         my $x = s#[:=]s$## ? '<arg>' : s#[:=]i$## ? '<num>' : '';
331                         print $fd ' ' x 21, join(', ', map { length $_ > 1 ?
332                                                         "--$_" : "-$_" }
333                                                 split /\|/,$_)," $x\n";
334                 }
335         }
336         print $fd <<"";
337 \nGIT_SVN_ID may be set in the environment or via the --id/-i switch to an
338 arbitrary identifier if you're tracking multiple SVN branches/repositories in
339 one git repository and want to keep them separate.  See git-svn(1) for more
340 information.
341
342         exit $exit;
343 }
344
345 sub version {
346         print "git-svn version $VERSION (svn $SVN::Core::VERSION)\n";
347         exit 0;
348 }
349
350 sub do_git_init_db {
351         unless (-d $ENV{GIT_DIR}) {
352                 my @init_db = ('init');
353                 push @init_db, "--template=$_template" if defined $_template;
354                 if (defined $_shared) {
355                         if ($_shared =~ /[a-z]/) {
356                                 push @init_db, "--shared=$_shared";
357                         } else {
358                                 push @init_db, "--shared";
359                         }
360                 }
361                 command_noisy(@init_db);
362                 $_repository = Git->repository(Repository => ".git");
363         }
364         command_noisy('config', 'core.autocrlf', 'false');
365         my $set;
366         my $pfx = "svn-remote.$Git::SVN::default_repo_id";
367         foreach my $i (keys %icv) {
368                 die "'$set' and '$i' cannot both be set\n" if $set;
369                 next unless defined $icv{$i};
370                 command_noisy('config', "$pfx.$i", $icv{$i});
371                 $set = $i;
372         }
373         my $ignore_regex = \$SVN::Git::Fetcher::_ignore_regex;
374         command_noisy('config', "$pfx.ignore-paths", $$ignore_regex)
375                 if defined $$ignore_regex;
376 }
377
378 sub init_subdir {
379         my $repo_path = shift or return;
380         mkpath([$repo_path]) unless -d $repo_path;
381         chdir $repo_path or die "Couldn't chdir to $repo_path: $!\n";
382         $ENV{GIT_DIR} = '.git';
383         $_repository = Git->repository(Repository => $ENV{GIT_DIR});
384 }
385
386 sub cmd_clone {
387         my ($url, $path) = @_;
388         if (!defined $path &&
389             (defined $_trunk || @_branches || @_tags ||
390              defined $_stdlayout) &&
391             $url !~ m#^[a-z\+]+://#) {
392                 $path = $url;
393         }
394         $path = basename($url) if !defined $path || !length $path;
395         my $authors_absolute = $_authors ? File::Spec->rel2abs($_authors) : "";
396         cmd_init($url, $path);
397         command_oneline('config', 'svn.authorsfile', $authors_absolute)
398             if $_authors;
399         Git::SVN::fetch_all($Git::SVN::default_repo_id);
400 }
401
402 sub cmd_init {
403         if (defined $_stdlayout) {
404                 $_trunk = 'trunk' if (!defined $_trunk);
405                 @_tags = 'tags' if (! @_tags);
406                 @_branches = 'branches' if (! @_branches);
407         }
408         if (defined $_trunk || @_branches || @_tags) {
409                 return cmd_multi_init(@_);
410         }
411         my $url = shift or die "SVN repository location required ",
412                                "as a command-line argument\n";
413         $url = canonicalize_url($url);
414         init_subdir(@_);
415         do_git_init_db();
416
417         if ($Git::SVN::_minimize_url eq 'unset') {
418                 $Git::SVN::_minimize_url = 0;
419         }
420
421         Git::SVN->init($url);
422 }
423
424 sub cmd_fetch {
425         if (grep /^\d+=./, @_) {
426                 die "'<rev>=<commit>' fetch arguments are ",
427                     "no longer supported.\n";
428         }
429         my ($remote) = @_;
430         if (@_ > 1) {
431                 die "Usage: $0 fetch [--all] [--parent] [svn-remote]\n";
432         }
433         $Git::SVN::no_reuse_existing = undef;
434         if ($_fetch_parent) {
435                 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
436                 unless ($gs) {
437                         die "Unable to determine upstream SVN information from ",
438                             "working tree history\n";
439                 }
440                 # just fetch, don't checkout.
441                 $_no_checkout = 'true';
442                 $_fetch_all ? $gs->fetch_all : $gs->fetch;
443         } elsif ($_fetch_all) {
444                 cmd_multi_fetch();
445         } else {
446                 $remote ||= $Git::SVN::default_repo_id;
447                 Git::SVN::fetch_all($remote, Git::SVN::read_all_remotes());
448         }
449 }
450
451 sub cmd_set_tree {
452         my (@commits) = @_;
453         if ($_stdin || !@commits) {
454                 print "Reading from stdin...\n";
455                 @commits = ();
456                 while (<STDIN>) {
457                         if (/\b($sha1_short)\b/o) {
458                                 unshift @commits, $1;
459                         }
460                 }
461         }
462         my @revs;
463         foreach my $c (@commits) {
464                 my @tmp = command('rev-parse',$c);
465                 if (scalar @tmp == 1) {
466                         push @revs, $tmp[0];
467                 } elsif (scalar @tmp > 1) {
468                         push @revs, reverse(command('rev-list',@tmp));
469                 } else {
470                         fatal "Failed to rev-parse $c";
471                 }
472         }
473         my $gs = Git::SVN->new;
474         my ($r_last, $cmt_last) = $gs->last_rev_commit;
475         $gs->fetch;
476         if (defined $gs->{last_rev} && $r_last != $gs->{last_rev}) {
477                 fatal "There are new revisions that were fetched ",
478                       "and need to be merged (or acknowledged) ",
479                       "before committing.\nlast rev: $r_last\n",
480                       " current: $gs->{last_rev}";
481         }
482         $gs->set_tree($_) foreach @revs;
483         print "Done committing ",scalar @revs," revisions to SVN\n";
484         unlink $gs->{index};
485 }
486
487 sub cmd_dcommit {
488         my $head = shift;
489         git_cmd_try { command_oneline(qw/diff-index --quiet HEAD/) }
490                 'Cannot dcommit with a dirty index.  Commit your changes first, '
491                 . "or stash them with `git stash'.\n";
492         $head ||= 'HEAD';
493
494         my $old_head;
495         if ($head ne 'HEAD') {
496                 $old_head = eval {
497                         command_oneline([qw/symbolic-ref -q HEAD/])
498                 };
499                 if ($old_head) {
500                         $old_head =~ s{^refs/heads/}{};
501                 } else {
502                         $old_head = eval { command_oneline(qw/rev-parse HEAD/) };
503                 }
504                 command(['checkout', $head], STDERR => 0);
505         }
506
507         my @refs;
508         my ($url, $rev, $uuid, $gs) = working_head_info('HEAD', \@refs);
509         unless ($gs) {
510                 die "Unable to determine upstream SVN information from ",
511                     "$head history.\nPerhaps the repository is empty.";
512         }
513
514         if (defined $_commit_url) {
515                 $url = $_commit_url;
516         } else {
517                 $url = eval { command_oneline('config', '--get',
518                               "svn-remote.$gs->{repo_id}.commiturl") };
519                 if (!$url) {
520                         $url = $gs->full_url
521                 }
522         }
523
524         my $last_rev = $_revision if defined $_revision;
525         if ($url) {
526                 print "Committing to $url ...\n";
527         }
528         my ($linear_refs, $parents) = linearize_history($gs, \@refs);
529         if ($_no_rebase && scalar(@$linear_refs) > 1) {
530                 warn "Attempting to commit more than one change while ",
531                      "--no-rebase is enabled.\n",
532                      "If these changes depend on each other, re-running ",
533                      "without --no-rebase may be required."
534         }
535         my $expect_url = $url;
536         Git::SVN::remove_username($expect_url);
537         while (1) {
538                 my $d = shift @$linear_refs or last;
539                 unless (defined $last_rev) {
540                         (undef, $last_rev, undef) = cmt_metadata("$d~1");
541                         unless (defined $last_rev) {
542                                 fatal "Unable to extract revision information ",
543                                       "from commit $d~1";
544                         }
545                 }
546                 if ($_dry_run) {
547                         print "diff-tree $d~1 $d\n";
548                 } else {
549                         my $cmt_rev;
550                         my %ed_opts = ( r => $last_rev,
551                                         log => get_commit_entry($d)->{log},
552                                         ra => Git::SVN::Ra->new($url),
553                                         config => SVN::Core::config_get_config(
554                                                 $Git::SVN::Ra::config_dir
555                                         ),
556                                         tree_a => "$d~1",
557                                         tree_b => $d,
558                                         editor_cb => sub {
559                                                print "Committed r$_[0]\n";
560                                                $cmt_rev = $_[0];
561                                         },
562                                         svn_path => '');
563                         if (!SVN::Git::Editor->new(\%ed_opts)->apply_diff) {
564                                 print "No changes\n$d~1 == $d\n";
565                         } elsif ($parents->{$d} && @{$parents->{$d}}) {
566                                 $gs->{inject_parents_dcommit}->{$cmt_rev} =
567                                                                $parents->{$d};
568                         }
569                         $_fetch_all ? $gs->fetch_all : $gs->fetch;
570                         $last_rev = $cmt_rev;
571                         next if $_no_rebase;
572
573                         # we always want to rebase against the current HEAD,
574                         # not any head that was passed to us
575                         my @diff = command('diff-tree', $d,
576                                            $gs->refname, '--');
577                         my @finish;
578                         if (@diff) {
579                                 @finish = rebase_cmd();
580                                 print STDERR "W: $d and ", $gs->refname,
581                                              " differ, using @finish:\n",
582                                              join("\n", @diff), "\n";
583                         } else {
584                                 print "No changes between current HEAD and ",
585                                       $gs->refname,
586                                       "\nResetting to the latest ",
587                                       $gs->refname, "\n";
588                                 @finish = qw/reset --mixed/;
589                         }
590                         command_noisy(@finish, $gs->refname);
591                         if (@diff) {
592                                 @refs = ();
593                                 my ($url_, $rev_, $uuid_, $gs_) =
594                                               working_head_info('HEAD', \@refs);
595                                 my ($linear_refs_, $parents_) =
596                                               linearize_history($gs_, \@refs);
597                                 if (scalar(@$linear_refs) !=
598                                     scalar(@$linear_refs_)) {
599                                         fatal "# of revisions changed ",
600                                           "\nbefore:\n",
601                                           join("\n", @$linear_refs),
602                                           "\n\nafter:\n",
603                                           join("\n", @$linear_refs_), "\n",
604                                           'If you are attempting to commit ',
605                                           "merges, try running:\n\t",
606                                           'git rebase --interactive',
607                                           '--preserve-merges ',
608                                           $gs->refname,
609                                           "\nBefore dcommitting";
610                                 }
611                                 if ($url_ ne $expect_url) {
612                                         if ($url_ eq $gs->metadata_url) {
613                                                 print
614                                                   "Accepting rewritten URL:",
615                                                   " $url_\n";
616                                         } else {
617                                                 fatal
618                                                   "URL mismatch after rebase:",
619                                                   " $url_ != $expect_url";
620                                         }
621                                 }
622                                 if ($uuid_ ne $uuid) {
623                                         fatal "uuid mismatch after rebase: ",
624                                               "$uuid_ != $uuid";
625                                 }
626                                 # remap parents
627                                 my (%p, @l, $i);
628                                 for ($i = 0; $i < scalar @$linear_refs; $i++) {
629                                         my $new = $linear_refs_->[$i] or next;
630                                         $p{$new} =
631                                                 $parents->{$linear_refs->[$i]};
632                                         push @l, $new;
633                                 }
634                                 $parents = \%p;
635                                 $linear_refs = \@l;
636                         }
637                 }
638         }
639
640         if ($old_head) {
641                 my $new_head = command_oneline(qw/rev-parse HEAD/);
642                 my $new_is_symbolic = eval {
643                         command_oneline(qw/symbolic-ref -q HEAD/);
644                 };
645                 if ($new_is_symbolic) {
646                         print "dcommitted the branch ", $head, "\n";
647                 } else {
648                         print "dcommitted on a detached HEAD because you gave ",
649                               "a revision argument.\n",
650                               "The rewritten commit is: ", $new_head, "\n";
651                 }
652                 command(['checkout', $old_head], STDERR => 0);
653         }
654
655         unlink $gs->{index};
656 }
657
658 sub cmd_branch {
659         my ($branch_name, $head) = @_;
660
661         unless (defined $branch_name && length $branch_name) {
662                 die(($_tag ? "tag" : "branch") . " name required\n");
663         }
664         $head ||= 'HEAD';
665
666         my ($src, $rev, undef, $gs) = working_head_info($head);
667
668         my $remote = Git::SVN::read_all_remotes()->{$gs->{repo_id}};
669         my $allglobs = $remote->{ $_tag ? 'tags' : 'branches' };
670         my $glob;
671         if ($#{$allglobs} == 0) {
672                 $glob = $allglobs->[0];
673         } else {
674                 unless(defined $_branch_dest) {
675                         die "Multiple ",
676                             $_tag ? "tag" : "branch",
677                             " paths defined for Subversion repository.\n",
678                             "You must specify where you want to create the ",
679                             $_tag ? "tag" : "branch",
680                             " with the --destination argument.\n";
681                 }
682                 foreach my $g (@{$allglobs}) {
683                         # SVN::Git::Editor could probably be moved to Git.pm..
684                         my $re = SVN::Git::Editor::glob2pat($g->{path}->{left});
685                         if ($_branch_dest =~ /$re/) {
686                                 $glob = $g;
687                                 last;
688                         }
689                 }
690                 unless (defined $glob) {
691                         my $dest_re = qr/\b\Q$_branch_dest\E\b/;
692                         foreach my $g (@{$allglobs}) {
693                                 $g->{path}->{left} =~ /$dest_re/ or next;
694                                 if (defined $glob) {
695                                         die "Ambiguous destination: ",
696                                             $_branch_dest, "\nmatches both '",
697                                             $glob->{path}->{left}, "' and '",
698                                             $g->{path}->{left}, "'\n";
699                                 }
700                                 $glob = $g;
701                         }
702                         unless (defined $glob) {
703                                 die "Unknown ",
704                                     $_tag ? "tag" : "branch",
705                                     " destination $_branch_dest\n";
706                         }
707                 }
708         }
709         my ($lft, $rgt) = @{ $glob->{path} }{qw/left right/};
710         my $dst = join '/', $remote->{url}, $lft, $branch_name, ($rgt || ());
711
712         my $ctx = SVN::Client->new(
713                 auth    => Git::SVN::Ra::_auth_providers(),
714                 log_msg => sub {
715                         ${ $_[0] } = defined $_message
716                                 ? $_message
717                                 : 'Create ' . ($_tag ? 'tag ' : 'branch ' )
718                                 . $branch_name;
719                 },
720         );
721
722         eval {
723                 $ctx->ls($dst, 'HEAD', 0);
724         } and die "branch ${branch_name} already exists\n";
725
726         print "Copying ${src} at r${rev} to ${dst}...\n";
727         $ctx->copy($src, $rev, $dst)
728                 unless $_dry_run;
729
730         $gs->fetch_all;
731 }
732
733 sub cmd_find_rev {
734         my $revision_or_hash = shift or die "SVN or git revision required ",
735                                             "as a command-line argument\n";
736         my $result;
737         if ($revision_or_hash =~ /^r\d+$/) {
738                 my $head = shift;
739                 $head ||= 'HEAD';
740                 my @refs;
741                 my (undef, undef, $uuid, $gs) = working_head_info($head, \@refs);
742                 unless ($gs) {
743                         die "Unable to determine upstream SVN information from ",
744                             "$head history\n";
745                 }
746                 my $desired_revision = substr($revision_or_hash, 1);
747                 $result = $gs->rev_map_get($desired_revision, $uuid);
748         } else {
749                 my (undef, $rev, undef) = cmt_metadata($revision_or_hash);
750                 $result = $rev;
751         }
752         print "$result\n" if $result;
753 }
754
755 sub cmd_rebase {
756         command_noisy(qw/update-index --refresh/);
757         my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
758         unless ($gs) {
759                 die "Unable to determine upstream SVN information from ",
760                     "working tree history\n";
761         }
762         if ($_dry_run) {
763                 print "Remote Branch: " . $gs->refname . "\n";
764                 print "SVN URL: " . $url . "\n";
765                 return;
766         }
767         if (command(qw/diff-index HEAD --/)) {
768                 print STDERR "Cannot rebase with uncommited changes:\n";
769                 command_noisy('status');
770                 exit 1;
771         }
772         unless ($_local) {
773                 # rebase will checkout for us, so no need to do it explicitly
774                 $_no_checkout = 'true';
775                 $_fetch_all ? $gs->fetch_all : $gs->fetch;
776         }
777         command_noisy(rebase_cmd(), $gs->refname);
778         $gs->mkemptydirs;
779 }
780
781 sub cmd_show_ignore {
782         my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
783         $gs ||= Git::SVN->new;
784         my $r = (defined $_revision ? $_revision : $gs->ra->get_latest_revnum);
785         $gs->prop_walk($gs->{path}, $r, sub {
786                 my ($gs, $path, $props) = @_;
787                 print STDOUT "\n# $path\n";
788                 my $s = $props->{'svn:ignore'} or return;
789                 $s =~ s/[\r\n]+/\n/g;
790                 $s =~ s/^\n+//;
791                 chomp $s;
792                 $s =~ s#^#$path#gm;
793                 print STDOUT "$s\n";
794         });
795 }
796
797 sub cmd_show_externals {
798         my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
799         $gs ||= Git::SVN->new;
800         my $r = (defined $_revision ? $_revision : $gs->ra->get_latest_revnum);
801         $gs->prop_walk($gs->{path}, $r, sub {
802                 my ($gs, $path, $props) = @_;
803                 print STDOUT "\n# $path\n";
804                 my $s = $props->{'svn:externals'} or return;
805                 $s =~ s/[\r\n]+/\n/g;
806                 chomp $s;
807                 $s =~ s#^#$path#gm;
808                 print STDOUT "$s\n";
809         });
810 }
811
812 sub cmd_create_ignore {
813         my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
814         $gs ||= Git::SVN->new;
815         my $r = (defined $_revision ? $_revision : $gs->ra->get_latest_revnum);
816         $gs->prop_walk($gs->{path}, $r, sub {
817                 my ($gs, $path, $props) = @_;
818                 # $path is of the form /path/to/dir/
819                 $path = '.' . $path;
820                 # SVN can have attributes on empty directories,
821                 # which git won't track
822                 mkpath([$path]) unless -d $path;
823                 my $ignore = $path . '.gitignore';
824                 my $s = $props->{'svn:ignore'} or return;
825                 open(GITIGNORE, '>', $ignore)
826                   or fatal("Failed to open `$ignore' for writing: $!");
827                 $s =~ s/[\r\n]+/\n/g;
828                 $s =~ s/^\n+//;
829                 chomp $s;
830                 # Prefix all patterns so that the ignore doesn't apply
831                 # to sub-directories.
832                 $s =~ s#^#/#gm;
833                 print GITIGNORE "$s\n";
834                 close(GITIGNORE)
835                   or fatal("Failed to close `$ignore': $!");
836                 command_noisy('add', '-f', $ignore);
837         });
838 }
839
840 sub cmd_mkdirs {
841         my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
842         $gs ||= Git::SVN->new;
843         $gs->mkemptydirs($_revision);
844 }
845
846 sub canonicalize_path {
847         my ($path) = @_;
848         my $dot_slash_added = 0;
849         if (substr($path, 0, 1) ne "/") {
850                 $path = "./" . $path;
851                 $dot_slash_added = 1;
852         }
853         # File::Spec->canonpath doesn't collapse x/../y into y (for a
854         # good reason), so let's do this manually.
855         $path =~ s#/+#/#g;
856         $path =~ s#/\.(?:/|$)#/#g;
857         $path =~ s#/[^/]+/\.\.##g;
858         $path =~ s#/$##g;
859         $path =~ s#^\./## if $dot_slash_added;
860         $path =~ s#^/##;
861         $path =~ s#^\.$##;
862         return $path;
863 }
864
865 sub canonicalize_url {
866         my ($url) = @_;
867         $url =~ s#^([^:]+://[^/]*/)(.*)$#$1 . canonicalize_path($2)#e;
868         return $url;
869 }
870
871 # get_svnprops(PATH)
872 # ------------------
873 # Helper for cmd_propget and cmd_proplist below.
874 sub get_svnprops {
875         my $path = shift;
876         my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
877         $gs ||= Git::SVN->new;
878
879         # prefix THE PATH by the sub-directory from which the user
880         # invoked us.
881         $path = $cmd_dir_prefix . $path;
882         fatal("No such file or directory: $path") unless -e $path;
883         my $is_dir = -d $path ? 1 : 0;
884         $path = $gs->{path} . '/' . $path;
885
886         # canonicalize the path (otherwise libsvn will abort or fail to
887         # find the file)
888         $path = canonicalize_path($path);
889
890         my $r = (defined $_revision ? $_revision : $gs->ra->get_latest_revnum);
891         my $props;
892         if ($is_dir) {
893                 (undef, undef, $props) = $gs->ra->get_dir($path, $r);
894         }
895         else {
896                 (undef, $props) = $gs->ra->get_file($path, $r, undef);
897         }
898         return $props;
899 }
900
901 # cmd_propget (PROP, PATH)
902 # ------------------------
903 # Print the SVN property PROP for PATH.
904 sub cmd_propget {
905         my ($prop, $path) = @_;
906         $path = '.' if not defined $path;
907         usage(1) if not defined $prop;
908         my $props = get_svnprops($path);
909         if (not defined $props->{$prop}) {
910                 fatal("`$path' does not have a `$prop' SVN property.");
911         }
912         print $props->{$prop} . "\n";
913 }
914
915 # cmd_proplist (PATH)
916 # -------------------
917 # Print the list of SVN properties for PATH.
918 sub cmd_proplist {
919         my $path = shift;
920         $path = '.' if not defined $path;
921         my $props = get_svnprops($path);
922         print "Properties on '$path':\n";
923         foreach (sort keys %{$props}) {
924                 print "  $_\n";
925         }
926 }
927
928 sub cmd_multi_init {
929         my $url = shift;
930         unless (defined $_trunk || @_branches || @_tags) {
931                 usage(1);
932         }
933
934         $_prefix = '' unless defined $_prefix;
935         if (defined $url) {
936                 $url = canonicalize_url($url);
937                 init_subdir(@_);
938         }
939         do_git_init_db();
940         if (defined $_trunk) {
941                 my $trunk_ref = 'refs/remotes/' . $_prefix . 'trunk';
942                 # try both old-style and new-style lookups:
943                 my $gs_trunk = eval { Git::SVN->new($trunk_ref) };
944                 unless ($gs_trunk) {
945                         my ($trunk_url, $trunk_path) =
946                                               complete_svn_url($url, $_trunk);
947                         $gs_trunk = Git::SVN->init($trunk_url, $trunk_path,
948                                                    undef, $trunk_ref);
949                 }
950         }
951         return unless @_branches || @_tags;
952         my $ra = $url ? Git::SVN::Ra->new($url) : undef;
953         foreach my $path (@_branches) {
954                 complete_url_ls_init($ra, $path, '--branches/-b', $_prefix);
955         }
956         foreach my $path (@_tags) {
957                 complete_url_ls_init($ra, $path, '--tags/-t', $_prefix.'tags/');
958         }
959 }
960
961 sub cmd_multi_fetch {
962         $Git::SVN::no_reuse_existing = undef;
963         my $remotes = Git::SVN::read_all_remotes();
964         foreach my $repo_id (sort keys %$remotes) {
965                 if ($remotes->{$repo_id}->{url}) {
966                         Git::SVN::fetch_all($repo_id, $remotes);
967                 }
968         }
969 }
970
971 # this command is special because it requires no metadata
972 sub cmd_commit_diff {
973         my ($ta, $tb, $url) = @_;
974         my $usage = "Usage: $0 commit-diff -r<revision> ".
975                     "<tree-ish> <tree-ish> [<URL>]";
976         fatal($usage) if (!defined $ta || !defined $tb);
977         my $svn_path = '';
978         if (!defined $url) {
979                 my $gs = eval { Git::SVN->new };
980                 if (!$gs) {
981                         fatal("Needed URL or usable git-svn --id in ",
982                               "the command-line\n", $usage);
983                 }
984                 $url = $gs->{url};
985                 $svn_path = $gs->{path};
986         }
987         unless (defined $_revision) {
988                 fatal("-r|--revision is a required argument\n", $usage);
989         }
990         if (defined $_message && defined $_file) {
991                 fatal("Both --message/-m and --file/-F specified ",
992                       "for the commit message.\n",
993                       "I have no idea what you mean");
994         }
995         if (defined $_file) {
996                 $_message = file_to_s($_file);
997         } else {
998                 $_message ||= get_commit_entry($tb)->{log};
999         }
1000         my $ra ||= Git::SVN::Ra->new($url);
1001         my $r = $_revision;
1002         if ($r eq 'HEAD') {
1003                 $r = $ra->get_latest_revnum;
1004         } elsif ($r !~ /^\d+$/) {
1005                 die "revision argument: $r not understood by git-svn\n";
1006         }
1007         my %ed_opts = ( r => $r,
1008                         log => $_message,
1009                         ra => $ra,
1010                         tree_a => $ta,
1011                         tree_b => $tb,
1012                         editor_cb => sub { print "Committed r$_[0]\n" },
1013                         svn_path => $svn_path );
1014         if (!SVN::Git::Editor->new(\%ed_opts)->apply_diff) {
1015                 print "No changes\n$ta == $tb\n";
1016         }
1017 }
1018
1019 sub escape_uri_only {
1020         my ($uri) = @_;
1021         my @tmp;
1022         foreach (split m{/}, $uri) {
1023                 s/([^~\w.%+-]|%(?![a-fA-F0-9]{2}))/sprintf("%%%02X",ord($1))/eg;
1024                 push @tmp, $_;
1025         }
1026         join('/', @tmp);
1027 }
1028
1029 sub escape_url {
1030         my ($url) = @_;
1031         if ($url =~ m#^([^:]+)://([^/]*)(.*)$#) {
1032                 my ($scheme, $domain, $uri) = ($1, $2, escape_uri_only($3));
1033                 $url = "$scheme://$domain$uri";
1034         }
1035         $url;
1036 }
1037
1038 sub cmd_info {
1039         my $path = canonicalize_path(defined($_[0]) ? $_[0] : ".");
1040         my $fullpath = canonicalize_path($cmd_dir_prefix . $path);
1041         if (exists $_[1]) {
1042                 die "Too many arguments specified\n";
1043         }
1044
1045         my ($file_type, $diff_status) = find_file_type_and_diff_status($path);
1046
1047         if (!$file_type && !$diff_status) {
1048                 print STDERR "svn: '$path' is not under version control\n";
1049                 exit 1;
1050         }
1051
1052         my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
1053         unless ($gs) {
1054                 die "Unable to determine upstream SVN information from ",
1055                     "working tree history\n";
1056         }
1057
1058         # canonicalize_path() will return "" to make libsvn 1.5.x happy,
1059         $path = "." if $path eq "";
1060
1061         my $full_url = $url . ($fullpath eq "" ? "" : "/$fullpath");
1062
1063         if ($_url) {
1064                 print escape_url($full_url), "\n";
1065                 return;
1066         }
1067
1068         my $result = "Path: $path\n";
1069         $result .= "Name: " . basename($path) . "\n" if $file_type ne "dir";
1070         $result .= "URL: " . escape_url($full_url) . "\n";
1071
1072         eval {
1073                 my $repos_root = $gs->repos_root;
1074                 Git::SVN::remove_username($repos_root);
1075                 $result .= "Repository Root: " . escape_url($repos_root) . "\n";
1076         };
1077         if ($@) {
1078                 $result .= "Repository Root: (offline)\n";
1079         }
1080         $result .= "Repository UUID: $uuid\n" unless $diff_status eq "A" &&
1081                 ($SVN::Core::VERSION le '1.5.4' || $file_type ne "dir");
1082         $result .= "Revision: " . ($diff_status eq "A" ? 0 : $rev) . "\n";
1083
1084         $result .= "Node Kind: " .
1085                    ($file_type eq "dir" ? "directory" : "file") . "\n";
1086
1087         my $schedule = $diff_status eq "A"
1088                        ? "add"
1089                        : ($diff_status eq "D" ? "delete" : "normal");
1090         $result .= "Schedule: $schedule\n";
1091
1092         if ($diff_status eq "A") {
1093                 print $result, "\n";
1094                 return;
1095         }
1096
1097         my ($lc_author, $lc_rev, $lc_date_utc);
1098         my @args = Git::SVN::Log::git_svn_log_cmd($rev, $rev, "--", $fullpath);
1099         my $log = command_output_pipe(@args);
1100         my $esc_color = qr/(?:\033\[(?:(?:\d+;)*\d*)?m)*/;
1101         while (<$log>) {
1102                 if (/^${esc_color}author (.+) <[^>]+> (\d+) ([\-\+]?\d+)$/o) {
1103                         $lc_author = $1;
1104                         $lc_date_utc = Git::SVN::Log::parse_git_date($2, $3);
1105                 } elsif (/^${esc_color}    (git-svn-id:.+)$/o) {
1106                         (undef, $lc_rev, undef) = ::extract_metadata($1);
1107                 }
1108         }
1109         close $log;
1110
1111         Git::SVN::Log::set_local_timezone();
1112
1113         $result .= "Last Changed Author: $lc_author\n";
1114         $result .= "Last Changed Rev: $lc_rev\n";
1115         $result .= "Last Changed Date: " .
1116                    Git::SVN::Log::format_svn_date($lc_date_utc) . "\n";
1117
1118         if ($file_type ne "dir") {
1119                 my $text_last_updated_date =
1120                     ($diff_status eq "D" ? $lc_date_utc : (stat $path)[9]);
1121                 $result .=
1122                     "Text Last Updated: " .
1123                     Git::SVN::Log::format_svn_date($text_last_updated_date) .
1124                     "\n";
1125                 my $checksum;
1126                 if ($diff_status eq "D") {
1127                         my ($fh, $ctx) =
1128                             command_output_pipe(qw(cat-file blob), "HEAD:$path");
1129                         if ($file_type eq "link") {
1130                                 my $file_name = <$fh>;
1131                                 $checksum = md5sum("link $file_name");
1132                         } else {
1133                                 $checksum = md5sum($fh);
1134                         }
1135                         command_close_pipe($fh, $ctx);
1136                 } elsif ($file_type eq "link") {
1137                         my $file_name =
1138                             command(qw(cat-file blob), "HEAD:$path");
1139                         $checksum =
1140                             md5sum("link " . $file_name);
1141                 } else {
1142                         open FILE, "<", $path or die $!;
1143                         $checksum = md5sum(\*FILE);
1144                         close FILE or die $!;
1145                 }
1146                 $result .= "Checksum: " . $checksum . "\n";
1147         }
1148
1149         print $result, "\n";
1150 }
1151
1152 sub cmd_reset {
1153         my $target = shift || $_revision or die "SVN revision required\n";
1154         $target = $1 if $target =~ /^r(\d+)$/;
1155         $target =~ /^\d+$/ or die "Numeric SVN revision expected\n";
1156         my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
1157         unless ($gs) {
1158                 die "Unable to determine upstream SVN information from ".
1159                     "history\n";
1160         }
1161         my ($r, $c) = $gs->find_rev_before($target, not $_fetch_parent);
1162         $gs->rev_map_set($r, $c, 'reset', $uuid);
1163         print "r$r = $c ($gs->{ref_id})\n";
1164 }
1165
1166 sub cmd_gc {
1167         if (!$can_compress) {
1168                 warn "Compress::Zlib could not be found; unhandled.log " .
1169                      "files will not be compressed.\n";
1170         }
1171         find({ wanted => \&gc_directory, no_chdir => 1}, "$ENV{GIT_DIR}/svn");
1172 }
1173
1174 ########################### utility functions #########################
1175
1176 sub rebase_cmd {
1177         my @cmd = qw/rebase/;
1178         push @cmd, '-v' if $_verbose;
1179         push @cmd, qw/--merge/ if $_merge;
1180         push @cmd, "--strategy=$_strategy" if $_strategy;
1181         @cmd;
1182 }
1183
1184 sub post_fetch_checkout {
1185         return if $_no_checkout;
1186         my $gs = $Git::SVN::_head or return;
1187         return if verify_ref('refs/heads/master^0');
1188
1189         # look for "trunk" ref if it exists
1190         my $remote = Git::SVN::read_all_remotes()->{$gs->{repo_id}};
1191         my $fetch = $remote->{fetch};
1192         if ($fetch) {
1193                 foreach my $p (keys %$fetch) {
1194                         basename($fetch->{$p}) eq 'trunk' or next;
1195                         $gs = Git::SVN->new($fetch->{$p}, $gs->{repo_id}, $p);
1196                         last;
1197                 }
1198         }
1199
1200         my $valid_head = verify_ref('HEAD^0');
1201         command_noisy(qw(update-ref refs/heads/master), $gs->refname);
1202         return if ($valid_head || !verify_ref('HEAD^0'));
1203
1204         return if $ENV{GIT_DIR} !~ m#^(?:.*/)?\.git$#;
1205         my $index = $ENV{GIT_INDEX_FILE} || "$ENV{GIT_DIR}/index";
1206         return if -f $index;
1207
1208         return if command_oneline(qw/rev-parse --is-inside-work-tree/) eq 'false';
1209         return if command_oneline(qw/rev-parse --is-inside-git-dir/) eq 'true';
1210         command_noisy(qw/read-tree -m -u -v HEAD HEAD/);
1211         print STDERR "Checked out HEAD:\n  ",
1212                      $gs->full_url, " r", $gs->last_rev, "\n";
1213         $gs->mkemptydirs($gs->last_rev);
1214 }
1215
1216 sub complete_svn_url {
1217         my ($url, $path) = @_;
1218         $path =~ s#/+$##;
1219         if ($path !~ m#^[a-z\+]+://#) {
1220                 if (!defined $url || $url !~ m#^[a-z\+]+://#) {
1221                         fatal("E: '$path' is not a complete URL ",
1222                               "and a separate URL is not specified");
1223                 }
1224                 return ($url, $path);
1225         }
1226         return ($path, '');
1227 }
1228
1229 sub complete_url_ls_init {
1230         my ($ra, $repo_path, $switch, $pfx) = @_;
1231         unless ($repo_path) {
1232                 print STDERR "W: $switch not specified\n";
1233                 return;
1234         }
1235         $repo_path =~ s#/+$##;
1236         if ($repo_path =~ m#^[a-z\+]+://#) {
1237                 $ra = Git::SVN::Ra->new($repo_path);
1238                 $repo_path = '';
1239         } else {
1240                 $repo_path =~ s#^/+##;
1241                 unless ($ra) {
1242                         fatal("E: '$repo_path' is not a complete URL ",
1243                               "and a separate URL is not specified");
1244                 }
1245         }
1246         my $url = $ra->{url};
1247         my $gs = Git::SVN->init($url, undef, undef, undef, 1);
1248         my $k = "svn-remote.$gs->{repo_id}.url";
1249         my $orig_url = eval { command_oneline(qw/config --get/, $k) };
1250         if ($orig_url && ($orig_url ne $gs->{url})) {
1251                 die "$k already set: $orig_url\n",
1252                     "wanted to set to: $gs->{url}\n";
1253         }
1254         command_oneline('config', $k, $gs->{url}) unless $orig_url;
1255         my $remote_path = "$gs->{path}/$repo_path";
1256         $remote_path =~ s{%([0-9A-F]{2})}{chr hex($1)}ieg;
1257         $remote_path =~ s#/+#/#g;
1258         $remote_path =~ s#^/##g;
1259         $remote_path .= "/*" if $remote_path !~ /\*/;
1260         my ($n) = ($switch =~ /^--(\w+)/);
1261         if (length $pfx && $pfx !~ m#/$#) {
1262                 die "--prefix='$pfx' must have a trailing slash '/'\n";
1263         }
1264         command_noisy('config',
1265                       '--add',
1266                       "svn-remote.$gs->{repo_id}.$n",
1267                       "$remote_path:refs/remotes/$pfx*" .
1268                         ('/*' x (($remote_path =~ tr/*/*/) - 1)) );
1269 }
1270
1271 sub verify_ref {
1272         my ($ref) = @_;
1273         eval { command_oneline([ 'rev-parse', '--verify', $ref ],
1274                                { STDERR => 0 }); };
1275 }
1276
1277 sub get_tree_from_treeish {
1278         my ($treeish) = @_;
1279         # $treeish can be a symbolic ref, too:
1280         my $type = command_oneline(qw/cat-file -t/, $treeish);
1281         my $expected;
1282         while ($type eq 'tag') {
1283                 ($treeish, $type) = command(qw/cat-file tag/, $treeish);
1284         }
1285         if ($type eq 'commit') {
1286                 $expected = (grep /^tree /, command(qw/cat-file commit/,
1287                                                     $treeish))[0];
1288                 ($expected) = ($expected =~ /^tree ($sha1)$/o);
1289                 die "Unable to get tree from $treeish\n" unless $expected;
1290         } elsif ($type eq 'tree') {
1291                 $expected = $treeish;
1292         } else {
1293                 die "$treeish is a $type, expected tree, tag or commit\n";
1294         }
1295         return $expected;
1296 }
1297
1298 sub get_commit_entry {
1299         my ($treeish) = shift;
1300         my %log_entry = ( log => '', tree => get_tree_from_treeish($treeish) );
1301         my $commit_editmsg = "$ENV{GIT_DIR}/COMMIT_EDITMSG";
1302         my $commit_msg = "$ENV{GIT_DIR}/COMMIT_MSG";
1303         open my $log_fh, '>', $commit_editmsg or croak $!;
1304
1305         my $type = command_oneline(qw/cat-file -t/, $treeish);
1306         if ($type eq 'commit' || $type eq 'tag') {
1307                 my ($msg_fh, $ctx) = command_output_pipe('cat-file',
1308                                                          $type, $treeish);
1309                 my $in_msg = 0;
1310                 my $author;
1311                 my $saw_from = 0;
1312                 my $msgbuf = "";
1313                 while (<$msg_fh>) {
1314                         if (!$in_msg) {
1315                                 $in_msg = 1 if (/^\s*$/);
1316                                 $author = $1 if (/^author (.*>)/);
1317                         } elsif (/^git-svn-id: /) {
1318                                 # skip this for now, we regenerate the
1319                                 # correct one on re-fetch anyways
1320                                 # TODO: set *:merge properties or like...
1321                         } else {
1322                                 if (/^From:/ || /^Signed-off-by:/) {
1323                                         $saw_from = 1;
1324                                 }
1325                                 $msgbuf .= $_;
1326                         }
1327                 }
1328                 $msgbuf =~ s/\s+$//s;
1329                 if ($Git::SVN::_add_author_from && defined($author)
1330                     && !$saw_from) {
1331                         $msgbuf .= "\n\nFrom: $author";
1332                 }
1333                 print $log_fh $msgbuf or croak $!;
1334                 command_close_pipe($msg_fh, $ctx);
1335         }
1336         close $log_fh or croak $!;
1337
1338         if ($_edit || ($type eq 'tree')) {
1339                 chomp(my $editor = command_oneline(qw(var GIT_EDITOR)));
1340                 system('sh', '-c', $editor.' "$@"', $editor, $commit_editmsg);
1341         }
1342         rename $commit_editmsg, $commit_msg or croak $!;
1343         {
1344                 require Encode;
1345                 # SVN requires messages to be UTF-8 when entering the repo
1346                 local $/;
1347                 open $log_fh, '<', $commit_msg or croak $!;
1348                 binmode $log_fh;
1349                 chomp($log_entry{log} = <$log_fh>);
1350
1351                 my $enc = Git::config('i18n.commitencoding') || 'UTF-8';
1352                 my $msg = $log_entry{log};
1353
1354                 eval { $msg = Encode::decode($enc, $msg, 1) };
1355                 if ($@) {
1356                         die "Could not decode as $enc:\n", $msg,
1357                             "\nPerhaps you need to set i18n.commitencoding\n";
1358                 }
1359
1360                 eval { $msg = Encode::encode('UTF-8', $msg, 1) };
1361                 die "Could not encode as UTF-8:\n$msg\n" if $@;
1362
1363                 $log_entry{log} = $msg;
1364
1365                 close $log_fh or croak $!;
1366         }
1367         unlink $commit_msg;
1368         \%log_entry;
1369 }
1370
1371 sub s_to_file {
1372         my ($str, $file, $mode) = @_;
1373         open my $fd,'>',$file or croak $!;
1374         print $fd $str,"\n" or croak $!;
1375         close $fd or croak $!;
1376         chmod ($mode &~ umask, $file) if (defined $mode);
1377 }
1378
1379 sub file_to_s {
1380         my $file = shift;
1381         open my $fd,'<',$file or croak "$!: file: $file\n";
1382         local $/;
1383         my $ret = <$fd>;
1384         close $fd or croak $!;
1385         $ret =~ s/\s*$//s;
1386         return $ret;
1387 }
1388
1389 # '<svn username> = real-name <email address>' mapping based on git-svnimport:
1390 sub load_authors {
1391         open my $authors, '<', $_authors or die "Can't open $_authors $!\n";
1392         my $log = $cmd eq 'log';
1393         while (<$authors>) {
1394                 chomp;
1395                 next unless /^(.+?|\(no author\))\s*=\s*(.+?)\s*<(.+)>\s*$/;
1396                 my ($user, $name, $email) = ($1, $2, $3);
1397                 if ($log) {
1398                         $Git::SVN::Log::rusers{"$name <$email>"} = $user;
1399                 } else {
1400                         $users{$user} = [$name, $email];
1401                 }
1402         }
1403         close $authors or croak $!;
1404 }
1405
1406 # convert GetOpt::Long specs for use by git-config
1407 sub read_git_config {
1408         my $opts = shift;
1409         my @config_only;
1410         foreach my $o (keys %$opts) {
1411                 # if we have mixedCase and a long option-only, then
1412                 # it's a config-only variable that we don't need for
1413                 # the command-line.
1414                 push @config_only, $o if ($o =~ /[A-Z]/ && $o =~ /^[a-z]+$/i);
1415                 my $v = $opts->{$o};
1416                 my ($key) = ($o =~ /^([a-zA-Z\-]+)/);
1417                 $key =~ s/-//g;
1418                 my $arg = 'git config';
1419                 $arg .= ' --int' if ($o =~ /[:=]i$/);
1420                 $arg .= ' --bool' if ($o !~ /[:=][sfi]$/);
1421                 if (ref $v eq 'ARRAY') {
1422                         chomp(my @tmp = `$arg --get-all svn.$key`);
1423                         @$v = @tmp if @tmp;
1424                 } else {
1425                         chomp(my $tmp = `$arg --get svn.$key`);
1426                         if ($tmp && !($arg =~ / --bool/ && $tmp eq 'false')) {
1427                                 $$v = $tmp;
1428                         }
1429                 }
1430         }
1431         delete @$opts{@config_only} if @config_only;
1432 }
1433
1434 sub extract_metadata {
1435         my $id = shift or return (undef, undef, undef);
1436         my ($url, $rev, $uuid) = ($id =~ /^\s*git-svn-id:\s+(.*)\@(\d+)
1437                                                         \s([a-f\d\-]+)$/ix);
1438         if (!defined $rev || !$uuid || !$url) {
1439                 # some of the original repositories I made had
1440                 # identifiers like this:
1441                 ($rev, $uuid) = ($id =~/^\s*git-svn-id:\s(\d+)\@([a-f\d\-]+)/i);
1442         }
1443         return ($url, $rev, $uuid);
1444 }
1445
1446 sub cmt_metadata {
1447         return extract_metadata((grep(/^git-svn-id: /,
1448                 command(qw/cat-file commit/, shift)))[-1]);
1449 }
1450
1451 sub cmt_sha2rev_batch {
1452         my %s2r;
1453         my ($pid, $in, $out, $ctx) = command_bidi_pipe(qw/cat-file --batch/);
1454         my $list = shift;
1455
1456         foreach my $sha (@{$list}) {
1457                 my $first = 1;
1458                 my $size = 0;
1459                 print $out $sha, "\n";
1460
1461                 while (my $line = <$in>) {
1462                         if ($first && $line =~ /^[[:xdigit:]]{40}\smissing$/) {
1463                                 last;
1464                         } elsif ($first &&
1465                                $line =~ /^[[:xdigit:]]{40}\scommit\s(\d+)$/) {
1466                                 $first = 0;
1467                                 $size = $1;
1468                                 next;
1469                         } elsif ($line =~ /^(git-svn-id: )/) {
1470                                 my (undef, $rev, undef) =
1471                                                       extract_metadata($line);
1472                                 $s2r{$sha} = $rev;
1473                         }
1474
1475                         $size -= length($line);
1476                         last if ($size == 0);
1477                 }
1478         }
1479
1480         command_close_bidi_pipe($pid, $in, $out, $ctx);
1481
1482         return \%s2r;
1483 }
1484
1485 sub working_head_info {
1486         my ($head, $refs) = @_;
1487         my @args = ('log', '--no-color', '--first-parent', '--pretty=medium');
1488         my ($fh, $ctx) = command_output_pipe(@args, $head);
1489         my $hash;
1490         my %max;
1491         while (<$fh>) {
1492                 if ( m{^commit ($::sha1)$} ) {
1493                         unshift @$refs, $hash if $hash and $refs;
1494                         $hash = $1;
1495                         next;
1496                 }
1497                 next unless s{^\s*(git-svn-id:)}{$1};
1498                 my ($url, $rev, $uuid) = extract_metadata($_);
1499                 if (defined $url && defined $rev) {
1500                         next if $max{$url} and $max{$url} < $rev;
1501                         if (my $gs = Git::SVN->find_by_url($url)) {
1502                                 my $c = $gs->rev_map_get($rev, $uuid);
1503                                 if ($c && $c eq $hash) {
1504                                         close $fh; # break the pipe
1505                                         return ($url, $rev, $uuid, $gs);
1506                                 } else {
1507                                         $max{$url} ||= $gs->rev_map_max;
1508                                 }
1509                         }
1510                 }
1511         }
1512         command_close_pipe($fh, $ctx);
1513         (undef, undef, undef, undef);
1514 }
1515
1516 sub read_commit_parents {
1517         my ($parents, $c) = @_;
1518         chomp(my $p = command_oneline(qw/rev-list --parents -1/, $c));
1519         $p =~ s/^($c)\s*// or die "rev-list --parents -1 $c failed!\n";
1520         @{$parents->{$c}} = split(/ /, $p);
1521 }
1522
1523 sub linearize_history {
1524         my ($gs, $refs) = @_;
1525         my %parents;
1526         foreach my $c (@$refs) {
1527                 read_commit_parents(\%parents, $c);
1528         }
1529
1530         my @linear_refs;
1531         my %skip = ();
1532         my $last_svn_commit = $gs->last_commit;
1533         foreach my $c (reverse @$refs) {
1534                 next if $c eq $last_svn_commit;
1535                 last if $skip{$c};
1536
1537                 unshift @linear_refs, $c;
1538                 $skip{$c} = 1;
1539
1540                 # we only want the first parent to diff against for linear
1541                 # history, we save the rest to inject when we finalize the
1542                 # svn commit
1543                 my $fp_a = verify_ref("$c~1");
1544                 my $fp_b = shift @{$parents{$c}} if $parents{$c};
1545                 if (!$fp_a || !$fp_b) {
1546                         die "Commit $c\n",
1547                             "has no parent commit, and therefore ",
1548                             "nothing to diff against.\n",
1549                             "You should be working from a repository ",
1550                             "originally created by git-svn\n";
1551                 }
1552                 if ($fp_a ne $fp_b) {
1553                         die "$c~1 = $fp_a, however parsing commit $c ",
1554                             "revealed that:\n$c~1 = $fp_b\nBUG!\n";
1555                 }
1556
1557                 foreach my $p (@{$parents{$c}}) {
1558                         $skip{$p} = 1;
1559                 }
1560         }
1561         (\@linear_refs, \%parents);
1562 }
1563
1564 sub find_file_type_and_diff_status {
1565         my ($path) = @_;
1566         return ('dir', '') if $path eq '';
1567
1568         my $diff_output =
1569             command_oneline(qw(diff --cached --name-status --), $path) || "";
1570         my $diff_status = (split(' ', $diff_output))[0] || "";
1571
1572         my $ls_tree = command_oneline(qw(ls-tree HEAD), $path) || "";
1573
1574         return (undef, undef) if !$diff_status && !$ls_tree;
1575
1576         if ($diff_status eq "A") {
1577                 return ("link", $diff_status) if -l $path;
1578                 return ("dir", $diff_status) if -d $path;
1579                 return ("file", $diff_status);
1580         }
1581
1582         my $mode = (split(' ', $ls_tree))[0] || "";
1583
1584         return ("link", $diff_status) if $mode eq "120000";
1585         return ("dir", $diff_status) if $mode eq "040000";
1586         return ("file", $diff_status);
1587 }
1588
1589 sub md5sum {
1590         my $arg = shift;
1591         my $ref = ref $arg;
1592         my $md5 = Digest::MD5->new();
1593         if ($ref eq 'GLOB' || $ref eq 'IO::File' || $ref eq 'File::Temp') {
1594                 $md5->addfile($arg) or croak $!;
1595         } elsif ($ref eq 'SCALAR') {
1596                 $md5->add($$arg) or croak $!;
1597         } elsif (!$ref) {
1598                 $md5->add($arg) or croak $!;
1599         } else {
1600                 ::fatal "Can't provide MD5 hash for unknown ref type: '", $ref, "'";
1601         }
1602         return $md5->hexdigest();
1603 }
1604
1605 sub gc_directory {
1606         if ($can_compress && -f $_ && basename($_) eq "unhandled.log") {
1607                 my $out_filename = $_ . ".gz";
1608                 open my $in_fh, "<", $_ or die "Unable to open $_: $!\n";
1609                 binmode $in_fh;
1610                 my $gz = Compress::Zlib::gzopen($out_filename, "ab") or
1611                                 die "Unable to open $out_filename: $!\n";
1612
1613                 my $res;
1614                 while ($res = sysread($in_fh, my $str, 1024)) {
1615                         $gz->gzwrite($str) or
1616                                 die "Unable to write: ".$gz->gzerror()."!\n";
1617                 }
1618                 unlink $_ or die "unlink $File::Find::name: $!\n";
1619         } elsif (-f $_ && basename($_) eq "index") {
1620                 unlink $_ or die "unlink $_: $!\n";
1621         }
1622 }
1623
1624 package Git::SVN;
1625 use strict;
1626 use warnings;
1627 use Fcntl qw/:DEFAULT :seek/;
1628 use constant rev_map_fmt => 'NH40';
1629 use vars qw/$default_repo_id $default_ref_id $_no_metadata $_follow_parent
1630             $_repack $_repack_flags $_use_svm_props $_head
1631             $_use_svnsync_props $no_reuse_existing $_minimize_url
1632             $_use_log_author $_add_author_from $_localtime/;
1633 use Carp qw/croak/;
1634 use File::Path qw/mkpath/;
1635 use File::Copy qw/copy/;
1636 use IPC::Open3;
1637 use Memoize;  # core since 5.8.0, Jul 2002
1638
1639 my ($_gc_nr, $_gc_period);
1640
1641 # properties that we do not log:
1642 my %SKIP_PROP;
1643 BEGIN {
1644         %SKIP_PROP = map { $_ => 1 } qw/svn:wc:ra_dav:version-url
1645                                         svn:special svn:executable
1646                                         svn:entry:committed-rev
1647                                         svn:entry:last-author
1648                                         svn:entry:uuid
1649                                         svn:entry:committed-date/;
1650
1651         # some options are read globally, but can be overridden locally
1652         # per [svn-remote "..."] section.  Command-line options will *NOT*
1653         # override options set in an [svn-remote "..."] section
1654         no strict 'refs';
1655         for my $option (qw/follow_parent no_metadata use_svm_props
1656                            use_svnsync_props/) {
1657                 my $key = $option;
1658                 $key =~ tr/_//d;
1659                 my $prop = "-$option";
1660                 *$option = sub {
1661                         my ($self) = @_;
1662                         return $self->{$prop} if exists $self->{$prop};
1663                         my $k = "svn-remote.$self->{repo_id}.$key";
1664                         eval { command_oneline(qw/config --get/, $k) };
1665                         if ($@) {
1666                                 $self->{$prop} = ${"Git::SVN::_$option"};
1667                         } else {
1668                                 my $v = command_oneline(qw/config --bool/,$k);
1669                                 $self->{$prop} = $v eq 'false' ? 0 : 1;
1670                         }
1671                         return $self->{$prop};
1672                 }
1673         }
1674 }
1675
1676
1677 my (%LOCKFILES, %INDEX_FILES);
1678 END {
1679         unlink keys %LOCKFILES if %LOCKFILES;
1680         unlink keys %INDEX_FILES if %INDEX_FILES;
1681 }
1682
1683 sub resolve_local_globs {
1684         my ($url, $fetch, $glob_spec) = @_;
1685         return unless defined $glob_spec;
1686         my $ref = $glob_spec->{ref};
1687         my $path = $glob_spec->{path};
1688         foreach (command(qw#for-each-ref --format=%(refname) refs/#)) {
1689                 next unless m#^$ref->{regex}$#;
1690                 my $p = $1;
1691                 my $pathname = desanitize_refname($path->full_path($p));
1692                 my $refname = desanitize_refname($ref->full_path($p));
1693                 if (my $existing = $fetch->{$pathname}) {
1694                         if ($existing ne $refname) {
1695                                 die "Refspec conflict:\n",
1696                                     "existing: $existing\n",
1697                                     " globbed: $refname\n";
1698                         }
1699                         my $u = (::cmt_metadata("$refname"))[0];
1700                         $u =~ s!^\Q$url\E(/|$)!! or die
1701                           "$refname: '$url' not found in '$u'\n";
1702                         if ($pathname ne $u) {
1703                                 warn "W: Refspec glob conflict ",
1704                                      "(ref: $refname):\n",
1705                                      "expected path: $pathname\n",
1706                                      "    real path: $u\n",
1707                                      "Continuing ahead with $u\n";
1708                                 next;
1709                         }
1710                 } else {
1711                         $fetch->{$pathname} = $refname;
1712                 }
1713         }
1714 }
1715
1716 sub parse_revision_argument {
1717         my ($base, $head) = @_;
1718         if (!defined $::_revision || $::_revision eq 'BASE:HEAD') {
1719                 return ($base, $head);
1720         }
1721         return ($1, $2) if ($::_revision =~ /^(\d+):(\d+)$/);
1722         return ($::_revision, $::_revision) if ($::_revision =~ /^\d+$/);
1723         return ($head, $head) if ($::_revision eq 'HEAD');
1724         return ($base, $1) if ($::_revision =~ /^BASE:(\d+)$/);
1725         return ($1, $head) if ($::_revision =~ /^(\d+):HEAD$/);
1726         die "revision argument: $::_revision not understood by git-svn\n";
1727 }
1728
1729 sub fetch_all {
1730         my ($repo_id, $remotes) = @_;
1731         if (ref $repo_id) {
1732                 my $gs = $repo_id;
1733                 $repo_id = undef;
1734                 $repo_id = $gs->{repo_id};
1735         }
1736         $remotes ||= read_all_remotes();
1737         my $remote = $remotes->{$repo_id} or
1738                      die "[svn-remote \"$repo_id\"] unknown\n";
1739         my $fetch = $remote->{fetch};
1740         my $url = $remote->{url} or die "svn-remote.$repo_id.url not defined\n";
1741         my (@gs, @globs);
1742         my $ra = Git::SVN::Ra->new($url);
1743         my $uuid = $ra->get_uuid;
1744         my $head = $ra->get_latest_revnum;
1745
1746         # ignore errors, $head revision may not even exist anymore
1747         eval { $ra->get_log("", $head, 0, 1, 0, 1, sub { $head = $_[1] }) };
1748         warn "W: $@\n" if $@;
1749
1750         my $base = defined $fetch ? $head : 0;
1751
1752         # read the max revs for wildcard expansion (branches/*, tags/*)
1753         foreach my $t (qw/branches tags/) {
1754                 defined $remote->{$t} or next;
1755                 push @globs, @{$remote->{$t}};
1756
1757                 my $max_rev = eval { tmp_config(qw/--int --get/,
1758                                          "svn-remote.$repo_id.${t}-maxRev") };
1759                 if (defined $max_rev && ($max_rev < $base)) {
1760                         $base = $max_rev;
1761                 } elsif (!defined $max_rev) {
1762                         $base = 0;
1763                 }
1764         }
1765
1766         if ($fetch) {
1767                 foreach my $p (sort keys %$fetch) {
1768                         my $gs = Git::SVN->new($fetch->{$p}, $repo_id, $p);
1769                         my $lr = $gs->rev_map_max;
1770                         if (defined $lr) {
1771                                 $base = $lr if ($lr < $base);
1772                         }
1773                         push @gs, $gs;
1774                 }
1775         }
1776
1777         ($base, $head) = parse_revision_argument($base, $head);
1778         $ra->gs_fetch_loop_common($base, $head, \@gs, \@globs);
1779 }
1780
1781 sub read_all_remotes {
1782         my $r = {};
1783         my $use_svm_props = eval { command_oneline(qw/config --bool
1784             svn.useSvmProps/) };
1785         $use_svm_props = $use_svm_props eq 'true' if $use_svm_props;
1786         my $svn_refspec = qr{\s*(.*?)\s*:\s*(.+?)\s*};
1787         foreach (grep { s/^svn-remote\.// } command(qw/config -l/)) {
1788                 if (m!^(.+)\.fetch=$svn_refspec$!) {
1789                         my ($remote, $local_ref, $remote_ref) = ($1, $2, $3);
1790                         die("svn-remote.$remote: remote ref '$remote_ref' "
1791                             . "must start with 'refs/'\n")
1792                                 unless $remote_ref =~ m{^refs/};
1793                         $r->{$remote}->{fetch}->{$local_ref} = $remote_ref;
1794                         $r->{$remote}->{svm} = {} if $use_svm_props;
1795                 } elsif (m!^(.+)\.usesvmprops=\s*(.*)\s*$!) {
1796                         $r->{$1}->{svm} = {};
1797                 } elsif (m!^(.+)\.url=\s*(.*)\s*$!) {
1798                         $r->{$1}->{url} = $2;
1799                 } elsif (m!^(.+)\.(branches|tags)=$svn_refspec$!) {
1800                         my ($remote, $t, $local_ref, $remote_ref) =
1801                                                              ($1, $2, $3, $4);
1802                         die("svn-remote.$remote: remote ref '$remote_ref' ($t) "
1803                             . "must start with 'refs/'\n")
1804                                 unless $remote_ref =~ m{^refs/};
1805                         my $rs = {
1806                             t => $t,
1807                             remote => $remote,
1808                             path => Git::SVN::GlobSpec->new($local_ref),
1809                             ref => Git::SVN::GlobSpec->new($remote_ref) };
1810                         if (length($rs->{ref}->{right}) != 0) {
1811                                 die "The '*' glob character must be the last ",
1812                                     "character of '$remote_ref'\n";
1813                         }
1814                         push @{ $r->{$remote}->{$t} }, $rs;
1815                 }
1816         }
1817
1818         map {
1819                 if (defined $r->{$_}->{svm}) {
1820                         my $svm;
1821                         eval {
1822                                 my $section = "svn-remote.$_";
1823                                 $svm = {
1824                                         source => tmp_config('--get',
1825                                             "$section.svm-source"),
1826                                         replace => tmp_config('--get',
1827                                             "$section.svm-replace"),
1828                                 }
1829                         };
1830                         $r->{$_}->{svm} = $svm;
1831                 }
1832         } keys %$r;
1833
1834         $r;
1835 }
1836
1837 sub init_vars {
1838         $_gc_nr = $_gc_period = 1000;
1839         if (defined $_repack || defined $_repack_flags) {
1840                warn "Repack options are obsolete; they have no effect.\n";
1841         }
1842 }
1843
1844 sub verify_remotes_sanity {
1845         return unless -d $ENV{GIT_DIR};
1846         my %seen;
1847         foreach (command(qw/config -l/)) {
1848                 if (m!^svn-remote\.(?:.+)\.fetch=.*:refs/remotes/(\S+)\s*$!) {
1849                         if ($seen{$1}) {
1850                                 die "Remote ref refs/remote/$1 is tracked by",
1851                                     "\n  \"$_\"\nand\n  \"$seen{$1}\"\n",
1852                                     "Please resolve this ambiguity in ",
1853                                     "your git configuration file before ",
1854                                     "continuing\n";
1855                         }
1856                         $seen{$1} = $_;
1857                 }
1858         }
1859 }
1860
1861 sub find_existing_remote {
1862         my ($url, $remotes) = @_;
1863         return undef if $no_reuse_existing;
1864         my $existing;
1865         foreach my $repo_id (keys %$remotes) {
1866                 my $u = $remotes->{$repo_id}->{url} or next;
1867                 next if $u ne $url;
1868                 $existing = $repo_id;
1869                 last;
1870         }
1871         $existing;
1872 }
1873
1874 sub init_remote_config {
1875         my ($self, $url, $no_write) = @_;
1876         $url =~ s!/+$!!; # strip trailing slash
1877         my $r = read_all_remotes();
1878         my $existing = find_existing_remote($url, $r);
1879         if ($existing) {
1880                 unless ($no_write) {
1881                         print STDERR "Using existing ",
1882                                      "[svn-remote \"$existing\"]\n";
1883                 }
1884                 $self->{repo_id} = $existing;
1885         } elsif ($_minimize_url) {
1886                 my $min_url = Git::SVN::Ra->new($url)->minimize_url;
1887                 $existing = find_existing_remote($min_url, $r);
1888                 if ($existing) {
1889                         unless ($no_write) {
1890                                 print STDERR "Using existing ",
1891                                              "[svn-remote \"$existing\"]\n";
1892                         }
1893                         $self->{repo_id} = $existing;
1894                 }
1895                 if ($min_url ne $url) {
1896                         unless ($no_write) {
1897                                 print STDERR "Using higher level of URL: ",
1898                                              "$url => $min_url\n";
1899                         }
1900                         my $old_path = $self->{path};
1901                         $self->{path} = $url;
1902                         $self->{path} =~ s!^\Q$min_url\E(/|$)!!;
1903                         if (length $old_path) {
1904                                 $self->{path} .= "/$old_path";
1905                         }
1906                         $url = $min_url;
1907                 }
1908         }
1909         my $orig_url;
1910         if (!$existing) {
1911                 # verify that we aren't overwriting anything:
1912                 $orig_url = eval {
1913                         command_oneline('config', '--get',
1914                                         "svn-remote.$self->{repo_id}.url")
1915                 };
1916                 if ($orig_url && ($orig_url ne $url)) {
1917                         die "svn-remote.$self->{repo_id}.url already set: ",
1918                             "$orig_url\nwanted to set to: $url\n";
1919                 }
1920         }
1921         my ($xrepo_id, $xpath) = find_ref($self->refname);
1922         if (!$no_write && defined $xpath) {
1923                 die "svn-remote.$xrepo_id.fetch already set to track ",
1924                     "$xpath:", $self->refname, "\n";
1925         }
1926         unless ($no_write) {
1927                 command_noisy('config',
1928                               "svn-remote.$self->{repo_id}.url", $url);
1929                 $self->{path} =~ s{^/}{};
1930                 $self->{path} =~ s{%([0-9A-F]{2})}{chr hex($1)}ieg;
1931                 command_noisy('config', '--add',
1932                               "svn-remote.$self->{repo_id}.fetch",
1933                               "$self->{path}:".$self->refname);
1934         }
1935         $self->{url} = $url;
1936 }
1937
1938 sub find_by_url { # repos_root and, path are optional
1939         my ($class, $full_url, $repos_root, $path) = @_;
1940
1941         return undef unless defined $full_url;
1942         remove_username($full_url);
1943         remove_username($repos_root) if defined $repos_root;
1944         my $remotes = read_all_remotes();
1945         if (defined $full_url && defined $repos_root && !defined $path) {
1946                 $path = $full_url;
1947                 $path =~ s#^\Q$repos_root\E(?:/|$)##;
1948         }
1949         foreach my $repo_id (keys %$remotes) {
1950                 my $u = $remotes->{$repo_id}->{url} or next;
1951                 remove_username($u);
1952                 next if defined $repos_root && $repos_root ne $u;
1953
1954                 my $fetch = $remotes->{$repo_id}->{fetch} || {};
1955                 foreach my $t (qw/branches tags/) {
1956                         foreach my $globspec (@{$remotes->{$repo_id}->{$t}}) {
1957                                 resolve_local_globs($u, $fetch, $globspec);
1958                         }
1959                 }
1960                 my $p = $path;
1961                 my $rwr = rewrite_root({repo_id => $repo_id});
1962                 my $svm = $remotes->{$repo_id}->{svm}
1963                         if defined $remotes->{$repo_id}->{svm};
1964                 unless (defined $p) {
1965                         $p = $full_url;
1966                         my $z = $u;
1967                         my $prefix = '';
1968                         if ($rwr) {
1969                                 $z = $rwr;
1970                                 remove_username($z);
1971                         } elsif (defined $svm) {
1972                                 $z = $svm->{source};
1973                                 $prefix = $svm->{replace};
1974                                 $prefix =~ s#^\Q$u\E(?:/|$)##;
1975                                 $prefix =~ s#/$##;
1976                         }
1977                         $p =~ s#^\Q$z\E(?:/|$)#$prefix# or next;
1978                 }
1979                 foreach my $f (keys %$fetch) {
1980                         next if $f ne $p;
1981                         return Git::SVN->new($fetch->{$f}, $repo_id, $f);
1982                 }
1983         }
1984         undef;
1985 }
1986
1987 sub init {
1988         my ($class, $url, $path, $repo_id, $ref_id, $no_write) = @_;
1989         my $self = _new($class, $repo_id, $ref_id, $path);
1990         if (defined $url) {
1991                 $self->init_remote_config($url, $no_write);
1992         }
1993         $self;
1994 }
1995
1996 sub find_ref {
1997         my ($ref_id) = @_;
1998         foreach (command(qw/config -l/)) {
1999                 next unless m!^svn-remote\.(.+)\.fetch=
2000                               \s*(.*?)\s*:\s*(.+?)\s*$!x;
2001                 my ($repo_id, $path, $ref) = ($1, $2, $3);
2002                 if ($ref eq $ref_id) {
2003                         $path = '' if ($path =~ m#^\./?#);
2004                         return ($repo_id, $path);
2005                 }
2006         }
2007         (undef, undef, undef);
2008 }
2009
2010 sub new {
2011         my ($class, $ref_id, $repo_id, $path) = @_;
2012         if (defined $ref_id && !defined $repo_id && !defined $path) {
2013                 ($repo_id, $path) = find_ref($ref_id);
2014                 if (!defined $repo_id) {
2015                         die "Could not find a \"svn-remote.*.fetch\" key ",
2016                             "in the repository configuration matching: ",
2017                             "$ref_id\n";
2018                 }
2019         }
2020         my $self = _new($class, $repo_id, $ref_id, $path);
2021         if (!defined $self->{path} || !length $self->{path}) {
2022                 my $fetch = command_oneline('config', '--get',
2023                                             "svn-remote.$repo_id.fetch",
2024                                             ":$ref_id\$") or
2025                      die "Failed to read \"svn-remote.$repo_id.fetch\" ",
2026                          "\":$ref_id\$\" in config\n";
2027                 ($self->{path}, undef) = split(/\s*:\s*/, $fetch);
2028         }
2029         $self->{url} = command_oneline('config', '--get',
2030                                        "svn-remote.$repo_id.url") or
2031                   die "Failed to read \"svn-remote.$repo_id.url\" in config\n";
2032         $self->rebuild;
2033         $self;
2034 }
2035
2036 sub refname {
2037         my ($refname) = $_[0]->{ref_id} ;
2038
2039         # It cannot end with a slash /, we'll throw up on this because
2040         # SVN can't have directories with a slash in their name, either:
2041         if ($refname =~ m{/$}) {
2042                 die "ref: '$refname' ends with a trailing slash, this is ",
2043                     "not permitted by git nor Subversion\n";
2044         }
2045
2046         # It cannot have ASCII control character space, tilde ~, caret ^,
2047         # colon :, question-mark ?, asterisk *, space, or open bracket [
2048         # anywhere.
2049         #
2050         # Additionally, % must be escaped because it is used for escaping
2051         # and we want our escaped refname to be reversible
2052         $refname =~ s{([ \%~\^:\?\*\[\t])}{uc sprintf('%%%02x',ord($1))}eg;
2053
2054         # no slash-separated component can begin with a dot .
2055         # /.* becomes /%2E*
2056         $refname =~ s{/\.}{/%2E}g;
2057
2058         # It cannot have two consecutive dots .. anywhere
2059         # .. becomes %2E%2E
2060         $refname =~ s{\.\.}{%2E%2E}g;
2061
2062         return $refname;
2063 }
2064
2065 sub desanitize_refname {
2066         my ($refname) = @_;
2067         $refname =~ s{%(?:([0-9A-F]{2}))}{chr hex($1)}eg;
2068         return $refname;
2069 }
2070
2071 sub svm_uuid {
2072         my ($self) = @_;
2073         return $self->{svm}->{uuid} if $self->svm;
2074         $self->ra;
2075         unless ($self->{svm}) {
2076                 die "SVM UUID not cached, and reading remotely failed\n";
2077         }
2078         $self->{svm}->{uuid};
2079 }
2080
2081 sub svm {
2082         my ($self) = @_;
2083         return $self->{svm} if $self->{svm};
2084         my $svm;
2085         # see if we have it in our config, first:
2086         eval {
2087                 my $section = "svn-remote.$self->{repo_id}";
2088                 $svm = {
2089                   source => tmp_config('--get', "$section.svm-source"),
2090                   uuid => tmp_config('--get', "$section.svm-uuid"),
2091                   replace => tmp_config('--get', "$section.svm-replace"),
2092                 }
2093         };
2094         if ($svm && $svm->{source} && $svm->{uuid} && $svm->{replace}) {
2095                 $self->{svm} = $svm;
2096         }
2097         $self->{svm};
2098 }
2099
2100 sub _set_svm_vars {
2101         my ($self, $ra) = @_;
2102         return $ra if $self->svm;
2103
2104         my @err = ( "useSvmProps set, but failed to read SVM properties\n",
2105                     "(svm:source, svm:uuid) ",
2106                     "from the following URLs:\n" );
2107         sub read_svm_props {
2108                 my ($self, $ra, $path, $r) = @_;
2109                 my $props = ($ra->get_dir($path, $r))[2];
2110                 my $src = $props->{'svm:source'};
2111                 my $uuid = $props->{'svm:uuid'};
2112                 return undef if (!$src || !$uuid);
2113
2114                 chomp($src, $uuid);
2115
2116                 $uuid =~ m{^[0-9a-f\-]{30,}$}i
2117                     or die "doesn't look right - svm:uuid is '$uuid'\n";
2118
2119                 # the '!' is used to mark the repos_root!/relative/path
2120                 $src =~ s{/?!/?}{/};
2121                 $src =~ s{/+$}{}; # no trailing slashes please
2122                 # username is of no interest
2123                 $src =~ s{(^[a-z\+]*://)[^/@]*@}{$1};
2124
2125                 my $replace = $ra->{url};
2126                 $replace .= "/$path" if length $path;
2127
2128                 my $section = "svn-remote.$self->{repo_id}";
2129                 tmp_config("$section.svm-source", $src);
2130                 tmp_config("$section.svm-replace", $replace);
2131                 tmp_config("$section.svm-uuid", $uuid);
2132                 $self->{svm} = {
2133                         source => $src,
2134                         uuid => $uuid,
2135                         replace => $replace
2136                 };
2137         }
2138
2139         my $r = $ra->get_latest_revnum;
2140         my $path = $self->{path};
2141         my %tried;
2142         while (length $path) {
2143                 unless ($tried{"$self->{url}/$path"}) {
2144                         return $ra if $self->read_svm_props($ra, $path, $r);
2145                         $tried{"$self->{url}/$path"} = 1;
2146                 }
2147                 $path =~ s#/?[^/]+$##;
2148         }
2149         die "Path: '$path' should be ''\n" if $path ne '';
2150         return $ra if $self->read_svm_props($ra, $path, $r);
2151         $tried{"$self->{url}/$path"} = 1;
2152
2153         if ($ra->{repos_root} eq $self->{url}) {
2154                 die @err, (map { "  $_\n" } keys %tried), "\n";
2155         }
2156
2157         # nope, make sure we're connected to the repository root:
2158         my $ok;
2159         my @tried_b;
2160         $path = $ra->{svn_path};
2161         $ra = Git::SVN::Ra->new($ra->{repos_root});
2162         while (length $path) {
2163                 unless ($tried{"$ra->{url}/$path"}) {
2164                         $ok = $self->read_svm_props($ra, $path, $r);
2165                         last if $ok;
2166                         $tried{"$ra->{url}/$path"} = 1;
2167                 }
2168                 $path =~ s#/?[^/]+$##;
2169         }
2170         die "Path: '$path' should be ''\n" if $path ne '';
2171         $ok ||= $self->read_svm_props($ra, $path, $r);
2172         $tried{"$ra->{url}/$path"} = 1;
2173         if (!$ok) {
2174                 die @err, (map { "  $_\n" } keys %tried), "\n";
2175         }
2176         Git::SVN::Ra->new($self->{url});
2177 }
2178
2179 sub svnsync {
2180         my ($self) = @_;
2181         return $self->{svnsync} if $self->{svnsync};
2182
2183         if ($self->no_metadata) {
2184                 die "Can't have both 'noMetadata' and ",
2185                     "'useSvnsyncProps' options set!\n";
2186         }
2187         if ($self->rewrite_root) {
2188                 die "Can't have both 'useSvnsyncProps' and 'rewriteRoot' ",
2189                     "options set!\n";
2190         }
2191
2192         my $svnsync;
2193         # see if we have it in our config, first:
2194         eval {
2195                 my $section = "svn-remote.$self->{repo_id}";
2196
2197                 my $url = tmp_config('--get', "$section.svnsync-url");
2198                 ($url) = ($url =~ m{^([a-z\+]+://\S+)$}) or
2199                    die "doesn't look right - svn:sync-from-url is '$url'\n";
2200
2201                 my $uuid = tmp_config('--get', "$section.svnsync-uuid");
2202                 ($uuid) = ($uuid =~ m{^([0-9a-f\-]{30,})$}i) or
2203                    die "doesn't look right - svn:sync-from-uuid is '$uuid'\n";
2204
2205                 $svnsync = { url => $url, uuid => $uuid }
2206         };
2207         if ($svnsync && $svnsync->{url} && $svnsync->{uuid}) {
2208                 return $self->{svnsync} = $svnsync;
2209         }
2210
2211         my $err = "useSvnsyncProps set, but failed to read " .
2212                   "svnsync property: svn:sync-from-";
2213         my $rp = $self->ra->rev_proplist(0);
2214
2215         my $url = $rp->{'svn:sync-from-url'} or die $err . "url\n";
2216         ($url) = ($url =~ m{^([a-z\+]+://\S+)$}) or
2217                    die "doesn't look right - svn:sync-from-url is '$url'\n";
2218
2219         my $uuid = $rp->{'svn:sync-from-uuid'} or die $err . "uuid\n";
2220         ($uuid) = ($uuid =~ m{^([0-9a-f\-]{30,})$}i) or
2221                    die "doesn't look right - svn:sync-from-uuid is '$uuid'\n";
2222
2223         my $section = "svn-remote.$self->{repo_id}";
2224         tmp_config('--add', "$section.svnsync-uuid", $uuid);
2225         tmp_config('--add', "$section.svnsync-url", $url);
2226         return $self->{svnsync} = { url => $url, uuid => $uuid };
2227 }
2228
2229 # this allows us to memoize our SVN::Ra UUID locally and avoid a
2230 # remote lookup (useful for 'git svn log').
2231 sub ra_uuid {
2232         my ($self) = @_;
2233         unless ($self->{ra_uuid}) {
2234                 my $key = "svn-remote.$self->{repo_id}.uuid";
2235                 my $uuid = eval { tmp_config('--get', $key) };
2236                 if (!$@ && $uuid && $uuid =~ /^([a-f\d\-]{30,})$/i) {
2237                         $self->{ra_uuid} = $uuid;
2238                 } else {
2239                         die "ra_uuid called without URL\n" unless $self->{url};
2240                         $self->{ra_uuid} = $self->ra->get_uuid;
2241                         tmp_config('--add', $key, $self->{ra_uuid});
2242                 }
2243         }
2244         $self->{ra_uuid};
2245 }
2246
2247 sub _set_repos_root {
2248         my ($self, $repos_root) = @_;
2249         my $k = "svn-remote.$self->{repo_id}.reposRoot";
2250         $repos_root ||= $self->ra->{repos_root};
2251         tmp_config($k, $repos_root);
2252         $repos_root;
2253 }
2254
2255 sub repos_root {
2256         my ($self) = @_;
2257         my $k = "svn-remote.$self->{repo_id}.reposRoot";
2258         eval { tmp_config('--get', $k) } || $self->_set_repos_root;
2259 }
2260
2261 sub ra {
2262         my ($self) = shift;
2263         my $ra = Git::SVN::Ra->new($self->{url});
2264         $self->_set_repos_root($ra->{repos_root});
2265         if ($self->use_svm_props && !$self->{svm}) {
2266                 if ($self->no_metadata) {
2267                         die "Can't have both 'noMetadata' and ",
2268                             "'useSvmProps' options set!\n";
2269                 } elsif ($self->use_svnsync_props) {
2270                         die "Can't have both 'useSvnsyncProps' and ",
2271                             "'useSvmProps' options set!\n";
2272                 }
2273                 $ra = $self->_set_svm_vars($ra);
2274                 $self->{-want_revprops} = 1;
2275         }
2276         $ra;
2277 }
2278
2279 # prop_walk(PATH, REV, SUB)
2280 # -------------------------
2281 # Recursively traverse PATH at revision REV and invoke SUB for each
2282 # directory that contains a SVN property.  SUB will be invoked as
2283 # follows:  &SUB(gs, path, props);  where `gs' is this instance of
2284 # Git::SVN, `path' the path to the directory where the properties
2285 # `props' were found.  The `path' will be relative to point of checkout,
2286 # that is, if url://repo/trunk is the current Git branch, and that
2287 # directory contains a sub-directory `d', SUB will be invoked with `/d/'
2288 # as `path' (note the trailing `/').
2289 sub prop_walk {
2290         my ($self, $path, $rev, $sub) = @_;
2291
2292         $path =~ s#^/##;
2293         my ($dirent, undef, $props) = $self->ra->get_dir($path, $rev);
2294         $path =~ s#^/*#/#g;
2295         my $p = $path;
2296         # Strip the irrelevant part of the path.
2297         $p =~ s#^/+\Q$self->{path}\E(/|$)#/#;
2298         # Ensure the path is terminated by a `/'.
2299         $p =~ s#/*$#/#;
2300
2301         # The properties contain all the internal SVN stuff nobody
2302         # (usually) cares about.
2303         my $interesting_props = 0;
2304         foreach (keys %{$props}) {
2305                 # If it doesn't start with `svn:', it must be a
2306                 # user-defined property.
2307                 ++$interesting_props and next if $_ !~ /^svn:/;
2308                 # FIXME: Fragile, if SVN adds new public properties,
2309                 # this needs to be updated.
2310                 ++$interesting_props if /^svn:(?:ignore|keywords|executable
2311                                                  |eol-style|mime-type
2312                                                  |externals|needs-lock)$/x;
2313         }
2314         &$sub($self, $p, $props) if $interesting_props;
2315
2316         foreach (sort keys %$dirent) {
2317                 next if $dirent->{$_}->{kind} != $SVN::Node::dir;
2318                 $self->prop_walk($self->{path} . $p . $_, $rev, $sub);
2319         }
2320 }
2321
2322 sub last_rev { ($_[0]->last_rev_commit)[0] }
2323 sub last_commit { ($_[0]->last_rev_commit)[1] }
2324
2325 # returns the newest SVN revision number and newest commit SHA1
2326 sub last_rev_commit {
2327         my ($self) = @_;
2328         if (defined $self->{last_rev} && defined $self->{last_commit}) {
2329                 return ($self->{last_rev}, $self->{last_commit});
2330         }
2331         my $c = ::verify_ref($self->refname.'^0');
2332         if ($c && !$self->use_svm_props && !$self->no_metadata) {
2333                 my $rev = (::cmt_metadata($c))[1];
2334                 if (defined $rev) {
2335                         ($self->{last_rev}, $self->{last_commit}) = ($rev, $c);
2336                         return ($rev, $c);
2337                 }
2338         }
2339         my $map_path = $self->map_path;
2340         unless (-e $map_path) {
2341                 ($self->{last_rev}, $self->{last_commit}) = (undef, undef);
2342                 return (undef, undef);
2343         }
2344         my ($rev, $commit) = $self->rev_map_max(1);
2345         ($self->{last_rev}, $self->{last_commit}) = ($rev, $commit);
2346         return ($rev, $commit);
2347 }
2348
2349 sub get_fetch_range {
2350         my ($self, $min, $max) = @_;
2351         $max ||= $self->ra->get_latest_revnum;
2352         $min ||= $self->rev_map_max;
2353         (++$min, $max);
2354 }
2355
2356 sub tmp_config {
2357         my (@args) = @_;
2358         my $old_def_config = "$ENV{GIT_DIR}/svn/config";
2359         my $config = "$ENV{GIT_DIR}/svn/.metadata";
2360         if (! -f $config && -f $old_def_config) {
2361                 rename $old_def_config, $config or
2362                        die "Failed rename $old_def_config => $config: $!\n";
2363         }
2364         my $old_config = $ENV{GIT_CONFIG};
2365         $ENV{GIT_CONFIG} = $config;
2366         $@ = undef;
2367         my @ret = eval {
2368                 unless (-f $config) {
2369                         mkfile($config);
2370                         open my $fh, '>', $config or
2371                             die "Can't open $config: $!\n";
2372                         print $fh "; This file is used internally by ",
2373                                   "git-svn\n" or die
2374                                   "Couldn't write to $config: $!\n";
2375                         print $fh "; You should not have to edit it\n" or
2376                               die "Couldn't write to $config: $!\n";
2377                         close $fh or die "Couldn't close $config: $!\n";
2378                 }
2379                 command('config', @args);
2380         };
2381         my $err = $@;
2382         if (defined $old_config) {
2383                 $ENV{GIT_CONFIG} = $old_config;
2384         } else {
2385                 delete $ENV{GIT_CONFIG};
2386         }
2387         die $err if $err;
2388         wantarray ? @ret : $ret[0];
2389 }
2390
2391 sub tmp_index_do {
2392         my ($self, $sub) = @_;
2393         my $old_index = $ENV{GIT_INDEX_FILE};
2394         $ENV{GIT_INDEX_FILE} = $self->{index};
2395         $@ = undef;
2396         my @ret = eval {
2397                 my ($dir, $base) = ($self->{index} =~ m#^(.*?)/?([^/]+)$#);
2398                 mkpath([$dir]) unless -d $dir;
2399                 &$sub;
2400         };
2401         my $err = $@;
2402         if (defined $old_index) {
2403                 $ENV{GIT_INDEX_FILE} = $old_index;
2404         } else {
2405                 delete $ENV{GIT_INDEX_FILE};
2406         }
2407         die $err if $err;
2408         wantarray ? @ret : $ret[0];
2409 }
2410
2411 sub assert_index_clean {
2412         my ($self, $treeish) = @_;
2413
2414         $self->tmp_index_do(sub {
2415                 command_noisy('read-tree', $treeish) unless -e $self->{index};
2416                 my $x = command_oneline('write-tree');
2417                 my ($y) = (command(qw/cat-file commit/, $treeish) =~
2418                            /^tree ($::sha1)/mo);
2419                 return if $y eq $x;
2420
2421                 warn "Index mismatch: $y != $x\nrereading $treeish\n";
2422                 unlink $self->{index} or die "unlink $self->{index}: $!\n";
2423                 command_noisy('read-tree', $treeish);
2424                 $x = command_oneline('write-tree');
2425                 if ($y ne $x) {
2426                         ::fatal "trees ($treeish) $y != $x\n",
2427                                 "Something is seriously wrong...";
2428                 }
2429         });
2430 }
2431
2432 sub get_commit_parents {
2433         my ($self, $log_entry) = @_;
2434         my (%seen, @ret, @tmp);
2435         # legacy support for 'set-tree'; this is only used by set_tree_cb:
2436         if (my $ip = $self->{inject_parents}) {
2437                 if (my $commit = delete $ip->{$log_entry->{revision}}) {
2438                         push @tmp, $commit;
2439                 }
2440         }
2441         if (my $cur = ::verify_ref($self->refname.'^0')) {
2442                 push @tmp, $cur;
2443         }
2444         if (my $ipd = $self->{inject_parents_dcommit}) {
2445                 if (my $commit = delete $ipd->{$log_entry->{revision}}) {
2446                         push @tmp, @$commit;
2447                 }
2448         }
2449         push @tmp, $_ foreach (@{$log_entry->{parents}}, @tmp);
2450         while (my $p = shift @tmp) {
2451                 next if $seen{$p};
2452                 $seen{$p} = 1;
2453                 push @ret, $p;
2454                 # MAXPARENT is defined to 16 in commit-tree.c:
2455                 last if @ret >= 16;
2456         }
2457         if (@tmp) {
2458                 die "r$log_entry->{revision}: No room for parents:\n\t",
2459                     join("\n\t", @tmp), "\n";
2460         }
2461         @ret;
2462 }
2463
2464 sub rewrite_root {
2465         my ($self) = @_;
2466         return $self->{-rewrite_root} if exists $self->{-rewrite_root};
2467         my $k = "svn-remote.$self->{repo_id}.rewriteRoot";
2468         my $rwr = eval { command_oneline(qw/config --get/, $k) };
2469         if ($rwr) {
2470                 $rwr =~ s#/+$##;
2471                 if ($rwr !~ m#^[a-z\+]+://#) {
2472                         die "$rwr is not a valid URL (key: $k)\n";
2473                 }
2474         }
2475         $self->{-rewrite_root} = $rwr;
2476 }
2477
2478 sub metadata_url {
2479         my ($self) = @_;
2480         ($self->rewrite_root || $self->{url}) .
2481            (length $self->{path} ? '/' . $self->{path} : '');
2482 }
2483
2484 sub full_url {
2485         my ($self) = @_;
2486         $self->{url} . (length $self->{path} ? '/' . $self->{path} : '');
2487 }
2488
2489
2490 sub set_commit_header_env {
2491         my ($log_entry) = @_;
2492         my %env;
2493         foreach my $ned (qw/NAME EMAIL DATE/) {
2494                 foreach my $ac (qw/AUTHOR COMMITTER/) {
2495                         $env{"GIT_${ac}_${ned}"} = $ENV{"GIT_${ac}_${ned}"};
2496                 }
2497         }
2498
2499         $ENV{GIT_AUTHOR_NAME} = $log_entry->{name};
2500         $ENV{GIT_AUTHOR_EMAIL} = $log_entry->{email};
2501         $ENV{GIT_AUTHOR_DATE} = $ENV{GIT_COMMITTER_DATE} = $log_entry->{date};
2502
2503         $ENV{GIT_COMMITTER_NAME} = (defined $log_entry->{commit_name})
2504                                                 ? $log_entry->{commit_name}
2505                                                 : $log_entry->{name};
2506         $ENV{GIT_COMMITTER_EMAIL} = (defined $log_entry->{commit_email})
2507                                                 ? $log_entry->{commit_email}
2508                                                 : $log_entry->{email};
2509         \%env;
2510 }
2511
2512 sub restore_commit_header_env {
2513         my ($env) = @_;
2514         foreach my $ned (qw/NAME EMAIL DATE/) {
2515                 foreach my $ac (qw/AUTHOR COMMITTER/) {
2516                         my $k = "GIT_${ac}_${ned}";
2517                         if (defined $env->{$k}) {
2518                                 $ENV{$k} = $env->{$k};
2519                         } else {
2520                                 delete $ENV{$k};
2521                         }
2522                 }
2523         }
2524 }
2525
2526 sub gc {
2527         command_noisy('gc', '--auto');
2528 };
2529
2530 sub do_git_commit {
2531         my ($self, $log_entry) = @_;
2532         my $lr = $self->last_rev;
2533         if (defined $lr && $lr >= $log_entry->{revision}) {
2534                 die "Last fetched revision of ", $self->refname,
2535                     " was r$lr, but we are about to fetch: ",
2536                     "r$log_entry->{revision}!\n";
2537         }
2538         if (my $c = $self->rev_map_get($log_entry->{revision})) {
2539                 croak "$log_entry->{revision} = $c already exists! ",
2540                       "Why are we refetching it?\n";
2541         }
2542         my $old_env = set_commit_header_env($log_entry);
2543         my $tree = $log_entry->{tree};
2544         if (!defined $tree) {
2545                 $tree = $self->tmp_index_do(sub {
2546                                             command_oneline('write-tree') });
2547         }
2548         die "Tree is not a valid sha1: $tree\n" if $tree !~ /^$::sha1$/o;
2549
2550         my @exec = ('git', 'commit-tree', $tree);
2551         foreach ($self->get_commit_parents($log_entry)) {
2552                 push @exec, '-p', $_;
2553         }
2554         defined(my $pid = open3(my $msg_fh, my $out_fh, '>&STDERR', @exec))
2555                                                                    or croak $!;
2556         binmode $msg_fh;
2557
2558         # we always get UTF-8 from SVN, but we may want our commits in
2559         # a different encoding.
2560         if (my $enc = Git::config('i18n.commitencoding')) {
2561                 require Encode;
2562                 Encode::from_to($log_entry->{log}, 'UTF-8', $enc);
2563         }
2564         print $msg_fh $log_entry->{log} or croak $!;
2565         restore_commit_header_env($old_env);
2566         unless ($self->no_metadata) {
2567                 print $msg_fh "\ngit-svn-id: $log_entry->{metadata}\n"
2568                               or croak $!;
2569         }
2570         $msg_fh->flush == 0 or croak $!;
2571         close $msg_fh or croak $!;
2572         chomp(my $commit = do { local $/; <$out_fh> });
2573         close $out_fh or croak $!;
2574         waitpid $pid, 0;
2575         croak $? if $?;
2576         if ($commit !~ /^$::sha1$/o) {
2577                 die "Failed to commit, invalid sha1: $commit\n";
2578         }
2579
2580         $self->rev_map_set($log_entry->{revision}, $commit, 1);
2581
2582         $self->{last_rev} = $log_entry->{revision};
2583         $self->{last_commit} = $commit;
2584         print "r$log_entry->{revision}" unless $::_q > 1;
2585         if (defined $log_entry->{svm_revision}) {
2586                  print " (\@$log_entry->{svm_revision})" unless $::_q > 1;
2587                  $self->rev_map_set($log_entry->{svm_revision}, $commit,
2588                                    0, $self->svm_uuid);
2589         }
2590         print " = $commit ($self->{ref_id})\n" unless $::_q > 1;
2591         if (--$_gc_nr == 0) {
2592                 $_gc_nr = $_gc_period;
2593                 gc();
2594         }
2595         return $commit;
2596 }
2597
2598 sub match_paths {
2599         my ($self, $paths, $r) = @_;
2600         return 1 if $self->{path} eq '';
2601         if (my $path = $paths->{"/$self->{path}"}) {
2602                 return ($path->{action} eq 'D') ? 0 : 1;
2603         }
2604         $self->{path_regex} ||= qr/^\/\Q$self->{path}\E\//;
2605         if (grep /$self->{path_regex}/, keys %$paths) {
2606                 return 1;
2607         }
2608         my $c = '';
2609         foreach (split m#/#, $self->{path}) {
2610                 $c .= "/$_";
2611                 next unless ($paths->{$c} &&
2612                              ($paths->{$c}->{action} =~ /^[AR]$/));
2613                 if ($self->ra->check_path($self->{path}, $r) ==
2614                     $SVN::Node::dir) {
2615                         return 1;
2616                 }
2617         }
2618         return 0;
2619 }
2620
2621 sub find_parent_branch {
2622         my ($self, $paths, $rev) = @_;
2623         return undef unless $self->follow_parent;
2624         unless (defined $paths) {
2625                 my $err_handler = $SVN::Error::handler;
2626                 $SVN::Error::handler = \&Git::SVN::Ra::skip_unknown_revs;
2627                 $self->ra->get_log([$self->{path}], $rev, $rev, 0, 1, 1,
2628                                    sub { $paths = $_[0] });
2629                 $SVN::Error::handler = $err_handler;
2630         }
2631         return undef unless defined $paths;
2632
2633         # look for a parent from another branch:
2634         my @b_path_components = split m#/#, $self->{path};
2635         my @a_path_components;
2636         my $i;
2637         while (@b_path_components) {
2638                 $i = $paths->{'/'.join('/', @b_path_components)};
2639                 last if $i && defined $i->{copyfrom_path};
2640                 unshift(@a_path_components, pop(@b_path_components));
2641         }
2642         return undef unless defined $i && defined $i->{copyfrom_path};
2643         my $branch_from = $i->{copyfrom_path};
2644         if (@a_path_components) {
2645                 print STDERR "branch_from: $branch_from => ";
2646                 $branch_from .= '/'.join('/', @a_path_components);
2647                 print STDERR $branch_from, "\n";
2648         }
2649         my $r = $i->{copyfrom_rev};
2650         my $repos_root = $self->ra->{repos_root};
2651         my $url = $self->ra->{url};
2652         my $new_url = $url . $branch_from;
2653         print STDERR  "Found possible branch point: ",
2654                       "$new_url => ", $self->full_url, ", $r\n"
2655                       unless $::_q > 1;
2656         $branch_from =~ s#^/##;
2657         my $gs = $self->other_gs($new_url, $url,
2658                                  $branch_from, $r, $self->{ref_id});
2659         my ($r0, $parent) = $gs->find_rev_before($r, 1);
2660         {
2661                 my ($base, $head);
2662                 if (!defined $r0 || !defined $parent) {
2663                         ($base, $head) = parse_revision_argument(0, $r);
2664                 } else {
2665                         if ($r0 < $r) {
2666                                 $gs->ra->get_log([$gs->{path}], $r0 + 1, $r, 1,
2667                                         0, 1, sub { $base = $_[1] - 1 });
2668                         }
2669                 }
2670                 if (defined $base && $base <= $r) {
2671                         $gs->fetch($base, $r);
2672                 }
2673                 ($r0, $parent) = $gs->find_rev_before($r, 1);
2674         }
2675         if (defined $r0 && defined $parent) {
2676                 print STDERR "Found branch parent: ($self->{ref_id}) $parent\n"
2677                              unless $::_q > 1;
2678                 my $ed;
2679                 if ($self->ra->can_do_switch) {
2680                         $self->assert_index_clean($parent);
2681                         print STDERR "Following parent with do_switch\n"
2682                                      unless $::_q > 1;
2683                         # do_switch works with svn/trunk >= r22312, but that
2684                         # is not included with SVN 1.4.3 (the latest version
2685                         # at the moment), so we can't rely on it
2686                         $self->{last_rev} = $r0;
2687                         $self->{last_commit} = $parent;
2688                         $ed = SVN::Git::Fetcher->new($self, $gs->{path});
2689                         $gs->ra->gs_do_switch($r0, $rev, $gs,
2690                                               $self->full_url, $ed)
2691                           or die "SVN connection failed somewhere...\n";
2692                 } elsif ($self->ra->trees_match($new_url, $r0,
2693                                                 $self->full_url, $rev)) {
2694                         print STDERR "Trees match:\n",
2695                                      "  $new_url\@$r0\n",
2696                                      "  ${\$self->full_url}\@$rev\n",
2697                                      "Following parent with no changes\n"
2698                                      unless $::_q > 1;
2699                         $self->tmp_index_do(sub {
2700                             command_noisy('read-tree', $parent);
2701                         });
2702                         $self->{last_commit} = $parent;
2703                 } else {
2704                         print STDERR "Following parent with do_update\n"
2705                                      unless $::_q > 1;
2706                         $ed = SVN::Git::Fetcher->new($self);
2707                         $self->ra->gs_do_update($rev, $rev, $self, $ed)
2708                           or die "SVN connection failed somewhere...\n";
2709                 }
2710                 print STDERR "Successfully followed parent\n" unless $::_q > 1;
2711                 return $self->make_log_entry($rev, [$parent], $ed);
2712         }
2713         return undef;
2714 }
2715
2716 sub do_fetch {
2717         my ($self, $paths, $rev) = @_;
2718         my $ed;
2719         my ($last_rev, @parents);
2720         if (my $lc = $self->last_commit) {
2721                 # we can have a branch that was deleted, then re-added
2722                 # under the same name but copied from another path, in
2723                 # which case we'll have multiple parents (we don't
2724                 # want to break the original ref, nor lose copypath info):
2725                 if (my $log_entry = $self->find_parent_branch($paths, $rev)) {
2726                         push @{$log_entry->{parents}}, $lc;
2727                         return $log_entry;
2728                 }
2729                 $ed = SVN::Git::Fetcher->new($self);
2730                 $last_rev = $self->{last_rev};
2731                 $ed->{c} = $lc;
2732                 @parents = ($lc);
2733         } else {
2734                 $last_rev = $rev;
2735                 if (my $log_entry = $self->find_parent_branch($paths, $rev)) {
2736                         return $log_entry;
2737                 }
2738                 $ed = SVN::Git::Fetcher->new($self);
2739         }
2740         unless ($self->ra->gs_do_update($last_rev, $rev, $self, $ed)) {
2741                 die "SVN connection failed somewhere...\n";
2742         }
2743         $self->make_log_entry($rev, \@parents, $ed);
2744 }
2745
2746 sub mkemptydirs {
2747         my ($self, $r) = @_;
2748
2749         sub scan {
2750                 my ($r, $empty_dirs, $line) = @_;
2751                 if (defined $r && $line =~ /^r(\d+)$/) {
2752                         return 0 if $1 > $r;
2753                 } elsif ($line =~ /^  \+empty_dir: (.+)$/) {
2754                         $empty_dirs->{$1} = 1;
2755                 } elsif ($line =~ /^  \-empty_dir: (.+)$/) {
2756                         my @d = grep {m[^\Q$1\E(/|$)]} (keys %$empty_dirs);
2757                         delete @$empty_dirs{@d};
2758                 }
2759                 1; # continue
2760         };
2761
2762         my %empty_dirs = ();
2763         my $gz_file = "$self->{dir}/unhandled.log.gz";
2764         if (-f $gz_file) {
2765                 if (!$can_compress) {
2766                         warn "Compress::Zlib could not be found; ",
2767                              "empty directories in $gz_file will not be read\n";
2768                 } else {
2769                         my $gz = Compress::Zlib::gzopen($gz_file, "rb") or
2770                                 die "Unable to open $gz_file: $!\n";
2771                         my $line;
2772                         while ($gz->gzreadline($line) > 0) {
2773                                 scan($r, \%empty_dirs, $line) or last;
2774                         }
2775                         $gz->gzclose;
2776                 }
2777         }
2778
2779         if (open my $fh, '<', "$self->{dir}/unhandled.log") {
2780                 binmode $fh or croak "binmode: $!";
2781                 while (<$fh>) {
2782                         scan($r, \%empty_dirs, $_) or last;
2783                 }
2784                 close $fh;
2785         }
2786
2787         my $strip = qr/\A\Q$self->{path}\E(?:\/|$)/;
2788         foreach my $d (sort keys %empty_dirs) {
2789                 $d = uri_decode($d);
2790                 $d =~ s/$strip//;
2791                 next if -d $d;
2792                 if (-e _) {
2793                         warn "$d exists but is not a directory\n";
2794                 } else {
2795                         print "creating empty directory: $d\n";
2796                         mkpath([$d]);
2797                 }
2798         }
2799 }
2800
2801 sub get_untracked {
2802         my ($self, $ed) = @_;
2803         my @out;
2804         my $h = $ed->{empty};
2805         foreach (sort keys %$h) {
2806                 my $act = $h->{$_} ? '+empty_dir' : '-empty_dir';
2807                 push @out, "  $act: " . uri_encode($_);
2808                 warn "W: $act: $_\n";
2809         }
2810         foreach my $t (qw/dir_prop file_prop/) {
2811                 $h = $ed->{$t} or next;
2812                 foreach my $path (sort keys %$h) {
2813                         my $ppath = $path eq '' ? '.' : $path;
2814                         foreach my $prop (sort keys %{$h->{$path}}) {
2815                                 next if $SKIP_PROP{$prop};
2816                                 my $v = $h->{$path}->{$prop};
2817                                 my $t_ppath_prop = "$t: " .
2818                                                     uri_encode($ppath) . ' ' .
2819                                                     uri_encode($prop);
2820                                 if (defined $v) {
2821                                         push @out, "  +$t_ppath_prop " .
2822                                                    uri_encode($v);
2823                                 } else {
2824                                         push @out, "  -$t_ppath_prop";
2825                                 }
2826                         }
2827                 }
2828         }
2829         foreach my $t (qw/absent_file absent_directory/) {
2830                 $h = $ed->{$t} or next;
2831                 foreach my $parent (sort keys %$h) {
2832                         foreach my $path (sort @{$h->{$parent}}) {
2833                                 push @out, "  $t: " .
2834                                            uri_encode("$parent/$path");
2835                                 warn "W: $t: $parent/$path ",
2836                                      "Insufficient permissions?\n";
2837                         }
2838                 }
2839         }
2840         \@out;
2841 }
2842
2843 # parse_svn_date(DATE)
2844 # --------------------
2845 # Given a date (in UTC) from Subversion, return a string in the format
2846 # "<TZ Offset> <local date/time>" that Git will use.
2847 #
2848 # By default the parsed date will be in UTC; if $Git::SVN::_localtime
2849 # is true we'll convert it to the local timezone instead.
2850 sub parse_svn_date {
2851         my $date = shift || return '+0000 1970-01-01 00:00:00';
2852         my ($Y,$m,$d,$H,$M,$S) = ($date =~ /^(\d{4})\-(\d\d)\-(\d\d)T
2853                                             (\d\d)\:(\d\d)\:(\d\d)\.\d*Z$/x) or
2854                                          croak "Unable to parse date: $date\n";
2855         my $parsed_date;    # Set next.
2856
2857         if ($Git::SVN::_localtime) {
2858                 # Translate the Subversion datetime to an epoch time.
2859                 # Begin by switching ourselves to $date's timezone, UTC.
2860                 my $old_env_TZ = $ENV{TZ};
2861                 $ENV{TZ} = 'UTC';
2862
2863                 my $epoch_in_UTC =
2864                     POSIX::strftime('%s', $S, $M, $H, $d, $m - 1, $Y - 1900);
2865
2866                 # Determine our local timezone (including DST) at the
2867                 # time of $epoch_in_UTC.  $Git::SVN::Log::TZ stored the
2868                 # value of TZ, if any, at the time we were run.
2869                 if (defined $Git::SVN::Log::TZ) {
2870                         $ENV{TZ} = $Git::SVN::Log::TZ;
2871                 } else {
2872                         delete $ENV{TZ};
2873                 }
2874
2875                 my $our_TZ =
2876                     POSIX::strftime('%Z', $S, $M, $H, $d, $m - 1, $Y - 1900);
2877
2878                 # This converts $epoch_in_UTC into our local timezone.
2879                 my ($sec, $min, $hour, $mday, $mon, $year,
2880                     $wday, $yday, $isdst) = localtime($epoch_in_UTC);
2881
2882                 $parsed_date = sprintf('%s %04d-%02d-%02d %02d:%02d:%02d',
2883                                        $our_TZ, $year + 1900, $mon + 1,
2884                                        $mday, $hour, $min, $sec);
2885
2886                 # Reset us to the timezone in effect when we entered
2887                 # this routine.
2888                 if (defined $old_env_TZ) {
2889                         $ENV{TZ} = $old_env_TZ;
2890                 } else {
2891                         delete $ENV{TZ};
2892                 }
2893         } else {
2894                 $parsed_date = "+0000 $Y-$m-$d $H:$M:$S";
2895         }
2896
2897         return $parsed_date;
2898 }
2899
2900 sub other_gs {
2901         my ($self, $new_url, $url,
2902             $branch_from, $r, $old_ref_id) = @_;
2903         my $gs = Git::SVN->find_by_url($new_url, $url, $branch_from);
2904         unless ($gs) {
2905                 my $ref_id = $old_ref_id;
2906                 $ref_id =~ s/\@\d+$//;
2907                 $ref_id .= "\@$r";
2908                 # just grow a tail if we're not unique enough :x
2909                 $ref_id .= '-' while find_ref($ref_id);
2910                 print STDERR "Initializing parent: $ref_id\n" unless $::_q > 1;
2911                 my ($u, $p, $repo_id) = ($new_url, '', $ref_id);
2912                 if ($u =~ s#^\Q$url\E(/|$)##) {
2913                         $p = $u;
2914                         $u = $url;
2915                         $repo_id = $self->{repo_id};
2916                 }
2917                 $gs = Git::SVN->init($u, $p, $repo_id, $ref_id, 1);
2918         }
2919         $gs
2920 }
2921
2922 sub call_authors_prog {
2923         my ($orig_author) = @_;
2924         $orig_author = command_oneline('rev-parse', '--sq-quote', $orig_author);
2925         my $author = `$::_authors_prog $orig_author`;
2926         if ($? != 0) {
2927                 die "$::_authors_prog failed with exit code $?\n"
2928         }
2929         if ($author =~ /^\s*(.+?)\s*<(.*)>\s*$/) {
2930                 my ($name, $email) = ($1, $2);
2931                 $email = undef if length $2 == 0;
2932                 return [$name, $email];
2933         } else {
2934                 die "Author: $orig_author: $::_authors_prog returned "
2935                         . "invalid author format: $author\n";
2936         }
2937 }
2938
2939 sub check_author {
2940         my ($author) = @_;
2941         if (!defined $author || length $author == 0) {
2942                 $author = '(no author)';
2943         }
2944         if (!defined $::users{$author}) {
2945                 if (defined $::_authors_prog) {
2946                         $::users{$author} = call_authors_prog($author);
2947                 } elsif (defined $::_authors) {
2948                         die "Author: $author not defined in $::_authors file\n";
2949                 }
2950         }
2951         $author;
2952 }
2953
2954 sub find_extra_svk_parents {
2955         my ($self, $ed, $tickets, $parents) = @_;
2956         # aha!  svk:merge property changed...
2957         my @tickets = split "\n", $tickets;
2958         my @known_parents;
2959         for my $ticket ( @tickets ) {
2960                 my ($uuid, $path, $rev) = split /:/, $ticket;
2961                 if ( $uuid eq $self->ra_uuid ) {
2962                         my $url = $self->rewrite_root || $self->{url};
2963                         my $repos_root = $url;
2964                         my $branch_from = $path;
2965                         $branch_from =~ s{^/}{};
2966                         my $gs = $self->other_gs($repos_root."/".$branch_from,
2967                                                  $url,
2968                                                  $branch_from,
2969                                                  $rev,
2970                                                  $self->{ref_id});
2971                         if ( my $commit = $gs->rev_map_get($rev, $uuid) ) {
2972                                 # wahey!  we found it, but it might be
2973                                 # an old one (!)
2974                                 push @known_parents, [ $rev, $commit ];
2975                         }
2976                 }
2977         }
2978         # Ordering matters; highest-numbered commit merge tickets
2979         # first, as they may account for later merge ticket additions
2980         # or changes.
2981         @known_parents = map {$_->[1]} sort {$b->[0] <=> $a->[0]} @known_parents;
2982         for my $parent ( @known_parents ) {
2983                 my @cmd = ('rev-list', $parent, map { "^$_" } @$parents );
2984                 my ($msg_fh, $ctx) = command_output_pipe(@cmd);
2985                 my $new;
2986                 while ( <$msg_fh> ) {
2987                         $new=1;last;
2988                 }
2989                 command_close_pipe($msg_fh, $ctx);
2990                 if ( $new ) {
2991                         print STDERR
2992                             "Found merge parent (svk:merge ticket): $parent\n";
2993                         push @$parents, $parent;
2994                 }
2995         }
2996 }
2997
2998 sub lookup_svn_merge {
2999         my $uuid = shift;
3000         my $url = shift;
3001         my $merge = shift;
3002
3003         my ($source, $revs) = split ":", $merge;
3004         my $path = $source;
3005         $path =~ s{^/}{};
3006         my $gs = Git::SVN->find_by_url($url.$source, $url, $path);
3007         if ( !$gs ) {
3008                 warn "Couldn't find revmap for $url$source\n";
3009                 return;
3010         }
3011         my @ranges = split ",", $revs;
3012         my ($tip, $tip_commit);
3013         my @merged_commit_ranges;
3014         # find the tip
3015         for my $range ( @ranges ) {
3016                 my ($bottom, $top) = split "-", $range;
3017                 $top ||= $bottom;
3018                 my $bottom_commit =
3019                         $gs->rev_map_get($bottom, $uuid) ||
3020                         $gs->rev_map_get($bottom+1, $uuid);
3021                 my $top_commit;
3022                 for (; !$top_commit && $top >= $bottom; --$top) {
3023                         $top_commit =
3024                                 $gs->rev_map_get($top, $uuid);
3025                 }
3026
3027                 unless ($top_commit and $bottom_commit) {
3028                         warn "W:unknown path/rev in svn:mergeinfo "
3029                                 ."dirprop: $source:$range\n";
3030                         next;
3031                 }
3032
3033                 push @merged_commit_ranges,
3034                         "$bottom_commit..$top_commit";
3035
3036                 if ( !defined $tip or $top > $tip ) {
3037                         $tip = $top;
3038                         $tip_commit = $top_commit;
3039                 }
3040         }
3041         return ($tip_commit, @merged_commit_ranges);
3042 }
3043 BEGIN {
3044         memoize 'lookup_svn_merge';
3045 }
3046
3047 # note: this function should only be called if the various dirprops
3048 # have actually changed
3049 sub find_extra_svn_parents {
3050         my ($self, $ed, $mergeinfo, $parents) = @_;
3051         # aha!  svk:merge property changed...
3052
3053         # We first search for merged tips which are not in our
3054         # history.  Then, we figure out which git revisions are in
3055         # that tip, but not this revision.  If all of those revisions
3056         # are now marked as merge, we can add the tip as a parent.
3057         my @merges = split "\n", $mergeinfo;
3058         my @merge_tips;
3059         my @merged_commit_ranges;
3060         my $url = $self->rewrite_root || $self->{url};
3061         my $uuid = $self->ra_uuid;
3062         for my $merge ( @merges ) {
3063                 my ($tip_commit, @ranges) =
3064                         lookup_svn_merge( $uuid, $url, $merge );
3065                 push @merged_commit_ranges, @ranges;
3066                 unless (!$tip_commit or
3067                                 grep { $_ eq $tip_commit } @$parents ) {
3068                         push @merge_tips, $tip_commit;
3069                 } else {
3070                         push @merge_tips, undef;
3071                 }
3072         }
3073         for my $merge_tip ( @merge_tips ) {
3074                 my $spec = shift @merges;
3075                 next unless $merge_tip;
3076                 my @cmd = ('rev-list', "-1", $merge_tip,
3077                            "--not", @$parents );
3078                 my ($msg_fh, $ctx) = command_output_pipe(@cmd);
3079                 my $new;
3080                 while ( <$msg_fh> ) {
3081                         $new=1;last;
3082                 }
3083                 command_close_pipe($msg_fh, $ctx);
3084                 if ( $new ) {
3085                         push @cmd, @merged_commit_ranges;
3086                         my ($msg_fh, $ctx) = command_output_pipe(@cmd);
3087                         my $unmerged;
3088                         while ( <$msg_fh> ) {
3089                                 $unmerged=1;last;
3090                         }
3091                         command_close_pipe($msg_fh, $ctx);
3092                         if ( $unmerged ) {
3093                                 warn "W:svn cherry-pick ignored ($spec)\n";
3094                         } else {
3095                                 warn
3096                                   "Found merge parent (svn:mergeinfo prop): ",
3097                                   $merge_tip, "\n";
3098                                 push @$parents, $merge_tip;
3099                         }
3100                 }
3101         }
3102 }
3103
3104 sub make_log_entry {
3105         my ($self, $rev, $parents, $ed) = @_;
3106         my $untracked = $self->get_untracked($ed);
3107
3108         my @parents = @$parents;
3109         my $ps = $ed->{path_strip} || "";
3110         for my $path ( grep { m/$ps/ } %{$ed->{dir_prop}} ) {
3111                 my $props = $ed->{dir_prop}{$path};
3112                 if ( $props->{"svk:merge"} ) {
3113                         $self->find_extra_svk_parents
3114                                 ($ed, $props->{"svk:merge"}, \@parents);
3115                 }
3116                 if ( $props->{"svn:mergeinfo"} ) {
3117                         $self->find_extra_svn_parents
3118                                 ($ed,
3119                                  $props->{"svn:mergeinfo"},
3120                                  \@parents);
3121                 }
3122         }
3123
3124         open my $un, '>>', "$self->{dir}/unhandled.log" or croak $!;
3125         print $un "r$rev\n" or croak $!;
3126         print $un $_, "\n" foreach @$untracked;
3127         my %log_entry = ( parents => \@parents, revision => $rev,
3128                           log => '');
3129
3130         my $headrev;
3131         my $logged = delete $self->{logged_rev_props};
3132         if (!$logged || $self->{-want_revprops}) {
3133                 my $rp = $self->ra->rev_proplist($rev);
3134                 foreach (sort keys %$rp) {
3135                         my $v = $rp->{$_};
3136                         if (/^svn:(author|date|log)$/) {
3137                                 $log_entry{$1} = $v;
3138                         } elsif ($_ eq 'svm:headrev') {
3139                                 $headrev = $v;
3140                         } else {
3141                                 print $un "  rev_prop: ", uri_encode($_), ' ',
3142                                           uri_encode($v), "\n";
3143                         }
3144                 }
3145         } else {
3146                 map { $log_entry{$_} = $logged->{$_} } keys %$logged;
3147         }
3148         close $un or croak $!;
3149
3150         $log_entry{date} = parse_svn_date($log_entry{date});
3151         $log_entry{log} .= "\n";
3152         my $author = $log_entry{author} = check_author($log_entry{author});
3153         my ($name, $email) = defined $::users{$author} ? @{$::users{$author}}
3154                                                        : ($author, undef);
3155
3156         my ($commit_name, $commit_email) = ($name, $email);
3157         if ($_use_log_author) {
3158                 my $name_field;
3159                 if ($log_entry{log} =~ /From:\s+(.*\S)\s*\n/i) {
3160                         $name_field = $1;
3161                 } elsif ($log_entry{log} =~ /Signed-off-by:\s+(.*\S)\s*\n/i) {
3162                         $name_field = $1;
3163                 }
3164                 if (!defined $name_field) {
3165                         if (!defined $email) {
3166                                 $email = $name;
3167                         }
3168                 } elsif ($name_field =~ /(.*?)\s+<(.*)>/) {
3169                         ($name, $email) = ($1, $2);
3170                 } elsif ($name_field =~ /(.*)@/) {
3171                         ($name, $email) = ($1, $name_field);
3172                 } else {
3173                         ($name, $email) = ($name_field, $name_field);
3174                 }
3175         }
3176         if (defined $headrev && $self->use_svm_props) {
3177                 if ($self->rewrite_root) {
3178                         die "Can't have both 'useSvmProps' and 'rewriteRoot' ",
3179                             "options set!\n";
3180                 }
3181                 my ($uuid, $r) = $headrev =~ m{^([a-f\d\-]{30,}):(\d+)$}i;
3182                 # we don't want "SVM: initializing mirror for junk" ...
3183                 return undef if $r == 0;
3184                 my $svm = $self->svm;
3185                 if ($uuid ne $svm->{uuid}) {
3186                         die "UUID mismatch on SVM path:\n",
3187                             "expected: $svm->{uuid}\n",
3188                             "     got: $uuid\n";
3189                 }
3190                 my $full_url = $self->full_url;
3191                 $full_url =~ s#^\Q$svm->{replace}\E(/|$)#$svm->{source}$1# or
3192                              die "Failed to replace '$svm->{replace}' with ",
3193                                  "'$svm->{source}' in $full_url\n";
3194                 # throw away username for storing in records
3195                 remove_username($full_url);
3196                 $log_entry{metadata} = "$full_url\@$r $uuid";
3197                 $log_entry{svm_revision} = $r;
3198                 $email ||= "$author\@$uuid";
3199                 $commit_email ||= "$author\@$uuid";
3200         } elsif ($self->use_svnsync_props) {
3201                 my $full_url = $self->svnsync->{url};
3202                 $full_url .= "/$self->{path}" if length $self->{path};
3203                 remove_username($full_url);
3204                 my $uuid = $self->svnsync->{uuid};
3205                 $log_entry{metadata} = "$full_url\@$rev $uuid";
3206                 $email ||= "$author\@$uuid";
3207                 $commit_email ||= "$author\@$uuid";
3208         } else {
3209                 my $url = $self->metadata_url;
3210                 remove_username($url);
3211                 $log_entry{metadata} = "$url\@$rev " .
3212                                        $self->ra->get_uuid;
3213                 $email ||= "$author\@" . $self->ra->get_uuid;
3214                 $commit_email ||= "$author\@" . $self->ra->get_uuid;
3215         }
3216         $log_entry{name} = $name;
3217         $log_entry{email} = $email;
3218         $log_entry{commit_name} = $commit_name;
3219         $log_entry{commit_email} = $commit_email;
3220         \%log_entry;
3221 }
3222
3223 sub fetch {
3224         my ($self, $min_rev, $max_rev, @parents) = @_;
3225         my ($last_rev, $last_commit) = $self->last_rev_commit;
3226         my ($base, $head) = $self->get_fetch_range($min_rev, $max_rev);
3227         $self->ra->gs_fetch_loop_common($base, $head, [$self]);
3228 }
3229
3230 sub set_tree_cb {
3231         my ($self, $log_entry, $tree, $rev, $date, $author) = @_;
3232         $self->{inject_parents} = { $rev => $tree };
3233         $self->fetch(undef, undef);
3234 }
3235
3236 sub set_tree {
3237         my ($self, $tree) = (shift, shift);
3238         my $log_entry = ::get_commit_entry($tree);
3239         unless ($self->{last_rev}) {
3240                 ::fatal("Must have an existing revision to commit");
3241         }
3242         my %ed_opts = ( r => $self->{last_rev},
3243                         log => $log_entry->{log},
3244                         ra => $self->ra,
3245                         tree_a => $self->{last_commit},
3246                         tree_b => $tree,
3247                         editor_cb => sub {
3248                                $self->set_tree_cb($log_entry, $tree, @_) },
3249                         svn_path => $self->{path} );
3250         if (!SVN::Git::Editor->new(\%ed_opts)->apply_diff) {
3251                 print "No changes\nr$self->{last_rev} = $tree\n";
3252         }
3253 }
3254
3255 sub rebuild_from_rev_db {
3256         my ($self, $path) = @_;
3257         my $r = -1;
3258         open my $fh, '<', $path or croak "open: $!";
3259         binmode $fh or croak "binmode: $!";
3260         while (<$fh>) {
3261                 length($_) == 41 or croak "inconsistent size in ($_) != 41";
3262                 chomp($_);
3263                 ++$r;
3264                 next if $_ eq ('0' x 40);
3265                 $self->rev_map_set($r, $_);
3266                 print "r$r = $_\n";
3267         }
3268         close $fh or croak "close: $!";
3269         unlink $path or croak "unlink: $!";
3270 }
3271
3272 sub rebuild {
3273         my ($self) = @_;
3274         my $map_path = $self->map_path;
3275         my $partial = (-e $map_path && ! -z $map_path);
3276         return unless ::verify_ref($self->refname.'^0');
3277         if (!$partial && ($self->use_svm_props || $self->no_metadata)) {
3278                 my $rev_db = $self->rev_db_path;
3279                 $self->rebuild_from_rev_db($rev_db);
3280                 if ($self->use_svm_props) {
3281                         my $svm_rev_db = $self->rev_db_path($self->svm_uuid);
3282                         $self->rebuild_from_rev_db($svm_rev_db);
3283                 }
3284                 $self->unlink_rev_db_symlink;
3285                 return;
3286         }
3287         print "Rebuilding $map_path ...\n" if (!$partial);
3288         my ($base_rev, $head) = ($partial ? $self->rev_map_max_norebuild(1) :
3289                 (undef, undef));
3290         my ($log, $ctx) =
3291             command_output_pipe(qw/rev-list --pretty=raw --no-color --reverse/,
3292                                 ($head ? "$head.." : "") . $self->refname,
3293                                 '--');
3294         my $metadata_url = $self->metadata_url;
3295         remove_username($metadata_url);
3296         my $svn_uuid = $self->ra_uuid;
3297         my $c;
3298         while (<$log>) {
3299                 if ( m{^commit ($::sha1)$} ) {
3300                         $c = $1;
3301                         next;
3302                 }
3303                 next unless s{^\s*(git-svn-id:)}{$1};
3304                 my ($url, $rev, $uuid) = ::extract_metadata($_);
3305                 remove_username($url);
3306
3307                 # ignore merges (from set-tree)
3308                 next if (!defined $rev || !$uuid);
3309
3310                 # if we merged or otherwise started elsewhere, this is
3311                 # how we break out of it
3312                 if (($uuid ne $svn_uuid) ||
3313                     ($metadata_url && $url && ($url ne $metadata_url))) {
3314                         next;
3315                 }
3316                 if ($partial && $head) {
3317                         print "Partial-rebuilding $map_path ...\n";
3318                         print "Currently at $base_rev = $head\n";
3319                         $head = undef;
3320                 }
3321
3322                 $self->rev_map_set($rev, $c);
3323                 print "r$rev = $c\n";
3324         }
3325         command_close_pipe($log, $ctx);
3326         print "Done rebuilding $map_path\n" if (!$partial || !$head);
3327         my $rev_db_path = $self->rev_db_path;
3328         if (-f $self->rev_db_path) {
3329                 unlink $self->rev_db_path or croak "unlink: $!";
3330         }
3331         $self->unlink_rev_db_symlink;
3332 }
3333
3334 # rev_map:
3335 # Tie::File seems to be prone to offset errors if revisions get sparse,
3336 # it's not that fast, either.  Tie::File is also not in Perl 5.6.  So
3337 # one of my favorite modules is out :<  Next up would be one of the DBM
3338 # modules, but I'm not sure which is most portable...
3339 #
3340 # This is the replacement for the rev_db format, which was too big
3341 # and inefficient for large repositories with a lot of sparse history
3342 # (mainly tags)
3343 #
3344 # The format is this:
3345 #   - 24 bytes for every record,
3346 #     * 4 bytes for the integer representing an SVN revision number
3347 #     * 20 bytes representing the sha1 of a git commit
3348 #   - No empty padding records like the old format
3349 #     (except the last record, which can be overwritten)
3350 #   - new records are written append-only since SVN revision numbers
3351 #     increase monotonically
3352 #   - lookups on SVN revision number are done via a binary search
3353 #   - Piping the file to xxd -c24 is a good way of dumping it for
3354 #     viewing or editing (piped back through xxd -r), should the need
3355 #     ever arise.
3356 #   - The last record can be padding revision with an all-zero sha1
3357 #     This is used to optimize fetch performance when using multiple
3358 #     "fetch" directives in .git/config
3359 #
3360 # These files are disposable unless noMetadata or useSvmProps is set
3361
3362 sub _rev_map_set {
3363         my ($fh, $rev, $commit) = @_;
3364
3365         binmode $fh or croak "binmode: $!";
3366         my $size = (stat($fh))[7];
3367         ($size % 24) == 0 or croak "inconsistent size: $size";
3368
3369         my $wr_offset = 0;
3370         if ($size > 0) {
3371                 sysseek($fh, -24, SEEK_END) or croak "seek: $!";
3372                 my $read = sysread($fh, my $buf, 24) or croak "read: $!";
3373                 $read == 24 or croak "read only $read bytes (!= 24)";
3374                 my ($last_rev, $last_commit) = unpack(rev_map_fmt, $buf);
3375                 if ($last_commit eq ('0' x40)) {
3376                         if ($size >= 48) {
3377                                 sysseek($fh, -48, SEEK_END) or croak "seek: $!";
3378                                 $read = sysread($fh, $buf, 24) or
3379                                     croak "read: $!";
3380                                 $read == 24 or
3381                                     croak "read only $read bytes (!= 24)";
3382                                 ($last_rev, $last_commit) =
3383                                     unpack(rev_map_fmt, $buf);
3384                                 if ($last_commit eq ('0' x40)) {
3385                                         croak "inconsistent .rev_map\n";
3386                                 }
3387                         }
3388                         if ($last_rev >= $rev) {
3389                                 croak "last_rev is higher!: $last_rev >= $rev";
3390                         }
3391                         $wr_offset = -24;
3392                 }
3393         }
3394         sysseek($fh, $wr_offset, SEEK_END) or croak "seek: $!";
3395         syswrite($fh, pack(rev_map_fmt, $rev, $commit), 24) == 24 or
3396           croak "write: $!";
3397 }
3398
3399 sub _rev_map_reset {
3400         my ($fh, $rev, $commit) = @_;
3401         my $c = _rev_map_get($fh, $rev);
3402         $c eq $commit or die "_rev_map_reset(@_) commit $c does not match!\n";
3403         my $offset = sysseek($fh, 0, SEEK_CUR) or croak "seek: $!";
3404         truncate $fh, $offset or croak "truncate: $!";
3405 }
3406
3407 sub mkfile {
3408         my ($path) = @_;
3409         unless (-e $path) {
3410                 my ($dir, $base) = ($path =~ m#^(.*?)/?([^/]+)$#);
3411                 mkpath([$dir]) unless -d $dir;
3412                 open my $fh, '>>', $path or die "Couldn't create $path: $!\n";
3413                 close $fh or die "Couldn't close (create) $path: $!\n";
3414         }
3415 }
3416
3417 sub rev_map_set {
3418         my ($self, $rev, $commit, $update_ref, $uuid) = @_;
3419         length $commit == 40 or die "arg3 must be a full SHA1 hexsum\n";
3420         my $db = $self->map_path($uuid);
3421         my $db_lock = "$db.lock";
3422         my $sig;
3423         $update_ref ||= 0;
3424         if ($update_ref) {
3425                 $SIG{INT} = $SIG{HUP} = $SIG{TERM} = $SIG{ALRM} = $SIG{PIPE} =
3426                             $SIG{USR1} = $SIG{USR2} = sub { $sig = $_[0] };
3427         }
3428         mkfile($db);
3429
3430         $LOCKFILES{$db_lock} = 1;
3431         my $sync;
3432         # both of these options make our .rev_db file very, very important
3433         # and we can't afford to lose it because rebuild() won't work
3434         if ($self->use_svm_props || $self->no_metadata) {
3435                 $sync = 1;
3436                 copy($db, $db_lock) or die "rev_map_set(@_): ",
3437                                            "Failed to copy: ",
3438                                            "$db => $db_lock ($!)\n";
3439         } else {
3440                 rename $db, $db_lock or die "rev_map_set(@_): ",
3441                                             "Failed to rename: ",
3442                                             "$db => $db_lock ($!)\n";
3443         }
3444
3445         sysopen(my $fh, $db_lock, O_RDWR | O_CREAT)
3446              or croak "Couldn't open $db_lock: $!\n";
3447         $update_ref eq 'reset' ? _rev_map_reset($fh, $rev, $commit) :
3448                                  _rev_map_set($fh, $rev, $commit);
3449         if ($sync) {
3450                 $fh->flush or die "Couldn't flush $db_lock: $!\n";
3451                 $fh->sync or die "Couldn't sync $db_lock: $!\n";
3452         }
3453         close $fh or croak $!;
3454         if ($update_ref) {
3455                 $_head = $self;
3456                 my $note = "";
3457                 $note = " ($update_ref)" if ($update_ref !~ /^\d*$/);
3458                 command_noisy('update-ref', '-m', "r$rev$note",
3459                               $self->refname, $commit);
3460         }
3461         rename $db_lock, $db or die "rev_map_set(@_): ", "Failed to rename: ",
3462                                     "$db_lock => $db ($!)\n";
3463         delete $LOCKFILES{$db_lock};
3464         if ($update_ref) {
3465                 $SIG{INT} = $SIG{HUP} = $SIG{TERM} = $SIG{ALRM} = $SIG{PIPE} =
3466                             $SIG{USR1} = $SIG{USR2} = 'DEFAULT';
3467                 kill $sig, $$ if defined $sig;
3468         }
3469 }
3470
3471 # If want_commit, this will return an array of (rev, commit) where
3472 # commit _must_ be a valid commit in the archive.
3473 # Otherwise, it'll return the max revision (whether or not the
3474 # commit is valid or just a 0x40 placeholder).
3475 sub rev_map_max {
3476         my ($self, $want_commit) = @_;
3477         $self->rebuild;
3478         my ($r, $c) = $self->rev_map_max_norebuild($want_commit);
3479         $want_commit ? ($r, $c) : $r;
3480 }
3481
3482 sub rev_map_max_norebuild {
3483         my ($self, $want_commit) = @_;
3484         my $map_path = $self->map_path;
3485         stat $map_path or return $want_commit ? (0, undef) : 0;
3486         sysopen(my $fh, $map_path, O_RDONLY) or croak "open: $!";
3487         binmode $fh or croak "binmode: $!";
3488         my $size = (stat($fh))[7];
3489         ($size % 24) == 0 or croak "inconsistent size: $size";
3490
3491         if ($size == 0) {
3492                 close $fh or croak "close: $!";
3493                 return $want_commit ? (0, undef) : 0;
3494         }
3495
3496         sysseek($fh, -24, SEEK_END) or croak "seek: $!";
3497         sysread($fh, my $buf, 24) == 24 or croak "read: $!";
3498         my ($r, $c) = unpack(rev_map_fmt, $buf);
3499         if ($want_commit && $c eq ('0' x40)) {
3500                 if ($size < 48) {
3501                         return $want_commit ? (0, undef) : 0;
3502                 }
3503                 sysseek($fh, -48, SEEK_END) or croak "seek: $!";
3504                 sysread($fh, $buf, 24) == 24 or croak "read: $!";
3505                 ($r, $c) = unpack(rev_map_fmt, $buf);
3506                 if ($c eq ('0'x40)) {
3507                         croak "Penultimate record is all-zeroes in $map_path";
3508                 }
3509         }
3510         close $fh or croak "close: $!";
3511         $want_commit ? ($r, $c) : $r;
3512 }
3513
3514 sub rev_map_get {
3515         my ($self, $rev, $uuid) = @_;
3516         my $map_path = $self->map_path($uuid);
3517         return undef unless -e $map_path;
3518
3519         sysopen(my $fh, $map_path, O_RDONLY) or croak "open: $!";
3520         my $c = _rev_map_get($fh, $rev);
3521         close($fh) or croak "close: $!";
3522         $c
3523 }
3524
3525 sub _rev_map_get {
3526         my ($fh, $rev) = @_;
3527
3528         binmode $fh or croak "binmode: $!";
3529         my $size = (stat($fh))[7];
3530         ($size % 24) == 0 or croak "inconsistent size: $size";
3531
3532         if ($size == 0) {
3533                 return undef;
3534         }
3535
3536         my ($l, $u) = (0, $size - 24);
3537         my ($r, $c, $buf);
3538
3539         while ($l <= $u) {
3540                 my $i = int(($l/24 + $u/24) / 2) * 24;
3541                 sysseek($fh, $i, SEEK_SET) or croak "seek: $!";
3542                 sysread($fh, my $buf, 24) == 24 or croak "read: $!";
3543                 my ($r, $c) = unpack(rev_map_fmt, $buf);
3544
3545                 if ($r < $rev) {
3546                         $l = $i + 24;
3547                 } elsif ($r > $rev) {
3548                         $u = $i - 24;
3549                 } else { # $r == $rev
3550                         return $c eq ('0' x 40) ? undef : $c;
3551                 }
3552         }
3553         undef;
3554 }
3555
3556 # Finds the first svn revision that exists on (if $eq_ok is true) or
3557 # before $rev for the current branch.  It will not search any lower
3558 # than $min_rev.  Returns the git commit hash and svn revision number
3559 # if found, else (undef, undef).
3560 sub find_rev_before {
3561         my ($self, $rev, $eq_ok, $min_rev) = @_;
3562         --$rev unless $eq_ok;
3563         $min_rev ||= 1;
3564         my $max_rev = $self->rev_map_max;
3565         $rev = $max_rev if ($rev > $max_rev);
3566         while ($rev >= $min_rev) {
3567                 if (my $c = $self->rev_map_get($rev)) {
3568                         return ($rev, $c);
3569                 }
3570                 --$rev;
3571         }
3572         return (undef, undef);
3573 }
3574
3575 # Finds the first svn revision that exists on (if $eq_ok is true) or
3576 # after $rev for the current branch.  It will not search any higher
3577 # than $max_rev.  Returns the git commit hash and svn revision number
3578 # if found, else (undef, undef).
3579 sub find_rev_after {
3580         my ($self, $rev, $eq_ok, $max_rev) = @_;
3581         ++$rev unless $eq_ok;
3582         $max_rev ||= $self->rev_map_max;
3583         while ($rev <= $max_rev) {
3584                 if (my $c = $self->rev_map_get($rev)) {
3585                         return ($rev, $c);
3586                 }
3587                 ++$rev;
3588         }
3589         return (undef, undef);
3590 }
3591
3592 sub _new {
3593         my ($class, $repo_id, $ref_id, $path) = @_;
3594         unless (defined $repo_id && length $repo_id) {
3595                 $repo_id = $Git::SVN::default_repo_id;
3596         }
3597         unless (defined $ref_id && length $ref_id) {
3598                 $_prefix = '' unless defined($_prefix);
3599                 $_[2] = $ref_id =
3600                              "refs/remotes/$_prefix$Git::SVN::default_ref_id";
3601         }
3602         $_[1] = $repo_id;
3603         my $dir = "$ENV{GIT_DIR}/svn/$ref_id";
3604
3605         # Older repos imported by us used $GIT_DIR/svn/foo instead of
3606         # $GIT_DIR/svn/refs/remotes/foo when tracking refs/remotes/foo
3607         if ($ref_id =~ m{^refs/remotes/(.*)}) {
3608                 my $old_dir = "$ENV{GIT_DIR}/svn/$1";
3609                 if (-d $old_dir && ! -d $dir) {
3610                         $dir = $old_dir;
3611                 }
3612         }
3613
3614         $_[3] = $path = '' unless (defined $path);
3615         mkpath([$dir]);
3616         bless {
3617                 ref_id => $ref_id, dir => $dir, index => "$dir/index",
3618                 path => $path, config => "$ENV{GIT_DIR}/svn/config",
3619                 map_root => "$dir/.rev_map", repo_id => $repo_id }, $class;
3620 }
3621
3622 # for read-only access of old .rev_db formats
3623 sub unlink_rev_db_symlink {
3624         my ($self) = @_;
3625         my $link = $self->rev_db_path;
3626         $link =~ s/\.[\w-]+$// or croak "missing UUID at the end of $link";
3627         if (-l $link) {
3628                 unlink $link or croak "unlink: $link failed!";
3629         }
3630 }
3631
3632 sub rev_db_path {
3633         my ($self, $uuid) = @_;
3634         my $db_path = $self->map_path($uuid);
3635         $db_path =~ s{/\.rev_map\.}{/\.rev_db\.}
3636             or croak "map_path: $db_path does not contain '/.rev_map.' !";
3637         $db_path;
3638 }
3639
3640 # the new replacement for .rev_db
3641 sub map_path {
3642         my ($self, $uuid) = @_;
3643         $uuid ||= $self->ra_uuid;
3644         "$self->{map_root}.$uuid";
3645 }
3646
3647 sub uri_encode {
3648         my ($f) = @_;
3649         $f =~ s#([^a-zA-Z0-9\*!\:_\./\-])#uc sprintf("%%%02x",ord($1))#eg;
3650         $f
3651 }
3652
3653 sub uri_decode {
3654         my ($f) = @_;
3655         $f =~ s#%([0-9a-fA-F]{2})#chr(hex($1))#eg;
3656         $f
3657 }
3658
3659 sub remove_username {
3660         $_[0] =~ s{^([^:]*://)[^@]+@}{$1};
3661 }
3662
3663 package Git::SVN::Prompt;
3664 use strict;
3665 use warnings;
3666 require SVN::Core;
3667 use vars qw/$_no_auth_cache $_username/;
3668
3669 sub simple {
3670         my ($cred, $realm, $default_username, $may_save, $pool) = @_;
3671         $may_save = undef if $_no_auth_cache;
3672         $default_username = $_username if defined $_username;
3673         if (defined $default_username && length $default_username) {
3674                 if (defined $realm && length $realm) {
3675                         print STDERR "Authentication realm: $realm\n";
3676                         STDERR->flush;
3677                 }
3678                 $cred->username($default_username);
3679         } else {
3680                 username($cred, $realm, $may_save, $pool);
3681         }
3682         $cred->password(_read_password("Password for '" .
3683                                        $cred->username . "': ", $realm));
3684         $cred->may_save($may_save);
3685         $SVN::_Core::SVN_NO_ERROR;
3686 }
3687
3688 sub ssl_server_trust {
3689         my ($cred, $realm, $failures, $cert_info, $may_save, $pool) = @_;
3690         $may_save = undef if $_no_auth_cache;
3691         print STDERR "Error validating server certificate for '$realm':\n";
3692         {
3693                 no warnings 'once';
3694                 # All variables SVN::Auth::SSL::* are used only once,
3695                 # so we're shutting up Perl warnings about this.
3696                 if ($failures & $SVN::Auth::SSL::UNKNOWNCA) {
3697                         print STDERR " - The certificate is not issued ",
3698                             "by a trusted authority. Use the\n",
3699                             "   fingerprint to validate ",
3700                             "the certificate manually!\n";
3701                 }
3702                 if ($failures & $SVN::Auth::SSL::CNMISMATCH) {
3703                         print STDERR " - The certificate hostname ",
3704                             "does not match.\n";
3705                 }
3706                 if ($failures & $SVN::Auth::SSL::NOTYETVALID) {
3707                         print STDERR " - The certificate is not yet valid.\n";
3708                 }
3709                 if ($failures & $SVN::Auth::SSL::EXPIRED) {
3710                         print STDERR " - The certificate has expired.\n";
3711                 }
3712                 if ($failures & $SVN::Auth::SSL::OTHER) {
3713                         print STDERR " - The certificate has ",
3714                             "an unknown error.\n";
3715                 }
3716         } # no warnings 'once'
3717         printf STDERR
3718                 "Certificate information:\n".
3719                 " - Hostname: %s\n".
3720                 " - Valid: from %s until %s\n".
3721                 " - Issuer: %s\n".
3722                 " - Fingerprint: %s\n",
3723                 map $cert_info->$_, qw(hostname valid_from valid_until
3724                                        issuer_dname fingerprint);
3725         my $choice;
3726 prompt:
3727         print STDERR $may_save ?
3728               "(R)eject, accept (t)emporarily or accept (p)ermanently? " :
3729               "(R)eject or accept (t)emporarily? ";
3730         STDERR->flush;
3731         $choice = lc(substr(<STDIN> || 'R', 0, 1));
3732         if ($choice =~ /^t$/i) {
3733                 $cred->may_save(undef);
3734         } elsif ($choice =~ /^r$/i) {
3735                 return -1;
3736         } elsif ($may_save && $choice =~ /^p$/i) {
3737                 $cred->may_save($may_save);
3738         } else {
3739                 goto prompt;
3740         }
3741         $cred->accepted_failures($failures);
3742         $SVN::_Core::SVN_NO_ERROR;
3743 }
3744
3745 sub ssl_client_cert {
3746         my ($cred, $realm, $may_save, $pool) = @_;
3747         $may_save = undef if $_no_auth_cache;
3748         print STDERR "Client certificate filename: ";
3749         STDERR->flush;
3750         chomp(my $filename = <STDIN>);
3751         $cred->cert_file($filename);
3752         $cred->may_save($may_save);
3753         $SVN::_Core::SVN_NO_ERROR;
3754 }
3755
3756 sub ssl_client_cert_pw {
3757         my ($cred, $realm, $may_save, $pool) = @_;
3758         $may_save = undef if $_no_auth_cache;
3759         $cred->password(_read_password("Password: ", $realm));
3760         $cred->may_save($may_save);
3761         $SVN::_Core::SVN_NO_ERROR;
3762 }
3763
3764 sub username {
3765         my ($cred, $realm, $may_save, $pool) = @_;
3766         $may_save = undef if $_no_auth_cache;
3767         if (defined $realm && length $realm) {
3768                 print STDERR "Authentication realm: $realm\n";
3769         }
3770         my $username;
3771         if (defined $_username) {
3772                 $username = $_username;
3773         } else {
3774                 print STDERR "Username: ";
3775                 STDERR->flush;
3776                 chomp($username = <STDIN>);
3777         }
3778         $cred->username($username);
3779         $cred->may_save($may_save);
3780         $SVN::_Core::SVN_NO_ERROR;
3781 }
3782
3783 sub _read_password {
3784         my ($prompt, $realm) = @_;
3785         print STDERR $prompt;
3786         STDERR->flush;
3787         require Term::ReadKey;
3788         Term::ReadKey::ReadMode('noecho');
3789         my $password = '';
3790         while (defined(my $key = Term::ReadKey::ReadKey(0))) {
3791                 last if $key =~ /[\012\015]/; # \n\r
3792                 $password .= $key;
3793         }
3794         Term::ReadKey::ReadMode('restore');
3795         print STDERR "\n";
3796         STDERR->flush;
3797         $password;
3798 }
3799
3800 package SVN::Git::Fetcher;
3801 use vars qw/@ISA/;
3802 use strict;
3803 use warnings;
3804 use Carp qw/croak/;
3805 use File::Temp qw/tempfile/;
3806 use IO::File qw//;
3807 use vars qw/$_ignore_regex/;
3808
3809 # file baton members: path, mode_a, mode_b, pool, fh, blob, base
3810 sub new {
3811         my ($class, $git_svn, $switch_path) = @_;
3812         my $self = SVN::Delta::Editor->new;
3813         bless $self, $class;
3814         if (exists $git_svn->{last_commit}) {
3815                 $self->{c} = $git_svn->{last_commit};
3816                 $self->{empty_symlinks} =
3817                                   _mark_empty_symlinks($git_svn, $switch_path);
3818         }
3819         $self->{ignore_regex} = eval { command_oneline('config', '--get',
3820                              "svn-remote.$git_svn->{repo_id}.ignore-paths") };
3821         $self->{empty} = {};
3822         $self->{dir_prop} = {};
3823         $self->{file_prop} = {};
3824         $self->{absent_dir} = {};
3825         $self->{absent_file} = {};
3826         $self->{gii} = $git_svn->tmp_index_do(sub { Git::IndexInfo->new });
3827         $self;
3828 }
3829
3830 # this uses the Ra object, so it must be called before do_{switch,update},
3831 # not inside them (when the Git::SVN::Fetcher object is passed) to
3832 # do_{switch,update}
3833 sub _mark_empty_symlinks {
3834         my ($git_svn, $switch_path) = @_;
3835         my $bool = Git::config_bool('svn.brokenSymlinkWorkaround');
3836         return {} if (!defined($bool)) || (defined($bool) && ! $bool);
3837
3838         my %ret;
3839         my ($rev, $cmt) = $git_svn->last_rev_commit;
3840         return {} unless ($rev && $cmt);
3841
3842         # allow the warning to be printed for each revision we fetch to
3843         # ensure the user sees it.  The user can also disable the workaround
3844         # on the repository even while git svn is running and the next
3845         # revision fetched will skip this expensive function.
3846         my $printed_warning;
3847         chomp(my $empty_blob = `git hash-object -t blob --stdin < /dev/null`);
3848         my ($ls, $ctx) = command_output_pipe(qw/ls-tree -r -z/, $cmt);
3849         local $/ = "\0";
3850         my $pfx = defined($switch_path) ? $switch_path : $git_svn->{path};
3851         $pfx .= '/' if length($pfx);
3852         while (<$ls>) {
3853                 chomp;
3854                 s/\A100644 blob $empty_blob\t//o or next;
3855                 unless ($printed_warning) {
3856                         print STDERR "Scanning for empty symlinks, ",
3857                                      "this may take a while if you have ",
3858                                      "many empty files\n",
3859                                      "You may disable this with `",
3860                                      "git config svn.brokenSymlinkWorkaround ",
3861                                      "false'.\n",
3862                                      "This may be done in a different ",
3863                                      "terminal without restarting ",
3864                                      "git svn\n";
3865                         $printed_warning = 1;
3866                 }
3867                 my $path = $_;
3868                 my (undef, $props) =
3869                                $git_svn->ra->get_file($pfx.$path, $rev, undef);
3870                 if ($props->{'svn:special'}) {
3871                         $ret{$path} = 1;
3872                 }
3873         }
3874         command_close_pipe($ls, $ctx);
3875         \%ret;
3876 }
3877
3878 # returns true if a given path is inside a ".git" directory
3879 sub in_dot_git {
3880         $_[0] =~ m{(?:^|/)\.git(?:/|$)};
3881 }
3882
3883 # return value: 0 -- don't ignore, 1 -- ignore
3884 sub is_path_ignored {
3885         my ($self, $path) = @_;
3886         return 1 if in_dot_git($path);
3887         return 1 if defined($self->{ignore_regex}) &&
3888                     $path =~ m!$self->{ignore_regex}!;
3889         return 0 unless defined($_ignore_regex);
3890         return 1 if $path =~ m!$_ignore_regex!o;
3891         return 0;
3892 }
3893
3894 sub set_path_strip {
3895         my ($self, $path) = @_;
3896         $self->{path_strip} = qr/^\Q$path\E(\/|$)/ if length $path;
3897 }
3898
3899 sub open_root {
3900         { path => '' };
3901 }
3902
3903 sub open_directory {
3904         my ($self, $path, $pb, $rev) = @_;
3905         { path => $path };
3906 }
3907
3908 sub git_path {
3909         my ($self, $path) = @_;
3910         if ($self->{path_strip}) {
3911                 $path =~ s!$self->{path_strip}!! or
3912                   die "Failed to strip path '$path' ($self->{path_strip})\n";
3913         }
3914         $path;
3915 }
3916
3917 sub delete_entry {
3918         my ($self, $path, $rev, $pb) = @_;
3919         return undef if $self->is_path_ignored($path);
3920
3921         my $gpath = $self->git_path($path);
3922         return undef if ($gpath eq '');
3923
3924         # remove entire directories.
3925         my ($tree) = (command('ls-tree', '-z', $self->{c}, "./$gpath")
3926                          =~ /\A040000 tree ([a-f\d]{40})\t\Q$gpath\E\0/);
3927         if ($tree) {
3928                 my ($ls, $ctx) = command_output_pipe(qw/ls-tree
3929                                                      -r --name-only -z/,
3930                                                      $tree);
3931                 local $/ = "\0";
3932                 while (<$ls>) {
3933                         chomp;
3934                         my $rmpath = "$gpath/$_";
3935                         $self->{gii}->remove($rmpath);
3936                         print "\tD\t$rmpath\n" unless $::_q;
3937                 }
3938                 print "\tD\t$gpath/\n" unless $::_q;
3939                 command_close_pipe($ls, $ctx);
3940         } else {
3941                 $self->{gii}->remove($gpath);
3942                 print "\tD\t$gpath\n" unless $::_q;
3943         }
3944         $self->{empty}->{$path} = 0;
3945         undef;
3946 }
3947
3948 sub open_file {
3949         my ($self, $path, $pb, $rev) = @_;
3950         my ($mode, $blob);
3951
3952         goto out if $self->is_path_ignored($path);
3953
3954         my $gpath = $self->git_path($path);
3955         ($mode, $blob) = (command('ls-tree', '-z', $self->{c}, "./$gpath")
3956                              =~ /\A(\d{6}) blob ([a-f\d]{40})\t\Q$gpath\E\0/);
3957         unless (defined $mode && defined $blob) {
3958                 die "$path was not found in commit $self->{c} (r$rev)\n";
3959         }
3960         if ($mode eq '100644' && $self->{empty_symlinks}->{$path}) {
3961                 $mode = '120000';
3962         }
3963 out:
3964         { path => $path, mode_a => $mode, mode_b => $mode, blob => $blob,
3965           pool => SVN::Pool->new, action => 'M' };
3966 }
3967
3968 sub add_file {
3969         my ($self, $path, $pb, $cp_path, $cp_rev) = @_;
3970         my $mode;
3971
3972         if (!$self->is_path_ignored($path)) {
3973                 my ($dir, $file) = ($path =~ m#^(.*?)/?([^/]+)$#);
3974                 delete $self->{empty}->{$dir};
3975                 $mode = '100644';
3976         }
3977         { path => $path, mode_a => $mode, mode_b => $mode,
3978           pool => SVN::Pool->new, action => 'A' };
3979 }
3980
3981 sub add_directory {
3982         my ($self, $path, $cp_path, $cp_rev) = @_;
3983         goto out if $self->is_path_ignored($path);
3984         my $gpath = $self->git_path($path);
3985         if ($gpath eq '') {
3986                 my ($ls, $ctx) = command_output_pipe(qw/ls-tree
3987                                                      -r --name-only -z/,
3988                                                      $self->{c});
3989                 local $/ = "\0";
3990                 while (<$ls>) {
3991                         chomp;
3992                         $self->{gii}->remove($_);
3993                         print "\tD\t$_\n" unless $::_q;
3994                 }
3995                 command_close_pipe($ls, $ctx);
3996                 $self->{empty}->{$path} = 0;
3997         }
3998         my ($dir, $file) = ($path =~ m#^(.*?)/?([^/]+)$#);
3999         delete $self->{empty}->{$dir};
4000         $self->{empty}->{$path} = 1;
4001 out:
4002         { path => $path };
4003 }
4004
4005 sub change_dir_prop {
4006         my ($self, $db, $prop, $value) = @_;
4007         return undef if $self->is_path_ignored($db->{path});
4008         $self->{dir_prop}->{$db->{path}} ||= {};
4009         $self->{dir_prop}->{$db->{path}}->{$prop} = $value;
4010         undef;
4011 }
4012
4013 sub absent_directory {
4014         my ($self, $path, $pb) = @_;
4015         return undef if $self->is_path_ignored($path);
4016         $self->{absent_dir}->{$pb->{path}} ||= [];
4017         push @{$self->{absent_dir}->{$pb->{path}}}, $path;
4018         undef;
4019 }
4020
4021 sub absent_file {
4022         my ($self, $path, $pb) = @_;
4023         return undef if $self->is_path_ignored($path);
4024         $self->{absent_file}->{$pb->{path}} ||= [];
4025         push @{$self->{absent_file}->{$pb->{path}}}, $path;
4026         undef;
4027 }
4028
4029 sub change_file_prop {
4030         my ($self, $fb, $prop, $value) = @_;
4031         return undef if $self->is_path_ignored($fb->{path});
4032         if ($prop eq 'svn:executable') {
4033                 if ($fb->{mode_b} != 120000) {
4034                         $fb->{mode_b} = defined $value ? 100755 : 100644;
4035                 }
4036         } elsif ($prop eq 'svn:special') {
4037                 $fb->{mode_b} = defined $value ? 120000 : 100644;
4038         } else {
4039                 $self->{file_prop}->{$fb->{path}} ||= {};
4040                 $self->{file_prop}->{$fb->{path}}->{$prop} = $value;
4041         }
4042         undef;
4043 }
4044
4045 sub apply_textdelta {
4046         my ($self, $fb, $exp) = @_;
4047         return undef if $self->is_path_ignored($fb->{path});
4048         my $fh = $::_repository->temp_acquire('svn_delta');
4049         # $fh gets auto-closed() by SVN::TxDelta::apply(),
4050         # (but $base does not,) so dup() it for reading in close_file
4051         open my $dup, '<&', $fh or croak $!;
4052         my $base = $::_repository->temp_acquire('git_blob');
4053
4054         if ($fb->{blob}) {
4055                 my ($base_is_link, $size);
4056
4057                 if ($fb->{mode_a} eq '120000' &&
4058                     ! $self->{empty_symlinks}->{$fb->{path}}) {
4059                         print $base 'link ' or die "print $!\n";
4060                         $base_is_link = 1;
4061                 }
4062         retry:
4063                 $size = $::_repository->cat_blob($fb->{blob}, $base);
4064                 die "Failed to read object $fb->{blob}" if ($size < 0);
4065
4066                 if (defined $exp) {
4067                         seek $base, 0, 0 or croak $!;
4068                         my $got = ::md5sum($base);
4069                         if ($got ne $exp) {
4070                                 my $err = "Checksum mismatch: ".
4071                                        "$fb->{path} $fb->{blob}\n" .
4072                                        "expected: $exp\n" .
4073                                        "     got: $got\n";
4074                                 if ($base_is_link) {
4075                                         warn $err,
4076                                              "Retrying... (possibly ",
4077                                              "a bad symlink from SVN)\n";
4078                                         $::_repository->temp_reset($base);
4079                                         $base_is_link = 0;
4080                                         goto retry;
4081                                 }
4082                                 die $err;
4083                         }
4084                 }
4085         }
4086         seek $base, 0, 0 or croak $!;
4087         $fb->{fh} = $fh;
4088         $fb->{base} = $base;
4089         [ SVN::TxDelta::apply($base, $dup, undef, $fb->{path}, $fb->{pool}) ];
4090 }
4091
4092 sub close_file {
4093         my ($self, $fb, $exp) = @_;
4094         return undef if $self->is_path_ignored($fb->{path});
4095
4096         my $hash;
4097         my $path = $self->git_path($fb->{path});
4098         if (my $fh = $fb->{fh}) {
4099                 if (defined $exp) {
4100                         seek($fh, 0, 0) or croak $!;
4101                         my $got = ::md5sum($fh);
4102                         if ($got ne $exp) {
4103                                 die "Checksum mismatch: $path\n",
4104                                     "expected: $exp\n    got: $got\n";
4105                         }
4106                 }
4107                 if ($fb->{mode_b} == 120000) {
4108                         sysseek($fh, 0, 0) or croak $!;
4109                         my $rd = sysread($fh, my $buf, 5);
4110
4111                         if (!defined $rd) {
4112                                 croak "sysread: $!\n";
4113                         } elsif ($rd == 0) {
4114                                 warn "$path has mode 120000",
4115                                      " but it points to nothing\n",
4116                                      "converting to an empty file with mode",
4117                                      " 100644\n";
4118                                 $fb->{mode_b} = '100644';
4119                         } elsif ($buf ne 'link ') {
4120                                 warn "$path has mode 120000",
4121                                      " but is not a link\n";
4122                         } else {
4123                                 my $tmp_fh = $::_repository->temp_acquire(
4124                                         'svn_hash');
4125                                 my $res;
4126                                 while ($res = sysread($fh, my $str, 1024)) {
4127                                         my $out = syswrite($tmp_fh, $str, $res);
4128                                         defined($out) && $out == $res
4129                                                 or croak("write ",
4130                                                         Git::temp_path($tmp_fh),
4131                                                         ": $!\n");
4132                                 }
4133                                 defined $res or croak $!;
4134
4135                                 ($fh, $tmp_fh) = ($tmp_fh, $fh);
4136                                 Git::temp_release($tmp_fh, 1);
4137                         }
4138                 }
4139
4140                 $hash = $::_repository->hash_and_insert_object(
4141                                 Git::temp_path($fh));
4142                 $hash =~ /^[a-f\d]{40}$/ or die "not a sha1: $hash\n";
4143
4144                 Git::temp_release($fb->{base}, 1);
4145                 Git::temp_release($fh, 1);
4146         } else {
4147                 $hash = $fb->{blob} or die "no blob information\n";
4148         }
4149         $fb->{pool}->clear;
4150         $self->{gii}->update($fb->{mode_b}, $hash, $path) or croak $!;
4151         print "\t$fb->{action}\t$path\n" if $fb->{action} && ! $::_q;
4152         undef;
4153 }
4154
4155 sub abort_edit {
4156         my $self = shift;
4157         $self->{nr} = $self->{gii}->{nr};
4158         delete $self->{gii};
4159         $self->SUPER::abort_edit(@_);
4160 }
4161
4162 sub close_edit {
4163         my $self = shift;
4164         $self->{git_commit_ok} = 1;
4165         $self->{nr} = $self->{gii}->{nr};
4166         delete $self->{gii};
4167         $self->SUPER::close_edit(@_);
4168 }
4169
4170 package SVN::Git::Editor;
4171 use vars qw/@ISA $_rmdir $_cp_similarity $_find_copies_harder $_rename_limit/;
4172 use strict;
4173 use warnings;
4174 use Carp qw/croak/;
4175 use IO::File;
4176
4177 sub new {
4178         my ($class, $opts) = @_;
4179         foreach (qw/svn_path r ra tree_a tree_b log editor_cb/) {
4180                 die "$_ required!\n" unless (defined $opts->{$_});
4181         }
4182
4183         my $pool = SVN::Pool->new;
4184         my $mods = generate_diff($opts->{tree_a}, $opts->{tree_b});
4185         my $types = check_diff_paths($opts->{ra}, $opts->{svn_path},
4186                                      $opts->{r}, $mods);
4187
4188         # $opts->{ra} functions should not be used after this:
4189         my @ce  = $opts->{ra}->get_commit_editor($opts->{log},
4190                                                 $opts->{editor_cb}, $pool);
4191         my $self = SVN::Delta::Editor->new(@ce, $pool);
4192         bless $self, $class;
4193         foreach (qw/svn_path r tree_a tree_b/) {
4194                 $self->{$_} = $opts->{$_};
4195         }
4196         $self->{url} = $opts->{ra}->{url};
4197         $self->{mods} = $mods;
4198         $self->{types} = $types;
4199         $self->{pool} = $pool;
4200         $self->{bat} = { '' => $self->open_root($self->{r}, $self->{pool}) };
4201         $self->{rm} = { };
4202         $self->{path_prefix} = length $self->{svn_path} ?
4203                                "$self->{svn_path}/" : '';
4204         $self->{config} = $opts->{config};
4205         return $self;
4206 }
4207
4208 sub generate_diff {
4209         my ($tree_a, $tree_b) = @_;
4210         my @diff_tree = qw(diff-tree -z -r);
4211         if ($_cp_similarity) {
4212                 push @diff_tree, "-C$_cp_similarity";
4213         } else {
4214                 push @diff_tree, '-C';
4215         }
4216         push @diff_tree, '--find-copies-harder' if $_find_copies_harder;
4217         push @diff_tree, "-l$_rename_limit" if defined $_rename_limit;
4218         push @diff_tree, $tree_a, $tree_b;
4219         my ($diff_fh, $ctx) = command_output_pipe(@diff_tree);
4220         local $/ = "\0";
4221         my $state = 'meta';
4222         my @mods;
4223         while (<$diff_fh>) {
4224                 chomp $_; # this gets rid of the trailing "\0"
4225                 if ($state eq 'meta' && /^:(\d{6})\s(\d{6})\s
4226                                         ($::sha1)\s($::sha1)\s
4227                                         ([MTCRAD])\d*$/xo) {
4228                         push @mods, {   mode_a => $1, mode_b => $2,
4229                                         sha1_a => $3, sha1_b => $4,
4230                                         chg => $5 };
4231                         if ($5 =~ /^(?:C|R)$/) {
4232                                 $state = 'file_a';
4233                         } else {
4234                                 $state = 'file_b';
4235                         }
4236                 } elsif ($state eq 'file_a') {
4237                         my $x = $mods[$#mods] or croak "Empty array\n";
4238                         if ($x->{chg} !~ /^(?:C|R)$/) {
4239                                 croak "Error parsing $_, $x->{chg}\n";
4240                         }
4241                         $x->{file_a} = $_;
4242                         $state = 'file_b';
4243                 } elsif ($state eq 'file_b') {
4244                         my $x = $mods[$#mods] or croak "Empty array\n";
4245                         if (exists $x->{file_a} && $x->{chg} !~ /^(?:C|R)$/) {
4246                                 croak "Error parsing $_, $x->{chg}\n";
4247                         }
4248                         if (!exists $x->{file_a} && $x->{chg} =~ /^(?:C|R)$/) {
4249                                 croak "Error parsing $_, $x->{chg}\n";
4250                         }
4251                         $x->{file_b} = $_;
4252                         $state = 'meta';
4253                 } else {
4254                         croak "Error parsing $_\n";
4255                 }
4256         }
4257         command_close_pipe($diff_fh, $ctx);
4258         \@mods;
4259 }
4260
4261 sub check_diff_paths {
4262         my ($ra, $pfx, $rev, $mods) = @_;
4263         my %types;
4264         $pfx .= '/' if length $pfx;
4265
4266         sub type_diff_paths {
4267                 my ($ra, $types, $path, $rev) = @_;
4268                 my @p = split m#/+#, $path;
4269                 my $c = shift @p;
4270                 unless (defined $types->{$c}) {
4271                         $types->{$c} = $ra->check_path($c, $rev);
4272                 }
4273                 while (@p) {
4274                         $c .= '/' . shift @p;
4275                         next if defined $types->{$c};
4276                         $types->{$c} = $ra->check_path($c, $rev);
4277                 }
4278         }
4279
4280         foreach my $m (@$mods) {
4281                 foreach my $f (qw/file_a file_b/) {
4282                         next unless defined $m->{$f};
4283                         my ($dir) = ($m->{$f} =~ m#^(.*?)/?(?:[^/]+)$#);
4284                         if (length $pfx.$dir && ! defined $types{$dir}) {
4285                                 type_diff_paths($ra, \%types, $pfx.$dir, $rev);
4286                         }
4287                 }
4288         }
4289         \%types;
4290 }
4291
4292 sub split_path {
4293         return ($_[0] =~ m#^(.*?)/?([^/]+)$#);
4294 }
4295
4296 sub repo_path {
4297         my ($self, $path) = @_;
4298         $self->{path_prefix}.(defined $path ? $path : '');
4299 }
4300
4301 sub url_path {
4302         my ($self, $path) = @_;
4303         if ($self->{url} =~ m#^https?://#) {
4304                 $path =~ s!([^~a-zA-Z0-9_./-])!uc sprintf("%%%02x",ord($1))!eg;
4305         }
4306         $self->{url} . '/' . $self->repo_path($path);
4307 }
4308
4309 sub rmdirs {
4310         my ($self) = @_;
4311         my $rm = $self->{rm};
4312         delete $rm->{''}; # we never delete the url we're tracking
4313         return unless %$rm;
4314
4315         foreach (keys %$rm) {
4316                 my @d = split m#/#, $_;
4317                 my $c = shift @d;
4318                 $rm->{$c} = 1;
4319                 while (@d) {
4320                         $c .= '/' . shift @d;
4321                         $rm->{$c} = 1;
4322                 }
4323         }
4324         delete $rm->{$self->{svn_path}};
4325         delete $rm->{''}; # we never delete the url we're tracking
4326         return unless %$rm;
4327
4328         my ($fh, $ctx) = command_output_pipe(qw/ls-tree --name-only -r -z/,
4329                                              $self->{tree_b});
4330         local $/ = "\0";
4331         while (<$fh>) {
4332                 chomp;
4333                 my @dn = split m#/#, $_;
4334                 while (pop @dn) {
4335                         delete $rm->{join '/', @dn};
4336                 }
4337                 unless (%$rm) {
4338                         close $fh;
4339                         return;
4340                 }
4341         }
4342         command_close_pipe($fh, $ctx);
4343
4344         my ($r, $p, $bat) = ($self->{r}, $self->{pool}, $self->{bat});
4345         foreach my $d (sort { $b =~ tr#/#/# <=> $a =~ tr#/#/# } keys %$rm) {
4346                 $self->close_directory($bat->{$d}, $p);
4347                 my ($dn) = ($d =~ m#^(.*?)/?(?:[^/]+)$#);
4348                 print "\tD+\t$d/\n" unless $::_q;
4349                 $self->SUPER::delete_entry($d, $r, $bat->{$dn}, $p);
4350                 delete $bat->{$d};
4351         }
4352 }
4353
4354 sub open_or_add_dir {
4355         my ($self, $full_path, $baton) = @_;
4356         my $t = $self->{types}->{$full_path};
4357         if (!defined $t) {
4358                 die "$full_path not known in r$self->{r} or we have a bug!\n";
4359         }
4360         {
4361                 no warnings 'once';
4362                 # SVN::Node::none and SVN::Node::file are used only once,
4363                 # so we're shutting up Perl's warnings about them.
4364                 if ($t == $SVN::Node::none) {
4365                         return $self->add_directory($full_path, $baton,
4366                             undef, -1, $self->{pool});
4367                 } elsif ($t == $SVN::Node::dir) {
4368                         return $self->open_directory($full_path, $baton,
4369                             $self->{r}, $self->{pool});
4370                 } # no warnings 'once'
4371                 print STDERR "$full_path already exists in repository at ",
4372                     "r$self->{r} and it is not a directory (",
4373                     ($t == $SVN::Node::file ? 'file' : 'unknown'),"/$t)\n";
4374         } # no warnings 'once'
4375         exit 1;
4376 }
4377
4378 sub ensure_path {
4379         my ($self, $path) = @_;
4380         my $bat = $self->{bat};
4381         my $repo_path = $self->repo_path($path);
4382         return $bat->{''} unless (length $repo_path);
4383         my @p = split m#/+#, $repo_path;
4384         my $c = shift @p;
4385         $bat->{$c} ||= $self->open_or_add_dir($c, $bat->{''});
4386         while (@p) {
4387                 my $c0 = $c;
4388                 $c .= '/' . shift @p;
4389                 $bat->{$c} ||= $self->open_or_add_dir($c, $bat->{$c0});
4390         }
4391         return $bat->{$c};
4392 }
4393
4394 # Subroutine to convert a globbing pattern to a regular expression.
4395 # From perl cookbook.
4396 sub glob2pat {
4397         my $globstr = shift;
4398         my %patmap = ('*' => '.*', '?' => '.', '[' => '[', ']' => ']');
4399         $globstr =~ s{(.)} { $patmap{$1} || "\Q$1" }ge;
4400         return '^' . $globstr . '$';
4401 }
4402
4403 sub check_autoprop {
4404         my ($self, $pattern, $properties, $file, $fbat) = @_;
4405         # Convert the globbing pattern to a regular expression.
4406         my $regex = glob2pat($pattern);
4407         # Check if the pattern matches the file name.
4408         if($file =~ m/($regex)/) {
4409                 # Parse the list of properties to set.
4410                 my @props = split(/;/, $properties);
4411                 foreach my $prop (@props) {
4412                         # Parse 'name=value' syntax and set the property.
4413                         if ($prop =~ /([^=]+)=(.*)/) {
4414                                 my ($n,$v) = ($1,$2);
4415                                 for ($n, $v) {
4416                                         s/^\s+//; s/\s+$//;
4417                                 }
4418                                 $self->change_file_prop($fbat, $n, $v);
4419                         }
4420                 }
4421         }
4422 }
4423
4424 sub apply_autoprops {
4425         my ($self, $file, $fbat) = @_;
4426         my $conf_t = ${$self->{config}}{'config'};
4427         no warnings 'once';
4428         # Check [miscellany]/enable-auto-props in svn configuration.
4429         if (SVN::_Core::svn_config_get_bool(
4430                 $conf_t,
4431                 $SVN::_Core::SVN_CONFIG_SECTION_MISCELLANY,
4432                 $SVN::_Core::SVN_CONFIG_OPTION_ENABLE_AUTO_PROPS,
4433                 0)) {
4434                 # Auto-props are enabled.  Enumerate them to look for matches.
4435                 my $callback = sub {
4436                         $self->check_autoprop($_[0], $_[1], $file, $fbat);
4437                 };
4438                 SVN::_Core::svn_config_enumerate(
4439                         $conf_t,
4440                         $SVN::_Core::SVN_CONFIG_SECTION_AUTO_PROPS,
4441                         $callback);
4442         }
4443 }
4444
4445 sub A {
4446         my ($self, $m) = @_;
4447         my ($dir, $file) = split_path($m->{file_b});
4448         my $pbat = $self->ensure_path($dir);
4449         my $fbat = $self->add_file($self->repo_path($m->{file_b}), $pbat,
4450                                         undef, -1);
4451         print "\tA\t$m->{file_b}\n" unless $::_q;
4452         $self->apply_autoprops($file, $fbat);
4453         $self->chg_file($fbat, $m);
4454         $self->close_file($fbat,undef,$self->{pool});
4455 }
4456
4457 sub C {
4458         my ($self, $m) = @_;
4459         my ($dir, $file) = split_path($m->{file_b});
4460         my $pbat = $self->ensure_path($dir);
4461         my $fbat = $self->add_file($self->repo_path($m->{file_b}), $pbat,
4462                                 $self->url_path($m->{file_a}), $self->{r});
4463         print "\tC\t$m->{file_a} => $m->{file_b}\n" unless $::_q;
4464         $self->chg_file($fbat, $m);
4465         $self->close_file($fbat,undef,$self->{pool});
4466 }
4467
4468 sub delete_entry {
4469         my ($self, $path, $pbat) = @_;
4470         my $rpath = $self->repo_path($path);
4471         my ($dir, $file) = split_path($rpath);
4472         $self->{rm}->{$dir} = 1;
4473         $self->SUPER::delete_entry($rpath, $self->{r}, $pbat, $self->{pool});
4474 }
4475
4476 sub R {
4477         my ($self, $m) = @_;
4478         my ($dir, $file) = split_path($m->{file_b});
4479         my $pbat = $self->ensure_path($dir);
4480         my $fbat = $self->add_file($self->repo_path($m->{file_b}), $pbat,
4481                                 $self->url_path($m->{file_a}), $self->{r});
4482         print "\tR\t$m->{file_a} => $m->{file_b}\n" unless $::_q;
4483         $self->apply_autoprops($file, $fbat);
4484         $self->chg_file($fbat, $m);
4485         $self->close_file($fbat,undef,$self->{pool});
4486
4487         ($dir, $file) = split_path($m->{file_a});
4488         $pbat = $self->ensure_path($dir);
4489         $self->delete_entry($m->{file_a}, $pbat);
4490 }
4491
4492 sub M {
4493         my ($self, $m) = @_;
4494         my ($dir, $file) = split_path($m->{file_b});
4495         my $pbat = $self->ensure_path($dir);
4496         my $fbat = $self->open_file($self->repo_path($m->{file_b}),
4497                                 $pbat,$self->{r},$self->{pool});
4498         print "\t$m->{chg}\t$m->{file_b}\n" unless $::_q;
4499         $self->chg_file($fbat, $m);
4500         $self->close_file($fbat,undef,$self->{pool});
4501 }
4502
4503 sub T { shift->M(@_) }
4504
4505 sub change_file_prop {
4506         my ($self, $fbat, $pname, $pval) = @_;
4507         $self->SUPER::change_file_prop($fbat, $pname, $pval, $self->{pool});
4508 }
4509
4510 sub _chg_file_get_blob ($$$$) {
4511         my ($self, $fbat, $m, $which) = @_;
4512         my $fh = $::_repository->temp_acquire("git_blob_$which");
4513         if ($m->{"mode_$which"} =~ /^120/) {
4514                 print $fh 'link ' or croak $!;
4515                 $self->change_file_prop($fbat,'svn:special','*');
4516         } elsif ($m->{mode_a} =~ /^120/ && $m->{"mode_$which"} !~ /^120/) {
4517                 $self->change_file_prop($fbat,'svn:special',undef);
4518         }
4519         my $blob = $m->{"sha1_$which"};
4520         return ($fh,) if ($blob =~ /^0{40}$/);
4521         my $size = $::_repository->cat_blob($blob, $fh);
4522         croak "Failed to read object $blob" if ($size < 0);
4523         $fh->flush == 0 or croak $!;
4524         seek $fh, 0, 0 or croak $!;
4525
4526         my $exp = ::md5sum($fh);
4527         seek $fh, 0, 0 or croak $!;
4528         return ($fh, $exp);
4529 }
4530
4531 sub chg_file {
4532         my ($self, $fbat, $m) = @_;
4533         if ($m->{mode_b} =~ /755$/ && $m->{mode_a} !~ /755$/) {
4534                 $self->change_file_prop($fbat,'svn:executable','*');
4535         } elsif ($m->{mode_b} !~ /755$/ && $m->{mode_a} =~ /755$/) {
4536                 $self->change_file_prop($fbat,'svn:executable',undef);
4537         }
4538         my ($fh_a, $exp_a) = _chg_file_get_blob $self, $fbat, $m, 'a';
4539         my ($fh_b, $exp_b) = _chg_file_get_blob $self, $fbat, $m, 'b';
4540         my $pool = SVN::Pool->new;
4541         my $atd = $self->apply_textdelta($fbat, $exp_a, $pool);
4542         if (-s $fh_a) {
4543                 my $txstream = SVN::TxDelta::new ($fh_a, $fh_b, $pool);
4544                 my $res = SVN::TxDelta::send_txstream($txstream, @$atd, $pool);
4545                 if (defined $res) {
4546                         die "Unexpected result from send_txstream: $res\n",
4547                             "(SVN::Core::VERSION: $SVN::Core::VERSION)\n";
4548                 }
4549         } else {
4550                 my $got = SVN::TxDelta::send_stream($fh_b, @$atd, $pool);
4551                 die "Checksum mismatch\nexpected: $exp_b\ngot: $got\n"
4552                     if ($got ne $exp_b);
4553         }
4554         Git::temp_release($fh_b, 1);
4555         Git::temp_release($fh_a, 1);
4556         $pool->clear;
4557 }
4558
4559 sub D {
4560         my ($self, $m) = @_;
4561         my ($dir, $file) = split_path($m->{file_b});
4562         my $pbat = $self->ensure_path($dir);
4563         print "\tD\t$m->{file_b}\n" unless $::_q;
4564         $self->delete_entry($m->{file_b}, $pbat);
4565 }
4566
4567 sub close_edit {
4568         my ($self) = @_;
4569         my ($p,$bat) = ($self->{pool}, $self->{bat});
4570         foreach (sort { $b =~ tr#/#/# <=> $a =~ tr#/#/# } keys %$bat) {
4571                 next if $_ eq '';
4572                 $self->close_directory($bat->{$_}, $p);
4573         }
4574         $self->close_directory($bat->{''}, $p);
4575         $self->SUPER::close_edit($p);
4576         $p->clear;
4577 }
4578
4579 sub abort_edit {
4580         my ($self) = @_;
4581         $self->SUPER::abort_edit($self->{pool});
4582 }
4583
4584 sub DESTROY {
4585         my $self = shift;
4586         $self->SUPER::DESTROY(@_);
4587         $self->{pool}->clear;
4588 }
4589
4590 # this drives the editor
4591 sub apply_diff {
4592         my ($self) = @_;
4593         my $mods = $self->{mods};
4594         my %o = ( D => 1, R => 0, C => -1, A => 3, M => 3, T => 3 );
4595         foreach my $m (sort { $o{$a->{chg}} <=> $o{$b->{chg}} } @$mods) {
4596                 my $f = $m->{chg};
4597                 if (defined $o{$f}) {
4598                         $self->$f($m);
4599                 } else {
4600                         fatal("Invalid change type: $f");
4601                 }
4602         }
4603         $self->rmdirs if $_rmdir;
4604         if (@$mods == 0) {
4605                 $self->abort_edit;
4606         } else {
4607                 $self->close_edit;
4608         }
4609         return scalar @$mods;
4610 }
4611
4612 package Git::SVN::Ra;
4613 use vars qw/@ISA $config_dir $_log_window_size/;
4614 use strict;
4615 use warnings;
4616 my ($ra_invalid, $can_do_switch, %ignored_err, $RA);
4617
4618 BEGIN {
4619         # enforce temporary pool usage for some simple functions
4620         no strict 'refs';
4621         for my $f (qw/rev_proplist get_latest_revnum get_uuid get_repos_root
4622                       get_file/) {
4623                 my $SUPER = "SUPER::$f";
4624                 *$f = sub {
4625                         my $self = shift;
4626                         my $pool = SVN::Pool->new;
4627                         my @ret = $self->$SUPER(@_,$pool);
4628                         $pool->clear;
4629                         wantarray ? @ret : $ret[0];
4630                 };
4631         }
4632 }
4633
4634 sub _auth_providers () {
4635         [
4636           SVN::Client::get_simple_provider(),
4637           SVN::Client::get_ssl_server_trust_file_provider(),
4638           SVN::Client::get_simple_prompt_provider(
4639             \&Git::SVN::Prompt::simple, 2),
4640           SVN::Client::get_ssl_client_cert_file_provider(),
4641           SVN::Client::get_ssl_client_cert_prompt_provider(
4642             \&Git::SVN::Prompt::ssl_client_cert, 2),
4643           SVN::Client::get_ssl_client_cert_pw_file_provider(),
4644           SVN::Client::get_ssl_client_cert_pw_prompt_provider(
4645             \&Git::SVN::Prompt::ssl_client_cert_pw, 2),
4646           SVN::Client::get_username_provider(),
4647           SVN::Client::get_ssl_server_trust_prompt_provider(
4648             \&Git::SVN::Prompt::ssl_server_trust),
4649           SVN::Client::get_username_prompt_provider(
4650             \&Git::SVN::Prompt::username, 2)
4651         ]
4652 }
4653
4654 sub escape_uri_only {
4655         my ($uri) = @_;
4656         my @tmp;
4657         foreach (split m{/}, $uri) {
4658                 s/([^~\w.%+-]|%(?![a-fA-F0-9]{2}))/sprintf("%%%02X",ord($1))/eg;
4659                 push @tmp, $_;
4660         }
4661         join('/', @tmp);
4662 }
4663
4664 sub escape_url {
4665         my ($url) = @_;
4666         if ($url =~ m#^(https?)://([^/]+)(.*)$#) {
4667                 my ($scheme, $domain, $uri) = ($1, $2, escape_uri_only($3));
4668                 $url = "$scheme://$domain$uri";
4669         }
4670         $url;
4671 }
4672
4673 sub new {
4674         my ($class, $url) = @_;
4675         $url =~ s!/+$!!;
4676         return $RA if ($RA && $RA->{url} eq $url);
4677
4678         SVN::_Core::svn_config_ensure($config_dir, undef);
4679         my ($baton, $callbacks) = SVN::Core::auth_open_helper(_auth_providers);
4680         my $config = SVN::Core::config_get_config($config_dir);
4681         $RA = undef;
4682         my $dont_store_passwords = 1;
4683         my $conf_t = ${$config}{'config'};
4684         {
4685                 no warnings 'once';
4686                 # The usage of $SVN::_Core::SVN_CONFIG_* variables
4687                 # produces warnings that variables are used only once.
4688                 # I had not found the better way to shut them up, so
4689                 # the warnings of type 'once' are disabled in this block.
4690                 if (SVN::_Core::svn_config_get_bool($conf_t,
4691                     $SVN::_Core::SVN_CONFIG_SECTION_AUTH,
4692                     $SVN::_Core::SVN_CONFIG_OPTION_STORE_PASSWORDS,
4693                     1) == 0) {
4694                         SVN::_Core::svn_auth_set_parameter($baton,
4695                             $SVN::_Core::SVN_AUTH_PARAM_DONT_STORE_PASSWORDS,
4696                             bless (\$dont_store_passwords, "_p_void"));
4697                 }
4698                 if (SVN::_Core::svn_config_get_bool($conf_t,
4699                     $SVN::_Core::SVN_CONFIG_SECTION_AUTH,
4700                     $SVN::_Core::SVN_CONFIG_OPTION_STORE_AUTH_CREDS,
4701                     1) == 0) {
4702                         $Git::SVN::Prompt::_no_auth_cache = 1;
4703                 }
4704         } # no warnings 'once'
4705         my $self = SVN::Ra->new(url => escape_url($url), auth => $baton,
4706                               config => $config,
4707                               pool => SVN::Pool->new,
4708                               auth_provider_callbacks => $callbacks);
4709         $self->{url} = $url;
4710         $self->{svn_path} = $url;
4711         $self->{repos_root} = $self->get_repos_root;
4712         $self->{svn_path} =~ s#^\Q$self->{repos_root}\E(/|$)##;
4713         $self->{cache} = { check_path => { r => 0, data => {} },
4714                            get_dir => { r => 0, data => {} } };
4715         $RA = bless $self, $class;
4716 }
4717
4718 sub check_path {
4719         my ($self, $path, $r) = @_;
4720         my $cache = $self->{cache}->{check_path};
4721         if ($r == $cache->{r} && exists $cache->{data}->{$path}) {
4722                 return $cache->{data}->{$path};
4723         }
4724         my $pool = SVN::Pool->new;
4725         my $t = $self->SUPER::check_path($path, $r, $pool);
4726         $pool->clear;
4727         if ($r != $cache->{r}) {
4728                 %{$cache->{data}} = ();
4729                 $cache->{r} = $r;
4730         }
4731         $cache->{data}->{$path} = $t;
4732 }
4733
4734 sub get_dir {
4735         my ($self, $dir, $r) = @_;
4736         my $cache = $self->{cache}->{get_dir};
4737         if ($r == $cache->{r}) {
4738                 if (my $x = $cache->{data}->{$dir}) {
4739                         return wantarray ? @$x : $x->[0];
4740                 }
4741         }
4742         my $pool = SVN::Pool->new;
4743         my ($d, undef, $props) = $self->SUPER::get_dir($dir, $r, $pool);
4744         my %dirents = map { $_ => { kind => $d->{$_}->kind } } keys %$d;
4745         $pool->clear;
4746         if ($r != $cache->{r}) {
4747                 %{$cache->{data}} = ();
4748                 $cache->{r} = $r;
4749         }
4750         $cache->{data}->{$dir} = [ \%dirents, $r, $props ];
4751         wantarray ? (\%dirents, $r, $props) : \%dirents;
4752 }
4753
4754 sub DESTROY {
4755         # do not call the real DESTROY since we store ourselves in $RA
4756 }
4757
4758 # get_log(paths, start, end, limit,
4759 #         discover_changed_paths, strict_node_history, receiver)
4760 sub get_log {
4761         my ($self, @args) = @_;
4762         my $pool = SVN::Pool->new;
4763
4764         # svn_log_changed_path_t objects passed to get_log are likely to be
4765         # overwritten even if only the refs are copied to an external variable,
4766         # so we should dup the structures in their entirety.  Using an
4767         # externally passed pool (instead of our temporary and quickly cleared
4768         # pool in Git::SVN::Ra) does not help matters at all...
4769         my $receiver = pop @args;
4770         my $prefix = "/".$self->{svn_path};
4771         $prefix =~ s#/+($)##;
4772         my $prefix_regex = qr#^\Q$prefix\E#;
4773         push(@args, sub {
4774                 my ($paths) = $_[0];
4775                 return &$receiver(@_) unless $paths;
4776                 $_[0] = ();
4777                 foreach my $p (keys %$paths) {
4778                         my $i = $paths->{$p};
4779                         # Make path relative to our url, not repos_root
4780                         $p =~ s/$prefix_regex//;
4781                         my %s = map { $_ => $i->$_; }
4782                                 qw/copyfrom_path copyfrom_rev action/;
4783                         if ($s{'copyfrom_path'}) {
4784                                 $s{'copyfrom_path'} =~ s/$prefix_regex//;
4785                         }
4786                         $_[0]{$p} = \%s;
4787                 }
4788                 &$receiver(@_);
4789         });
4790
4791
4792         # the limit parameter was not supported in SVN 1.1.x, so we
4793         # drop it.  Therefore, the receiver callback passed to it
4794         # is made aware of this limitation by being wrapped if
4795         # the limit passed to is being wrapped.
4796         if ($SVN::Core::VERSION le '1.2.0') {
4797                 my $limit = splice(@args, 3, 1);
4798                 if ($limit > 0) {
4799                         my $receiver = pop @args;
4800                         push(@args, sub { &$receiver(@_) if (--$limit >= 0) });
4801                 }
4802         }
4803         my $ret = $self->SUPER::get_log(@args, $pool);
4804         $pool->clear;
4805         $ret;
4806 }
4807
4808 sub trees_match {
4809         my ($self, $url1, $rev1, $url2, $rev2) = @_;
4810         my $ctx = SVN::Client->new(auth => _auth_providers);
4811         my $out = IO::File->new_tmpfile;
4812
4813         # older SVN (1.1.x) doesn't take $pool as the last parameter for
4814         # $ctx->diff(), so we'll create a default one
4815         my $pool = SVN::Pool->new_default_sub;
4816
4817         $ra_invalid = 1; # this will open a new SVN::Ra connection to $url1
4818         $ctx->diff([], $url1, $rev1, $url2, $rev2, 1, 1, 0, $out, $out);
4819         $out->flush;
4820         my $ret = (($out->stat)[7] == 0);
4821         close $out or croak $!;
4822
4823         $ret;
4824 }
4825
4826 sub get_commit_editor {
4827         my ($self, $log, $cb, $pool) = @_;
4828         my @lock = $SVN::Core::VERSION ge '1.2.0' ? (undef, 0) : ();
4829         $self->SUPER::get_commit_editor($log, $cb, @lock, $pool);
4830 }
4831
4832 sub gs_do_update {
4833         my ($self, $rev_a, $rev_b, $gs, $editor) = @_;
4834         my $new = ($rev_a == $rev_b);
4835         my $path = $gs->{path};
4836
4837         if ($new && -e $gs->{index}) {
4838                 unlink $gs->{index} or die
4839                   "Couldn't unlink index: $gs->{index}: $!\n";
4840         }
4841         my $pool = SVN::Pool->new;
4842         $editor->set_path_strip($path);
4843         my (@pc) = split m#/#, $path;
4844         my $reporter = $self->do_update($rev_b, (@pc ? shift @pc : ''),
4845                                         1, $editor, $pool);
4846         my @lock = $SVN::Core::VERSION ge '1.2.0' ? (undef) : ();
4847
4848         # Since we can't rely on svn_ra_reparent being available, we'll
4849         # just have to do some magic with set_path to make it so
4850         # we only want a partial path.
4851         my $sp = '';
4852         my $final = join('/', @pc);
4853         while (@pc) {
4854                 $reporter->set_path($sp, $rev_b, 0, @lock, $pool);
4855                 $sp .= '/' if length $sp;
4856                 $sp .= shift @pc;
4857         }
4858         die "BUG: '$sp' != '$final'\n" if ($sp ne $final);
4859
4860         $reporter->set_path($sp, $rev_a, $new, @lock, $pool);
4861
4862         $reporter->finish_report($pool);
4863         $pool->clear;
4864         $editor->{git_commit_ok};
4865 }
4866
4867 # this requires SVN 1.4.3 or later (do_switch didn't work before 1.4.3, and
4868 # svn_ra_reparent didn't work before 1.4)
4869 sub gs_do_switch {
4870         my ($self, $rev_a, $rev_b, $gs, $url_b, $editor) = @_;
4871         my $path = $gs->{path};
4872         my $pool = SVN::Pool->new;
4873
4874         my $full_url = $self->{url};
4875         my $old_url = $full_url;
4876         $full_url .= '/' . $path if length $path;
4877         my ($ra, $reparented);
4878
4879         if ($old_url =~ m#^svn(\+ssh)?://# ||
4880             ($full_url =~ m#^https?://# &&
4881              escape_url($full_url) ne $full_url)) {
4882                 $_[0] = undef;
4883                 $self = undef;
4884                 $RA = undef;
4885                 $ra = Git::SVN::Ra->new($full_url);
4886                 $ra_invalid = 1;
4887         } elsif ($old_url ne $full_url) {
4888                 SVN::_Ra::svn_ra_reparent($self->{session}, $full_url, $pool);
4889                 $self->{url} = $full_url;
4890                 $reparented = 1;
4891         }
4892
4893         $ra ||= $self;
4894         $url_b = escape_url($url_b);
4895         my $reporter = $ra->do_switch($rev_b, '', 1, $url_b, $editor, $pool);
4896         my @lock = $SVN::Core::VERSION ge '1.2.0' ? (undef) : ();
4897         $reporter->set_path('', $rev_a, 0, @lock, $pool);
4898         $reporter->finish_report($pool);
4899
4900         if ($reparented) {
4901                 SVN::_Ra::svn_ra_reparent($self->{session}, $old_url, $pool);
4902                 $self->{url} = $old_url;
4903         }
4904
4905         $pool->clear;
4906         $editor->{git_commit_ok};
4907 }
4908
4909 sub longest_common_path {
4910         my ($gsv, $globs) = @_;
4911         my %common;
4912         my $common_max = scalar @$gsv;
4913
4914         foreach my $gs (@$gsv) {
4915                 my @tmp = split m#/#, $gs->{path};
4916                 my $p = '';
4917                 foreach (@tmp) {
4918                         $p .= length($p) ? "/$_" : $_;
4919                         $common{$p} ||= 0;
4920                         $common{$p}++;
4921                 }
4922         }
4923         $globs ||= [];
4924         $common_max += scalar @$globs;
4925         foreach my $glob (@$globs) {
4926                 my @tmp = split m#/#, $glob->{path}->{left};
4927                 my $p = '';
4928                 foreach (@tmp) {
4929                         $p .= length($p) ? "/$_" : $_;
4930                         $common{$p} ||= 0;
4931                         $common{$p}++;
4932                 }
4933         }
4934
4935         my $longest_path = '';
4936         foreach (sort {length $b <=> length $a} keys %common) {
4937                 if ($common{$_} == $common_max) {
4938                         $longest_path = $_;
4939                         last;
4940                 }
4941         }
4942         $longest_path;
4943 }
4944
4945 sub gs_fetch_loop_common {
4946         my ($self, $base, $head, $gsv, $globs) = @_;
4947         return if ($base > $head);
4948         my $inc = $_log_window_size;
4949         my ($min, $max) = ($base, $head < $base + $inc ? $head : $base + $inc);
4950         my $longest_path = longest_common_path($gsv, $globs);
4951         my $ra_url = $self->{url};
4952         my $find_trailing_edge;
4953         while (1) {
4954                 my %revs;
4955                 my $err;
4956                 my $err_handler = $SVN::Error::handler;
4957                 $SVN::Error::handler = sub {
4958                         ($err) = @_;
4959                         skip_unknown_revs($err);
4960                 };
4961                 sub _cb {
4962                         my ($paths, $r, $author, $date, $log) = @_;
4963                         [ $paths,
4964                           { author => $author, date => $date, log => $log } ];
4965                 }
4966                 $self->get_log([$longest_path], $min, $max, 0, 1, 1,
4967                                sub { $revs{$_[1]} = _cb(@_) });
4968                 if ($err) {
4969                         print "Checked through r$max\r";
4970                 } else {
4971                         $find_trailing_edge = 1;
4972                 }
4973                 if ($err and $find_trailing_edge) {
4974                         print STDERR "Path '$longest_path' ",
4975                                      "was probably deleted:\n",
4976                                      $err->expanded_message,
4977                                      "\nWill attempt to follow ",
4978                                      "revisions r$min .. r$max ",
4979                                      "committed before the deletion\n";
4980                         my $hi = $max;
4981                         while (--$hi >= $min) {
4982                                 my $ok;
4983                                 $self->get_log([$longest_path], $min, $hi,
4984                                                0, 1, 1, sub {
4985                                                $ok = $_[1];
4986                                                $revs{$_[1]} = _cb(@_) });
4987                                 if ($ok) {
4988                                         print STDERR "r$min .. r$ok OK\n";
4989                                         last;
4990                                 }
4991                         }
4992                         $find_trailing_edge = 0;
4993                 }
4994                 $SVN::Error::handler = $err_handler;
4995
4996                 my %exists = map { $_->{path} => $_ } @$gsv;
4997                 foreach my $r (sort {$a <=> $b} keys %revs) {
4998                         my ($paths, $logged) = @{$revs{$r}};
4999
5000                         foreach my $gs ($self->match_globs(\%exists, $paths,
5001                                                            $globs, $r)) {
5002                                 if ($gs->rev_map_max >= $r) {
5003                                         next;
5004                                 }
5005                                 next unless $gs->match_paths($paths, $r);
5006                                 $gs->{logged_rev_props} = $logged;
5007                                 if (my $last_commit = $gs->last_commit) {
5008                                         $gs->assert_index_clean($last_commit);
5009                                 }
5010                                 my $log_entry = $gs->do_fetch($paths, $r);
5011                                 if ($log_entry) {
5012                                         $gs->do_git_commit($log_entry);
5013                                 }
5014                                 $INDEX_FILES{$gs->{index}} = 1;
5015                         }
5016                         foreach my $g (@$globs) {
5017                                 my $k = "svn-remote.$g->{remote}." .
5018                                         "$g->{t}-maxRev";
5019                                 Git::SVN::tmp_config($k, $r);
5020                         }
5021                         if ($ra_invalid) {
5022                                 $_[0] = undef;
5023                                 $self = undef;
5024                                 $RA = undef;
5025                                 $self = Git::SVN::Ra->new($ra_url);
5026                                 $ra_invalid = undef;
5027                         }
5028                 }
5029                 # pre-fill the .rev_db since it'll eventually get filled in
5030                 # with '0' x40 if something new gets committed
5031                 foreach my $gs (@$gsv) {
5032                         next if $gs->rev_map_max >= $max;
5033                         next if defined $gs->rev_map_get($max);
5034                         $gs->rev_map_set($max, 0 x40);
5035                 }
5036                 foreach my $g (@$globs) {
5037                         my $k = "svn-remote.$g->{remote}.$g->{t}-maxRev";
5038                         Git::SVN::tmp_config($k, $max);
5039                 }
5040                 last if $max >= $head;
5041                 $min = $max + 1;
5042                 $max += $inc;
5043                 $max = $head if ($max > $head);
5044         }
5045         Git::SVN::gc();
5046 }
5047
5048 sub get_dir_globbed {
5049         my ($self, $left, $depth, $r) = @_;
5050
5051         my @x = eval { $self->get_dir($left, $r) };
5052         return unless scalar @x == 3;
5053         my $dirents = $x[0];
5054         my @finalents;
5055         foreach my $de (keys %$dirents) {
5056                 next if $dirents->{$de}->{kind} != $SVN::Node::dir;
5057                 if ($depth > 1) {
5058                         my @args = ("$left/$de", $depth - 1, $r);
5059                         foreach my $dir ($self->get_dir_globbed(@args)) {
5060                                 push @finalents, "$de/$dir";
5061                         }
5062                 } else {
5063                         push @finalents, $de;
5064                 }
5065         }
5066         @finalents;
5067 }
5068
5069 sub match_globs {
5070         my ($self, $exists, $paths, $globs, $r) = @_;
5071
5072         sub get_dir_check {
5073                 my ($self, $exists, $g, $r) = @_;
5074
5075                 my @dirs = $self->get_dir_globbed($g->{path}->{left},
5076                                                   $g->{path}->{depth},
5077                                                   $r);
5078
5079                 foreach my $de (@dirs) {
5080                         my $p = $g->{path}->full_path($de);
5081                         next if $exists->{$p};
5082                         next if (length $g->{path}->{right} &&
5083                                  ($self->check_path($p, $r) !=
5084                                   $SVN::Node::dir));
5085                         $exists->{$p} = Git::SVN->init($self->{url}, $p, undef,
5086                                          $g->{ref}->full_path($de), 1);
5087                 }
5088         }
5089         foreach my $g (@$globs) {
5090                 if (my $path = $paths->{"/$g->{path}->{left}"}) {
5091                         if ($path->{action} =~ /^[AR]$/) {
5092                                 get_dir_check($self, $exists, $g, $r);
5093                         }
5094                 }
5095                 foreach (keys %$paths) {
5096                         if (/$g->{path}->{left_regex}/ &&
5097                             !/$g->{path}->{regex}/) {
5098                                 next if $paths->{$_}->{action} !~ /^[AR]$/;
5099                                 get_dir_check($self, $exists, $g, $r);
5100                         }
5101                         next unless /$g->{path}->{regex}/;
5102                         my $p = $1;
5103                         my $pathname = $g->{path}->full_path($p);
5104                         next if $exists->{$pathname};
5105                         next if ($self->check_path($pathname, $r) !=
5106                                  $SVN::Node::dir);
5107                         $exists->{$pathname} = Git::SVN->init(
5108                                               $self->{url}, $pathname, undef,
5109                                               $g->{ref}->full_path($p), 1);
5110                 }
5111                 my $c = '';
5112                 foreach (split m#/#, $g->{path}->{left}) {
5113                         $c .= "/$_";
5114                         next unless ($paths->{$c} &&
5115                                      ($paths->{$c}->{action} =~ /^[AR]$/));
5116                         get_dir_check($self, $exists, $g, $r);
5117                 }
5118         }
5119         values %$exists;
5120 }
5121
5122 sub minimize_url {
5123         my ($self) = @_;
5124         return $self->{url} if ($self->{url} eq $self->{repos_root});
5125         my $url = $self->{repos_root};
5126         my @components = split(m!/!, $self->{svn_path});
5127         my $c = '';
5128         do {
5129                 $url .= "/$c" if length $c;
5130                 eval {
5131                         my $ra = (ref $self)->new($url);
5132                         my $latest = $ra->get_latest_revnum;
5133                         $ra->get_log("", $latest, 0, 1, 0, 1, sub {});
5134                 };
5135         } while ($@ && ($c = shift @components));
5136         $url;
5137 }
5138
5139 sub can_do_switch {
5140         my $self = shift;
5141         unless (defined $can_do_switch) {
5142                 my $pool = SVN::Pool->new;
5143                 my $rep = eval {
5144                         $self->do_switch(1, '', 0, $self->{url},
5145                                          SVN::Delta::Editor->new, $pool);
5146                 };
5147                 if ($@) {
5148                         $can_do_switch = 0;
5149                 } else {
5150                         $rep->abort_report($pool);
5151                         $can_do_switch = 1;
5152                 }
5153                 $pool->clear;
5154         }
5155         $can_do_switch;
5156 }
5157
5158 sub skip_unknown_revs {
5159         my ($err) = @_;
5160         my $errno = $err->apr_err();
5161         # Maybe the branch we're tracking didn't
5162         # exist when the repo started, so it's
5163         # not an error if it doesn't, just continue
5164         #
5165         # Wonderfully consistent library, eh?
5166         # 160013 - svn:// and file://
5167         # 175002 - http(s)://
5168         # 175007 - http(s):// (this repo required authorization, too...)
5169         #   More codes may be discovered later...
5170         if ($errno == 175007 || $errno == 175002 || $errno == 160013) {
5171                 my $err_key = $err->expanded_message;
5172                 # revision numbers change every time, filter them out
5173                 $err_key =~ s/\d+/\0/g;
5174                 $err_key = "$errno\0$err_key";
5175                 unless ($ignored_err{$err_key}) {
5176                         warn "W: Ignoring error from SVN, path probably ",
5177                              "does not exist: ($errno): ",
5178                              $err->expanded_message,"\n";
5179                         warn "W: Do not be alarmed at the above message ",
5180                              "git-svn is just searching aggressively for ",
5181                              "old history.\n",
5182                              "This may take a while on large repositories\n";
5183                         $ignored_err{$err_key} = 1;
5184                 }
5185                 return;
5186         }
5187         die "Error from SVN, ($errno): ", $err->expanded_message,"\n";
5188 }
5189
5190 package Git::SVN::Log;
5191 use strict;
5192 use warnings;
5193 use POSIX qw/strftime/;
5194 use Time::Local;
5195 use constant commit_log_separator => ('-' x 72) . "\n";
5196 use vars qw/$TZ $limit $color $pager $non_recursive $verbose $oneline
5197             %rusers $show_commit $incremental/;
5198 my $l_fmt;
5199
5200 sub cmt_showable {
5201         my ($c) = @_;
5202         return 1 if defined $c->{r};
5203
5204         # big commit message got truncated by the 16k pretty buffer in rev-list
5205         if ($c->{l} && $c->{l}->[-1] eq "...\n" &&
5206                                 $c->{a_raw} =~ /\@([a-f\d\-]+)>$/) {
5207                 @{$c->{l}} = ();
5208                 my @log = command(qw/cat-file commit/, $c->{c});
5209
5210                 # shift off the headers
5211                 shift @log while ($log[0] ne '');
5212                 shift @log;
5213
5214                 # TODO: make $c->{l} not have a trailing newline in the future
5215                 @{$c->{l}} = map { "$_\n" } grep !/^git-svn-id: /, @log;
5216
5217                 (undef, $c->{r}, undef) = ::extract_metadata(
5218                                 (grep(/^git-svn-id: /, @log))[-1]);
5219         }
5220         return defined $c->{r};
5221 }
5222
5223 sub log_use_color {
5224         return $color || Git->repository->get_colorbool('color.diff');
5225 }
5226
5227 sub git_svn_log_cmd {
5228         my ($r_min, $r_max, @args) = @_;
5229         my $head = 'HEAD';
5230         my (@files, @log_opts);
5231         foreach my $x (@args) {
5232                 if ($x eq '--' || @files) {
5233                         push @files, $x;
5234                 } else {
5235                         if (::verify_ref("$x^0")) {
5236                                 $head = $x;
5237                         } else {
5238                                 push @log_opts, $x;
5239                         }
5240                 }
5241         }
5242
5243         my ($url, $rev, $uuid, $gs) = ::working_head_info($head);
5244         $gs ||= Git::SVN->_new;
5245         my @cmd = (qw/log --abbrev-commit --pretty=raw --default/,
5246                    $gs->refname);
5247         push @cmd, '-r' unless $non_recursive;
5248         push @cmd, qw/--raw --name-status/ if $verbose;
5249         push @cmd, '--color' if log_use_color();
5250         push @cmd, @log_opts;
5251         if (defined $r_max && $r_max == $r_min) {
5252                 push @cmd, '--max-count=1';
5253                 if (my $c = $gs->rev_map_get($r_max)) {
5254                         push @cmd, $c;
5255                 }
5256         } elsif (defined $r_max) {
5257                 if ($r_max < $r_min) {
5258                         ($r_min, $r_max) = ($r_max, $r_min);
5259                 }
5260                 my (undef, $c_max) = $gs->find_rev_before($r_max, 1, $r_min);
5261                 my (undef, $c_min) = $gs->find_rev_after($r_min, 1, $r_max);
5262                 # If there are no commits in the range, both $c_max and $c_min
5263                 # will be undefined.  If there is at least 1 commit in the
5264                 # range, both will be defined.
5265                 return () if !defined $c_min || !defined $c_max;
5266                 if ($c_min eq $c_max) {
5267                         push @cmd, '--max-count=1', $c_min;
5268                 } else {
5269                         push @cmd, '--boundary', "$c_min..$c_max";
5270                 }
5271         }
5272         return (@cmd, @files);
5273 }
5274
5275 # adapted from pager.c
5276 sub config_pager {
5277         chomp(my $pager = command_oneline(qw(var GIT_PAGER)));
5278         if ($pager eq 'cat') {
5279                 $pager = undef;
5280         }
5281         $ENV{GIT_PAGER_IN_USE} = defined($pager);
5282 }
5283
5284 sub run_pager {
5285         return unless -t *STDOUT && defined $pager;
5286         pipe my ($rfd, $wfd) or return;
5287         defined(my $pid = fork) or ::fatal "Can't fork: $!";
5288         if (!$pid) {
5289                 open STDOUT, '>&', $wfd or
5290                                      ::fatal "Can't redirect to stdout: $!";
5291                 return;
5292         }
5293         open STDIN, '<&', $rfd or ::fatal "Can't redirect stdin: $!";
5294         $ENV{LESS} ||= 'FRSX';
5295         exec $pager or ::fatal "Can't run pager: $! ($pager)";
5296 }
5297
5298 sub format_svn_date {
5299         # some systmes don't handle or mishandle %z, so be creative.
5300         my $t = shift || time;
5301         my $gm = timelocal(gmtime($t));
5302         my $sign = qw( + + - )[ $t <=> $gm ];
5303         my $gmoff = sprintf("%s%02d%02d", $sign, (gmtime(abs($t - $gm)))[2,1]);
5304         return strftime("%Y-%m-%d %H:%M:%S $gmoff (%a, %d %b %Y)", localtime($t));
5305 }
5306
5307 sub parse_git_date {
5308         my ($t, $tz) = @_;
5309         # Date::Parse isn't in the standard Perl distro :(
5310         if ($tz =~ s/^\+//) {
5311                 $t += tz_to_s_offset($tz);
5312         } elsif ($tz =~ s/^\-//) {
5313                 $t -= tz_to_s_offset($tz);
5314         }
5315         return $t;
5316 }
5317
5318 sub set_local_timezone {
5319         if (defined $TZ) {
5320                 $ENV{TZ} = $TZ;
5321         } else {
5322                 delete $ENV{TZ};
5323         }
5324 }
5325
5326 sub tz_to_s_offset {
5327         my ($tz) = @_;
5328         $tz =~ s/(\d\d)$//;
5329         return ($1 * 60) + ($tz * 3600);
5330 }
5331
5332 sub get_author_info {
5333         my ($dest, $author, $t, $tz) = @_;
5334         $author =~ s/(?:^\s*|\s*$)//g;
5335         $dest->{a_raw} = $author;
5336         my $au;
5337         if ($::_authors) {
5338                 $au = $rusers{$author} || undef;
5339         }
5340         if (!$au) {
5341                 ($au) = ($author =~ /<([^>]+)\@[^>]+>$/);
5342         }
5343         $dest->{t} = $t;
5344         $dest->{tz} = $tz;
5345         $dest->{a} = $au;
5346         $dest->{t_utc} = parse_git_date($t, $tz);
5347 }
5348
5349 sub process_commit {
5350         my ($c, $r_min, $r_max, $defer) = @_;
5351         if (defined $r_min && defined $r_max) {
5352                 if ($r_min == $c->{r} && $r_min == $r_max) {
5353                         show_commit($c);
5354                         return 0;
5355                 }
5356                 return 1 if $r_min == $r_max;
5357                 if ($r_min < $r_max) {
5358                         # we need to reverse the print order
5359                         return 0 if (defined $limit && --$limit < 0);
5360                         push @$defer, $c;
5361                         return 1;
5362                 }
5363                 if ($r_min != $r_max) {
5364                         return 1 if ($r_min < $c->{r});
5365                         return 1 if ($r_max > $c->{r});
5366                 }
5367         }
5368         return 0 if (defined $limit && --$limit < 0);
5369         show_commit($c);
5370         return 1;
5371 }
5372
5373 sub show_commit {
5374         my $c = shift;
5375         if ($oneline) {
5376                 my $x = "\n";
5377                 if (my $l = $c->{l}) {
5378                         while ($l->[0] =~ /^\s*$/) { shift @$l }
5379                         $x = $l->[0];
5380                 }
5381                 $l_fmt ||= 'A' . length($c->{r});
5382                 print 'r',pack($l_fmt, $c->{r}),' | ';
5383                 print "$c->{c} | " if $show_commit;
5384                 print $x;
5385         } else {
5386                 show_commit_normal($c);
5387         }
5388 }
5389
5390 sub show_commit_changed_paths {
5391         my ($c) = @_;
5392         return unless $c->{changed};
5393         print "Changed paths:\n", @{$c->{changed}};
5394 }
5395
5396 sub show_commit_normal {
5397         my ($c) = @_;
5398         print commit_log_separator, "r$c->{r} | ";
5399         print "$c->{c} | " if $show_commit;
5400         print "$c->{a} | ", format_svn_date($c->{t_utc}), ' | ';
5401         my $nr_line = 0;
5402
5403         if (my $l = $c->{l}) {
5404                 while ($l->[$#$l] eq "\n" && $#$l > 0
5405                                           && $l->[($#$l - 1)] eq "\n") {
5406                         pop @$l;
5407                 }
5408                 $nr_line = scalar @$l;
5409                 if (!$nr_line) {
5410                         print "1 line\n\n\n";
5411                 } else {
5412                         if ($nr_line == 1) {
5413                                 $nr_line = '1 line';
5414                         } else {
5415                                 $nr_line .= ' lines';
5416                         }
5417                         print $nr_line, "\n";
5418                         show_commit_changed_paths($c);
5419                         print "\n";
5420                         print $_ foreach @$l;
5421                 }
5422         } else {
5423                 print "1 line\n";
5424                 show_commit_changed_paths($c);
5425                 print "\n";
5426
5427         }
5428         foreach my $x (qw/raw stat diff/) {
5429                 if ($c->{$x}) {
5430                         print "\n";
5431                         print $_ foreach @{$c->{$x}}
5432                 }
5433         }
5434 }
5435
5436 sub cmd_show_log {
5437         my (@args) = @_;
5438         my ($r_min, $r_max);
5439         my $r_last = -1; # prevent dupes
5440         set_local_timezone();
5441         if (defined $::_revision) {
5442                 if ($::_revision =~ /^(\d+):(\d+)$/) {
5443                         ($r_min, $r_max) = ($1, $2);
5444                 } elsif ($::_revision =~ /^\d+$/) {
5445                         $r_min = $r_max = $::_revision;
5446                 } else {
5447                         ::fatal "-r$::_revision is not supported, use ",
5448                                 "standard 'git log' arguments instead";
5449                 }
5450         }
5451
5452         config_pager();
5453         @args = git_svn_log_cmd($r_min, $r_max, @args);
5454         if (!@args) {
5455                 print commit_log_separator unless $incremental || $oneline;
5456                 return;
5457         }
5458         my $log = command_output_pipe(@args);
5459         run_pager();
5460         my (@k, $c, $d, $stat);
5461         my $esc_color = qr/(?:\033\[(?:(?:\d+;)*\d*)?m)*/;
5462         while (<$log>) {
5463                 if (/^${esc_color}commit -?($::sha1_short)/o) {
5464                         my $cmt = $1;
5465                         if ($c && cmt_showable($c) && $c->{r} != $r_last) {
5466                                 $r_last = $c->{r};
5467                                 process_commit($c, $r_min, $r_max, \@k) or
5468                                                                 goto out;
5469                         }
5470                         $d = undef;
5471                         $c = { c => $cmt };
5472                 } elsif (/^${esc_color}author (.+) (\d+) ([\-\+]?\d+)$/o) {
5473                         get_author_info($c, $1, $2, $3);
5474                 } elsif (/^${esc_color}(?:tree|parent|committer) /o) {
5475                         # ignore
5476                 } elsif (/^${esc_color}:\d{6} \d{6} $::sha1_short/o) {
5477                         push @{$c->{raw}}, $_;
5478                 } elsif (/^${esc_color}[ACRMDT]\t/) {
5479                         # we could add $SVN->{svn_path} here, but that requires
5480                         # remote access at the moment (repo_path_split)...
5481                         s#^(${esc_color})([ACRMDT])\t#$1   $2 #o;
5482                         push @{$c->{changed}}, $_;
5483                 } elsif (/^${esc_color}diff /o) {
5484                         $d = 1;
5485                         push @{$c->{diff}}, $_;
5486                 } elsif ($d) {
5487                         push @{$c->{diff}}, $_;
5488                 } elsif (/^\ .+\ \|\s*\d+\ $esc_color[\+\-]*
5489                           $esc_color*[\+\-]*$esc_color$/x) {
5490                         $stat = 1;
5491                         push @{$c->{stat}}, $_;
5492                 } elsif ($stat && /^ \d+ files changed, \d+ insertions/) {
5493                         push @{$c->{stat}}, $_;
5494                         $stat = undef;
5495                 } elsif (/^${esc_color}    (git-svn-id:.+)$/o) {
5496                         ($c->{url}, $c->{r}, undef) = ::extract_metadata($1);
5497                 } elsif (s/^${esc_color}    //o) {
5498                         push @{$c->{l}}, $_;
5499                 }
5500         }
5501         if ($c && defined $c->{r} && $c->{r} != $r_last) {
5502                 $r_last = $c->{r};
5503                 process_commit($c, $r_min, $r_max, \@k);
5504         }
5505         if (@k) {
5506                 ($r_min, $r_max) = ($r_max, $r_min);
5507                 process_commit($_, $r_min, $r_max) foreach reverse @k;
5508         }
5509 out:
5510         close $log;
5511         print commit_log_separator unless $incremental || $oneline;
5512 }
5513
5514 sub cmd_blame {
5515         my $path = pop;
5516
5517         config_pager();
5518         run_pager();
5519
5520         my ($fh, $ctx, $rev);
5521
5522         if ($_git_format) {
5523                 ($fh, $ctx) = command_output_pipe('blame', @_, $path);
5524                 while (my $line = <$fh>) {
5525                         if ($line =~ /^\^?([[:xdigit:]]+)\s/) {
5526                                 # Uncommitted edits show up as a rev ID of
5527                                 # all zeros, which we can't look up with
5528                                 # cmt_metadata
5529                                 if ($1 !~ /^0+$/) {
5530                                         (undef, $rev, undef) =
5531                                                 ::cmt_metadata($1);
5532                                         $rev = '0' if (!$rev);
5533                                 } else {
5534                                         $rev = '0';
5535                                 }
5536                                 $rev = sprintf('%-10s', $rev);
5537                                 $line =~ s/^\^?[[:xdigit:]]+(\s)/$rev$1/;
5538                         }
5539                         print $line;
5540                 }
5541         } else {
5542                 ($fh, $ctx) = command_output_pipe('blame', '-p', @_, 'HEAD',
5543                                                   '--', $path);
5544                 my ($sha1);
5545                 my %authors;
5546                 my @buffer;
5547                 my %dsha; #distinct sha keys
5548
5549                 while (my $line = <$fh>) {
5550                         push @buffer, $line;
5551                         if ($line =~ /^([[:xdigit:]]{40})\s\d+\s\d+/) {
5552                                 $dsha{$1} = 1;
5553                         }
5554                 }
5555
5556                 my $s2r = ::cmt_sha2rev_batch([keys %dsha]);
5557
5558                 foreach my $line (@buffer) {
5559                         if ($line =~ /^([[:xdigit:]]{40})\s\d+\s\d+/) {
5560                                 $rev = $s2r->{$1};
5561                                 $rev = '0' if (!$rev)
5562                         }
5563                         elsif ($line =~ /^author (.*)/) {
5564                                 $authors{$rev} = $1;
5565                                 $authors{$rev} =~ s/\s/_/g;
5566                         }
5567                         elsif ($line =~ /^\t(.*)$/) {
5568                                 printf("%6s %10s %s\n", $rev, $authors{$rev}, $1);
5569                         }
5570                 }
5571         }
5572         command_close_pipe($fh, $ctx);
5573 }
5574
5575 package Git::SVN::Migration;
5576 # these version numbers do NOT correspond to actual version numbers
5577 # of git nor git-svn.  They are just relative.
5578 #
5579 # v0 layout: .git/$id/info/url, refs/heads/$id-HEAD
5580 #
5581 # v1 layout: .git/$id/info/url, refs/remotes/$id
5582 #
5583 # v2 layout: .git/svn/$id/info/url, refs/remotes/$id
5584 #
5585 # v3 layout: .git/svn/$id, refs/remotes/$id
5586 #            - info/url may remain for backwards compatibility
5587 #            - this is what we migrate up to this layout automatically,
5588 #            - this will be used by git svn init on single branches
5589 # v3.1 layout (auto migrated):
5590 #            - .rev_db => .rev_db.$UUID, .rev_db will remain as a symlink
5591 #              for backwards compatibility
5592 #
5593 # v4 layout: .git/svn/$repo_id/$id, refs/remotes/$repo_id/$id
5594 #            - this is only created for newly multi-init-ed
5595 #              repositories.  Similar in spirit to the
5596 #              --use-separate-remotes option in git-clone (now default)
5597 #            - we do not automatically migrate to this (following
5598 #              the example set by core git)
5599 #
5600 # v5 layout: .rev_db.$UUID => .rev_map.$UUID
5601 #            - newer, more-efficient format that uses 24-bytes per record
5602 #              with no filler space.
5603 #            - use xxd -c24 < .rev_map.$UUID to view and debug
5604 #            - This is a one-way migration, repositories updated to the
5605 #              new format will not be able to use old git-svn without
5606 #              rebuilding the .rev_db.  Rebuilding the rev_db is not
5607 #              possible if noMetadata or useSvmProps are set; but should
5608 #              be no problem for users that use the (sensible) defaults.
5609 use strict;
5610 use warnings;
5611 use Carp qw/croak/;
5612 use File::Path qw/mkpath/;
5613 use File::Basename qw/dirname basename/;
5614 use vars qw/$_minimize/;
5615
5616 sub migrate_from_v0 {
5617         my $git_dir = $ENV{GIT_DIR};
5618         return undef unless -d $git_dir;
5619         my ($fh, $ctx) = command_output_pipe(qw/rev-parse --symbolic --all/);
5620         my $migrated = 0;
5621         while (<$fh>) {
5622                 chomp;
5623                 my ($id, $orig_ref) = ($_, $_);
5624                 next unless $id =~ s#^refs/heads/(.+)-HEAD$#$1#;
5625                 next unless -f "$git_dir/$id/info/url";
5626                 my $new_ref = "refs/remotes/$id";
5627                 if (::verify_ref("$new_ref^0")) {
5628                         print STDERR "W: $orig_ref is probably an old ",
5629                                      "branch used by an ancient version of ",
5630                                      "git-svn.\n",
5631                                      "However, $new_ref also exists.\n",
5632                                      "We will not be able ",
5633                                      "to use this branch until this ",
5634                                      "ambiguity is resolved.\n";
5635                         next;
5636                 }
5637                 print STDERR "Migrating from v0 layout...\n" if !$migrated;
5638                 print STDERR "Renaming ref: $orig_ref => $new_ref\n";
5639                 command_noisy('update-ref', $new_ref, $orig_ref);
5640                 command_noisy('update-ref', '-d', $orig_ref, $orig_ref);
5641                 $migrated++;
5642         }
5643         command_close_pipe($fh, $ctx);
5644         print STDERR "Done migrating from v0 layout...\n" if $migrated;
5645         $migrated;
5646 }
5647
5648 sub migrate_from_v1 {
5649         my $git_dir = $ENV{GIT_DIR};
5650         my $migrated = 0;
5651         return $migrated unless -d $git_dir;
5652         my $svn_dir = "$git_dir/svn";
5653
5654         # just in case somebody used 'svn' as their $id at some point...
5655         return $migrated if -d $svn_dir && ! -f "$svn_dir/info/url";
5656
5657         print STDERR "Migrating from a git-svn v1 layout...\n";
5658         mkpath([$svn_dir]);
5659         print STDERR "Data from a previous version of git-svn exists, but\n\t",
5660                      "$svn_dir\n\t(required for this version ",
5661                      "($::VERSION) of git-svn) does not exist.\n";
5662         my ($fh, $ctx) = command_output_pipe(qw/rev-parse --symbolic --all/);
5663         while (<$fh>) {
5664                 my $x = $_;
5665                 next unless $x =~ s#^refs/remotes/##;
5666                 chomp $x;
5667                 next unless -f "$git_dir/$x/info/url";
5668                 my $u = eval { ::file_to_s("$git_dir/$x/info/url") };
5669                 next unless $u;
5670                 my $dn = dirname("$git_dir/svn/$x");
5671                 mkpath([$dn]) unless -d $dn;
5672                 if ($x eq 'svn') { # they used 'svn' as GIT_SVN_ID:
5673                         mkpath(["$git_dir/svn/svn"]);
5674                         print STDERR " - $git_dir/$x/info => ",
5675                                         "$git_dir/svn/$x/info\n";
5676                         rename "$git_dir/$x/info", "$git_dir/svn/$x/info" or
5677                                croak "$!: $x";
5678                         # don't worry too much about these, they probably
5679                         # don't exist with repos this old (save for index,
5680                         # and we can easily regenerate that)
5681                         foreach my $f (qw/unhandled.log index .rev_db/) {
5682                                 rename "$git_dir/$x/$f", "$git_dir/svn/$x/$f";
5683                         }
5684                 } else {
5685                         print STDERR " - $git_dir/$x => $git_dir/svn/$x\n";
5686                         rename "$git_dir/$x", "$git_dir/svn/$x" or
5687                                croak "$!: $x";
5688                 }
5689                 $migrated++;
5690         }
5691         command_close_pipe($fh, $ctx);
5692         print STDERR "Done migrating from a git-svn v1 layout\n";
5693         $migrated;
5694 }
5695
5696 sub read_old_urls {
5697         my ($l_map, $pfx, $path) = @_;
5698         my @dir;
5699         foreach (<$path/*>) {
5700                 if (-r "$_/info/url") {
5701                         $pfx .= '/' if $pfx && $pfx !~ m!/$!;
5702                         my $ref_id = $pfx . basename $_;
5703                         my $url = ::file_to_s("$_/info/url");
5704                         $l_map->{$ref_id} = $url;
5705                 } elsif (-d $_) {
5706                         push @dir, $_;
5707                 }
5708         }
5709         foreach (@dir) {
5710                 my $x = $_;
5711                 $x =~ s!^\Q$ENV{GIT_DIR}\E/svn/!!o;
5712                 read_old_urls($l_map, $x, $_);
5713         }
5714 }
5715
5716 sub migrate_from_v2 {
5717         my @cfg = command(qw/config -l/);
5718         return if grep /^svn-remote\..+\.url=/, @cfg;
5719         my %l_map;
5720         read_old_urls(\%l_map, '', "$ENV{GIT_DIR}/svn");
5721         my $migrated = 0;
5722
5723         foreach my $ref_id (sort keys %l_map) {
5724                 eval { Git::SVN->init($l_map{$ref_id}, '', undef, $ref_id) };
5725                 if ($@) {
5726                         Git::SVN->init($l_map{$ref_id}, '', $ref_id, $ref_id);
5727                 }
5728                 $migrated++;
5729         }
5730         $migrated;
5731 }
5732
5733 sub minimize_connections {
5734         my $r = Git::SVN::read_all_remotes();
5735         my $new_urls = {};
5736         my $root_repos = {};
5737         foreach my $repo_id (keys %$r) {
5738                 my $url = $r->{$repo_id}->{url} or next;
5739                 my $fetch = $r->{$repo_id}->{fetch} or next;
5740                 my $ra = Git::SVN::Ra->new($url);
5741
5742                 # skip existing cases where we already connect to the root
5743                 if (($ra->{url} eq $ra->{repos_root}) ||
5744                     ($ra->{repos_root} eq $repo_id)) {
5745                         $root_repos->{$ra->{url}} = $repo_id;
5746                         next;
5747                 }
5748
5749                 my $root_ra = Git::SVN::Ra->new($ra->{repos_root});
5750                 my $root_path = $ra->{url};
5751                 $root_path =~ s#^\Q$ra->{repos_root}\E(/|$)##;
5752                 foreach my $path (keys %$fetch) {
5753                         my $ref_id = $fetch->{$path};
5754                         my $gs = Git::SVN->new($ref_id, $repo_id, $path);
5755
5756                         # make sure we can read when connecting to
5757                         # a higher level of a repository
5758                         my ($last_rev, undef) = $gs->last_rev_commit;
5759                         if (!defined $last_rev) {
5760                                 $last_rev = eval {
5761                                         $root_ra->get_latest_revnum;
5762                                 };
5763                                 next if $@;
5764                         }
5765                         my $new = $root_path;
5766                         $new .= length $path ? "/$path" : '';
5767                         eval {
5768                                 $root_ra->get_log([$new], $last_rev, $last_rev,
5769                                                   0, 0, 1, sub { });
5770                         };
5771                         next if $@;
5772                         $new_urls->{$ra->{repos_root}}->{$new} =
5773                                 { ref_id => $ref_id,
5774                                   old_repo_id => $repo_id,
5775                                   old_path => $path };
5776                 }
5777         }
5778
5779         my @emptied;
5780         foreach my $url (keys %$new_urls) {
5781                 # see if we can re-use an existing [svn-remote "repo_id"]
5782                 # instead of creating a(n ugly) new section:
5783                 my $repo_id = $root_repos->{$url} || $url;
5784
5785                 my $fetch = $new_urls->{$url};
5786                 foreach my $path (keys %$fetch) {
5787                         my $x = $fetch->{$path};
5788                         Git::SVN->init($url, $path, $repo_id, $x->{ref_id});
5789                         my $pfx = "svn-remote.$x->{old_repo_id}";
5790
5791                         my $old_fetch = quotemeta("$x->{old_path}:".
5792                                                   "$x->{ref_id}");
5793                         command_noisy(qw/config --unset/,
5794                                       "$pfx.fetch", '^'. $old_fetch . '$');
5795                         delete $r->{$x->{old_repo_id}}->
5796                                {fetch}->{$x->{old_path}};
5797                         if (!keys %{$r->{$x->{old_repo_id}}->{fetch}}) {
5798                                 command_noisy(qw/config --unset/,
5799                                               "$pfx.url");
5800                                 push @emptied, $x->{old_repo_id}
5801                         }
5802                 }
5803         }
5804         if (@emptied) {
5805                 my $file = $ENV{GIT_CONFIG} || "$ENV{GIT_DIR}/config";
5806                 print STDERR <<EOF;
5807 The following [svn-remote] sections in your config file ($file) are empty
5808 and can be safely removed:
5809 EOF
5810                 print STDERR "[svn-remote \"$_\"]\n" foreach @emptied;
5811         }
5812 }
5813
5814 sub migration_check {
5815         migrate_from_v0();
5816         migrate_from_v1();
5817         migrate_from_v2();
5818         minimize_connections() if $_minimize;
5819 }
5820
5821 package Git::IndexInfo;
5822 use strict;
5823 use warnings;
5824 use Git qw/command_input_pipe command_close_pipe/;
5825
5826 sub new {
5827         my ($class) = @_;
5828         my ($gui, $ctx) = command_input_pipe(qw/update-index -z --index-info/);
5829         bless { gui => $gui, ctx => $ctx, nr => 0}, $class;
5830 }
5831
5832 sub remove {
5833         my ($self, $path) = @_;
5834         if (print { $self->{gui} } '0 ', 0 x 40, "\t", $path, "\0") {
5835                 return ++$self->{nr};
5836         }
5837         undef;
5838 }
5839
5840 sub update {
5841         my ($self, $mode, $hash, $path) = @_;
5842         if (print { $self->{gui} } $mode, ' ', $hash, "\t", $path, "\0") {
5843                 return ++$self->{nr};
5844         }
5845         undef;
5846 }
5847
5848 sub DESTROY {
5849         my ($self) = @_;
5850         command_close_pipe($self->{gui}, $self->{ctx});
5851 }
5852
5853 package Git::SVN::GlobSpec;
5854 use strict;
5855 use warnings;
5856
5857 sub new {
5858         my ($class, $glob) = @_;
5859         my $re = $glob;
5860         $re =~ s!/+$!!g; # no need for trailing slashes
5861         $re =~ m!^([^*]*)(\*(?:/\*)*)(.*)$!;
5862         my $temp = $re;
5863         my ($left, $right) = ($1, $3);
5864         $re = $2;
5865         my $depth = $re =~ tr/*/*/;
5866         if ($depth != $temp =~ tr/*/*/) {
5867                 die "Only one set of wildcard directories " .
5868                         "(e.g. '*' or '*/*/*') is supported: '$glob'\n";
5869         }
5870         if ($depth == 0) {
5871                 die "One '*' is needed for glob: '$glob'\n";
5872         }
5873         $re =~ s!\*!\[^/\]*!g;
5874         $re = quotemeta($left) . "($re)" . quotemeta($right);
5875         if (length $left && !($left =~ s!/+$!!g)) {
5876                 die "Missing trailing '/' on left side of: '$glob' ($left)\n";
5877         }
5878         if (length $right && !($right =~ s!^/+!!g)) {
5879                 die "Missing leading '/' on right side of: '$glob' ($right)\n";
5880         }
5881         my $left_re = qr/^\/\Q$left\E(\/|$)/;
5882         bless { left => $left, right => $right, left_regex => $left_re,
5883                 regex => qr/$re/, glob => $glob, depth => $depth }, $class;
5884 }
5885
5886 sub full_path {
5887         my ($self, $path) = @_;
5888         return (length $self->{left} ? "$self->{left}/" : '') .
5889                $path . (length $self->{right} ? "/$self->{right}" : '');
5890 }
5891
5892 __END__
5893
5894 Data structures:
5895
5896
5897 $remotes = { # returned by read_all_remotes()
5898         'svn' => {
5899                 # svn-remote.svn.url=https://svn.musicpd.org
5900                 url => 'https://svn.musicpd.org',
5901                 # svn-remote.svn.fetch=mpd/trunk:trunk
5902                 fetch => {
5903                         'mpd/trunk' => 'trunk',
5904                 },
5905                 # svn-remote.svn.tags=mpd/tags/*:tags/*
5906                 tags => {
5907                         path => {
5908                                 left => 'mpd/tags',
5909                                 right => '',
5910                                 regex => qr!mpd/tags/([^/]+)$!,
5911                                 glob => 'tags/*',
5912                         },
5913                         ref => {
5914                                 left => 'tags',
5915                                 right => '',
5916                                 regex => qr!tags/([^/]+)$!,
5917                                 glob => 'tags/*',
5918                         },
5919                 }
5920         }
5921 };
5922
5923 $log_entry hashref as returned by libsvn_log_entry()
5924 {
5925         log => 'whitespace-formatted log entry
5926 ',                                              # trailing newline is preserved
5927         revision => '8',                        # integer
5928         date => '2004-02-24T17:01:44.108345Z',  # commit date
5929         author => 'committer name'
5930 };
5931
5932
5933 # this is generated by generate_diff();
5934 @mods = array of diff-index line hashes, each element represents one line
5935         of diff-index output
5936
5937 diff-index line ($m hash)
5938 {
5939         mode_a => first column of diff-index output, no leading ':',
5940         mode_b => second column of diff-index output,
5941         sha1_b => sha1sum of the final blob,
5942         chg => change type [MCRADT],
5943         file_a => original file name of a file (iff chg is 'C' or 'R')
5944         file_b => new/current file name of a file (any chg)
5945 }
5946 ;
5947
5948 # retval of read_url_paths{,_all}();
5949 $l_map = {
5950         # repository root url
5951         'https://svn.musicpd.org' => {
5952                 # repository path               # GIT_SVN_ID
5953                 'mpd/trunk'             =>      'trunk',
5954                 'mpd/tags/0.11.5'       =>      'tags/0.11.5',
5955         },
5956 }
5957
5958 Notes:
5959         I don't trust the each() function on unless I created %hash myself
5960         because the internal iterator may not have started at base.