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