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