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