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