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