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