git-svn: --follow-parent tracks multi-parent paths
[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 (my $lc = $self->last_commit) {
1270                 # we can have a branch that was deleted, then re-added
1271                 # under the same name but copied from another path, in
1272                 # which case we'll have multiple parents (we don't
1273                 # want to break the original ref, nor lose copypath info):
1274                 if (my $log_entry = $self->find_parent_branch($paths, $rev)) {
1275                         push @{$log_entry->{parents}}, $lc;
1276                         return $log_entry;
1277                 }
1278                 $ed = SVN::Git::Fetcher->new($self);
1279                 $last_rev = $self->{last_rev};
1280                 $ed->{c} = $lc;
1281                 @parents = ($lc);
1282         } else {
1283                 $last_rev = $rev;
1284                 if (my $log_entry = $self->find_parent_branch($paths, $rev)) {
1285                         return $log_entry;
1286                 }
1287                 $ed = SVN::Git::Fetcher->new($self);
1288         }
1289         unless ($self->ra->gs_do_update($last_rev, $rev, $self, $ed)) {
1290                 die "SVN connection failed somewhere...\n";
1291         }
1292         $self->make_log_entry($rev, \@parents, $ed);
1293 }
1294
1295 sub get_untracked {
1296         my ($self, $ed) = @_;
1297         my @out;
1298         my $h = $ed->{empty};
1299         foreach (sort keys %$h) {
1300                 my $act = $h->{$_} ? '+empty_dir' : '-empty_dir';
1301                 push @out, "  $act: " . uri_encode($_);
1302                 warn "W: $act: $_\n";
1303         }
1304         foreach my $t (qw/dir_prop file_prop/) {
1305                 $h = $ed->{$t} or next;
1306                 foreach my $path (sort keys %$h) {
1307                         my $ppath = $path eq '' ? '.' : $path;
1308                         foreach my $prop (sort keys %{$h->{$path}}) {
1309                                 next if $SKIP_PROP{$prop};
1310                                 my $v = $h->{$path}->{$prop};
1311                                 my $t_ppath_prop = "$t: " .
1312                                                     uri_encode($ppath) . ' ' .
1313                                                     uri_encode($prop);
1314                                 if (defined $v) {
1315                                         push @out, "  +$t_ppath_prop " .
1316                                                    uri_encode($v);
1317                                 } else {
1318                                         push @out, "  -$t_ppath_prop";
1319                                 }
1320                         }
1321                 }
1322         }
1323         foreach my $t (qw/absent_file absent_directory/) {
1324                 $h = $ed->{$t} or next;
1325                 foreach my $parent (sort keys %$h) {
1326                         foreach my $path (sort @{$h->{$parent}}) {
1327                                 push @out, "  $t: " .
1328                                            uri_encode("$parent/$path");
1329                                 warn "W: $t: $parent/$path ",
1330                                      "Insufficient permissions?\n";
1331                         }
1332                 }
1333         }
1334         \@out;
1335 }
1336
1337 sub parse_svn_date {
1338         my $date = shift || return '+0000 1970-01-01 00:00:00';
1339         my ($Y,$m,$d,$H,$M,$S) = ($date =~ /^(\d{4})\-(\d\d)\-(\d\d)T
1340                                             (\d\d)\:(\d\d)\:(\d\d).\d+Z$/x) or
1341                                          croak "Unable to parse date: $date\n";
1342         "+0000 $Y-$m-$d $H:$M:$S";
1343 }
1344
1345 sub check_author {
1346         my ($author) = @_;
1347         if (!defined $author || length $author == 0) {
1348                 $author = '(no author)';
1349         }
1350         if (defined $::_authors && ! defined $::users{$author}) {
1351                 die "Author: $author not defined in $::_authors file\n";
1352         }
1353         $author;
1354 }
1355
1356 sub make_log_entry {
1357         my ($self, $rev, $parents, $ed) = @_;
1358         my $untracked = $self->get_untracked($ed);
1359
1360         open my $un, '>>', "$self->{dir}/unhandled.log" or croak $!;
1361         print $un "r$rev\n" or croak $!;
1362         print $un $_, "\n" foreach @$untracked;
1363         my %log_entry = ( parents => $parents || [], revision => $rev,
1364                           log => '');
1365
1366         my $logged = delete $self->{logged_rev_props};
1367         if (!$logged || $self->{-want_extra_revprops}) {
1368                 my $rp = $self->ra->rev_proplist($rev);
1369                 foreach (sort keys %$rp) {
1370                         my $v = $rp->{$_};
1371                         if (/^svn:(author|date|log)$/) {
1372                                 $log_entry{$1} = $v;
1373                         } else {
1374                                 print $un "  rev_prop: ", uri_encode($_), ' ',
1375                                           uri_encode($v), "\n";
1376                         }
1377                 }
1378         } else {
1379                 map { $log_entry{$_} = $logged->{$_} } keys %$logged;
1380         }
1381         close $un or croak $!;
1382
1383         $log_entry{date} = parse_svn_date($log_entry{date});
1384         $log_entry{author} = check_author($log_entry{author});
1385         $log_entry{log} .= "\n";
1386         \%log_entry;
1387 }
1388
1389 sub fetch {
1390         my ($self, $min_rev, $max_rev, @parents) = @_;
1391         my ($last_rev, $last_commit) = $self->last_rev_commit;
1392         my ($base, $head) = $self->get_fetch_range($min_rev, $max_rev);
1393         $self->ra->gs_fetch_loop_common($base, $head, [$self]);
1394 }
1395
1396 sub set_tree_cb {
1397         my ($self, $log_entry, $tree, $rev, $date, $author) = @_;
1398         # TODO: enable and test optimized commits:
1399         if (0 && $rev == ($self->{last_rev} + 1)) {
1400                 $log_entry->{revision} = $rev;
1401                 $log_entry->{author} = $author;
1402                 $self->do_git_commit($log_entry, "$rev=$tree");
1403         } else {
1404                 $self->{inject_parents} = { $rev => $tree };
1405                 $self->fetch(undef, undef);
1406         }
1407 }
1408
1409 sub set_tree {
1410         my ($self, $tree) = (shift, shift);
1411         my $log_entry = ::get_commit_entry($tree);
1412         unless ($self->{last_rev}) {
1413                 fatal("Must have an existing revision to commit\n");
1414         }
1415         my %ed_opts = ( r => $self->{last_rev},
1416                         log => $log_entry->{log},
1417                         ra => $self->ra,
1418                         tree_a => $self->{last_commit},
1419                         tree_b => $tree,
1420                         editor_cb => sub {
1421                                $self->set_tree_cb($log_entry, $tree, @_) },
1422                         svn_path => $self->{path} );
1423         if (!SVN::Git::Editor->new(\%ed_opts)->apply_diff) {
1424                 print "No changes\nr$self->{last_rev} = $tree\n";
1425         }
1426 }
1427
1428 sub rebuild {
1429         my ($self) = @_;
1430         print "Rebuilding $self->{db_path} ...\n";
1431         my ($rev_list, $ctx) = command_output_pipe("rev-list", $self->refname);
1432         my $latest;
1433         my $full_url = $self->full_url;
1434         my $svn_uuid;
1435         while (<$rev_list>) {
1436                 chomp;
1437                 my $c = $_;
1438                 die "Non-SHA1: $c\n" unless $c =~ /^$::sha1$/o;
1439                 my ($url, $rev, $uuid) = ::cmt_metadata($c);
1440
1441                 # ignore merges (from set-tree)
1442                 next if (!defined $rev || !$uuid);
1443
1444                 # if we merged or otherwise started elsewhere, this is
1445                 # how we break out of it
1446                 if ((defined $svn_uuid && ($uuid ne $svn_uuid)) ||
1447                     ($full_url && $url && ($url ne $full_url))) {
1448                         next;
1449                 }
1450                 $latest ||= $rev;
1451                 $svn_uuid ||= $uuid;
1452
1453                 $self->rev_db_set($rev, $c);
1454                 print "r$rev = $c\n";
1455         }
1456         command_close_pipe($rev_list, $ctx);
1457         print "Done rebuilding $self->{db_path}\n";
1458 }
1459
1460 # rev_db:
1461 # Tie::File seems to be prone to offset errors if revisions get sparse,
1462 # it's not that fast, either.  Tie::File is also not in Perl 5.6.  So
1463 # one of my favorite modules is out :<  Next up would be one of the DBM
1464 # modules, but I'm not sure which is most portable...  So I'll just
1465 # go with something that's plain-text, but still capable of
1466 # being randomly accessed.  So here's my ultra-simple fixed-width
1467 # database.  All records are 40 characters + "\n", so it's easy to seek
1468 # to a revision: (41 * rev) is the byte offset.
1469 # A record of 40 0s denotes an empty revision.
1470 # And yes, it's still pretty fast (faster than Tie::File).
1471 # These files are disposable unless --no-metadata is set
1472
1473 sub rev_db_set {
1474         my ($self, $rev, $commit, $update_ref) = @_;
1475         length $commit == 40 or croak "arg3 must be a full SHA1 hexsum\n";
1476         my ($db, $db_lock) = ($self->{db_path}, "$self->{db_path}.lock");
1477         my $sig;
1478         if ($update_ref) {
1479                 $SIG{INT} = $SIG{HUP} = $SIG{TERM} = $SIG{ALRM} = $SIG{PIPE} =
1480                             $SIG{USR1} = $SIG{USR2} = sub { $sig = $_[0] };
1481         }
1482         $LOCKFILES{$db_lock} = 1;
1483         if ($_no_metadata) {
1484                 copy($db, $db_lock) or die "rev_db_set(@_): ",
1485                                            "Failed to copy: ",
1486                                            "$db => $db_lock ($!)\n";
1487         } else {
1488                 rename $db, $db_lock or die "rev_db_set(@_): ",
1489                                             "Failed to rename: ",
1490                                             "$db => $db_lock ($!)\n";
1491         }
1492         open my $fh, '+<', $db_lock or croak $!;
1493         my $offset = $rev * 41;
1494         # assume that append is the common case:
1495         seek $fh, 0, 2 or croak $!;
1496         my $pos = tell $fh;
1497         if ($pos < $offset) {
1498                 for (1 .. (($offset - $pos) / 41)) {
1499                         print $fh (('0' x 40),"\n") or croak $!;
1500                 }
1501         }
1502         seek $fh, $offset, 0 or croak $!;
1503         print $fh $commit,"\n" or croak $!;
1504         close $fh or croak $!;
1505         if ($update_ref) {
1506                 command_noisy('update-ref', '-m', "r$rev",
1507                               $self->refname, $commit);
1508         }
1509         rename $db_lock, $db or die "rev_db_set(@_): ", "Failed to rename: ",
1510                                     "$db_lock => $db ($!)\n";
1511         delete $LOCKFILES{$db_lock};
1512         if ($update_ref) {
1513                 $SIG{INT} = $SIG{HUP} = $SIG{TERM} = $SIG{ALRM} = $SIG{PIPE} =
1514                             $SIG{USR1} = $SIG{USR2} = 'DEFAULT';
1515                 kill $sig, $$ if defined $sig;
1516         }
1517 }
1518
1519 sub rev_db_max {
1520         my ($self) = @_;
1521         my @stat = stat $self->{db_path} or
1522                         die "Couldn't stat $self->{db_path}: $!\n";
1523         ($stat[7] % 41) == 0 or
1524                         die "$self->{db_path} inconsistent size:$stat[7]\n";
1525         my $max = $stat[7] / 41;
1526         (($max > 0) ? $max - 1 : 0);
1527 }
1528
1529 sub rev_db_get {
1530         my ($self, $rev) = @_;
1531         my $ret;
1532         my $offset = $rev * 41;
1533         open my $fh, '<', $self->{db_path} or croak $!;
1534         if (sysseek($fh, $offset, 0) == $offset) {
1535                 my $read = sysread($fh, $ret, 40);
1536                 $ret = undef if ($read != 40 || $ret eq ('0'x40));
1537         }
1538         close $fh or croak $!;
1539         $ret;
1540 }
1541
1542 sub find_rev_before {
1543         my ($self, $rev, $eq_ok) = @_;
1544         --$rev unless $eq_ok;
1545         while ($rev > 0) {
1546                 if (my $c = $self->rev_db_get($rev)) {
1547                         return ($rev, $c);
1548                 }
1549                 --$rev;
1550         }
1551         return (undef, undef);
1552 }
1553
1554 sub _new {
1555         my ($class, $repo_id, $ref_id, $path) = @_;
1556         unless (defined $repo_id && length $repo_id) {
1557                 $repo_id = $Git::SVN::default_repo_id;
1558         }
1559         unless (defined $ref_id && length $ref_id) {
1560                 $_[2] = $ref_id = $Git::SVN::default_ref_id;
1561         }
1562         $_[1] = $repo_id = sanitize_remote_name($repo_id);
1563         my $dir = "$ENV{GIT_DIR}/svn/$ref_id";
1564         $_[3] = $path = '' unless (defined $path);
1565         mkpath([$dir]);
1566         unless (-f "$dir/.rev_db") {
1567                 open my $fh, '>>', "$dir/.rev_db" or croak $!;
1568                 close $fh or croak $!;
1569         }
1570         bless { ref_id => $ref_id, dir => $dir, index => "$dir/index",
1571                 path => $path,
1572                 db_path => "$dir/.rev_db", repo_id => $repo_id }, $class;
1573 }
1574
1575 sub uri_encode {
1576         my ($f) = @_;
1577         $f =~ s#([^a-zA-Z0-9\*!\:_\./\-])#uc sprintf("%%%02x",ord($1))#eg;
1578         $f
1579 }
1580
1581 package Git::SVN::Prompt;
1582 use strict;
1583 use warnings;
1584 require SVN::Core;
1585 use vars qw/$_no_auth_cache $_username/;
1586
1587 sub simple {
1588         my ($cred, $realm, $default_username, $may_save, $pool) = @_;
1589         $may_save = undef if $_no_auth_cache;
1590         $default_username = $_username if defined $_username;
1591         if (defined $default_username && length $default_username) {
1592                 if (defined $realm && length $realm) {
1593                         print STDERR "Authentication realm: $realm\n";
1594                         STDERR->flush;
1595                 }
1596                 $cred->username($default_username);
1597         } else {
1598                 username($cred, $realm, $may_save, $pool);
1599         }
1600         $cred->password(_read_password("Password for '" .
1601                                        $cred->username . "': ", $realm));
1602         $cred->may_save($may_save);
1603         $SVN::_Core::SVN_NO_ERROR;
1604 }
1605
1606 sub ssl_server_trust {
1607         my ($cred, $realm, $failures, $cert_info, $may_save, $pool) = @_;
1608         $may_save = undef if $_no_auth_cache;
1609         print STDERR "Error validating server certificate for '$realm':\n";
1610         if ($failures & $SVN::Auth::SSL::UNKNOWNCA) {
1611                 print STDERR " - The certificate is not issued by a trusted ",
1612                       "authority. Use the\n",
1613                       "   fingerprint to validate the certificate manually!\n";
1614         }
1615         if ($failures & $SVN::Auth::SSL::CNMISMATCH) {
1616                 print STDERR " - The certificate hostname does not match.\n";
1617         }
1618         if ($failures & $SVN::Auth::SSL::NOTYETVALID) {
1619                 print STDERR " - The certificate is not yet valid.\n";
1620         }
1621         if ($failures & $SVN::Auth::SSL::EXPIRED) {
1622                 print STDERR " - The certificate has expired.\n";
1623         }
1624         if ($failures & $SVN::Auth::SSL::OTHER) {
1625                 print STDERR " - The certificate has an unknown error.\n";
1626         }
1627         printf STDERR
1628                 "Certificate information:\n".
1629                 " - Hostname: %s\n".
1630                 " - Valid: from %s until %s\n".
1631                 " - Issuer: %s\n".
1632                 " - Fingerprint: %s\n",
1633                 map $cert_info->$_, qw(hostname valid_from valid_until
1634                                        issuer_dname fingerprint);
1635         my $choice;
1636 prompt:
1637         print STDERR $may_save ?
1638               "(R)eject, accept (t)emporarily or accept (p)ermanently? " :
1639               "(R)eject or accept (t)emporarily? ";
1640         STDERR->flush;
1641         $choice = lc(substr(<STDIN> || 'R', 0, 1));
1642         if ($choice =~ /^t$/i) {
1643                 $cred->may_save(undef);
1644         } elsif ($choice =~ /^r$/i) {
1645                 return -1;
1646         } elsif ($may_save && $choice =~ /^p$/i) {
1647                 $cred->may_save($may_save);
1648         } else {
1649                 goto prompt;
1650         }
1651         $cred->accepted_failures($failures);
1652         $SVN::_Core::SVN_NO_ERROR;
1653 }
1654
1655 sub ssl_client_cert {
1656         my ($cred, $realm, $may_save, $pool) = @_;
1657         $may_save = undef if $_no_auth_cache;
1658         print STDERR "Client certificate filename: ";
1659         STDERR->flush;
1660         chomp(my $filename = <STDIN>);
1661         $cred->cert_file($filename);
1662         $cred->may_save($may_save);
1663         $SVN::_Core::SVN_NO_ERROR;
1664 }
1665
1666 sub ssl_client_cert_pw {
1667         my ($cred, $realm, $may_save, $pool) = @_;
1668         $may_save = undef if $_no_auth_cache;
1669         $cred->password(_read_password("Password: ", $realm));
1670         $cred->may_save($may_save);
1671         $SVN::_Core::SVN_NO_ERROR;
1672 }
1673
1674 sub username {
1675         my ($cred, $realm, $may_save, $pool) = @_;
1676         $may_save = undef if $_no_auth_cache;
1677         if (defined $realm && length $realm) {
1678                 print STDERR "Authentication realm: $realm\n";
1679         }
1680         my $username;
1681         if (defined $_username) {
1682                 $username = $_username;
1683         } else {
1684                 print STDERR "Username: ";
1685                 STDERR->flush;
1686                 chomp($username = <STDIN>);
1687         }
1688         $cred->username($username);
1689         $cred->may_save($may_save);
1690         $SVN::_Core::SVN_NO_ERROR;
1691 }
1692
1693 sub _read_password {
1694         my ($prompt, $realm) = @_;
1695         print STDERR $prompt;
1696         STDERR->flush;
1697         require Term::ReadKey;
1698         Term::ReadKey::ReadMode('noecho');
1699         my $password = '';
1700         while (defined(my $key = Term::ReadKey::ReadKey(0))) {
1701                 last if $key =~ /[\012\015]/; # \n\r
1702                 $password .= $key;
1703         }
1704         Term::ReadKey::ReadMode('restore');
1705         print STDERR "\n";
1706         STDERR->flush;
1707         $password;
1708 }
1709
1710 package main;
1711
1712 {
1713         my $kill_stupid_warnings = $SVN::Node::none.$SVN::Node::file.
1714                                 $SVN::Node::dir.$SVN::Node::unknown.
1715                                 $SVN::Node::none.$SVN::Node::file.
1716                                 $SVN::Node::dir.$SVN::Node::unknown.
1717                                 $SVN::Auth::SSL::CNMISMATCH.
1718                                 $SVN::Auth::SSL::NOTYETVALID.
1719                                 $SVN::Auth::SSL::EXPIRED.
1720                                 $SVN::Auth::SSL::UNKNOWNCA.
1721                                 $SVN::Auth::SSL::OTHER;
1722 }
1723
1724 package SVN::Git::Fetcher;
1725 use vars qw/@ISA/;
1726 use strict;
1727 use warnings;
1728 use Carp qw/croak/;
1729 use IO::File qw//;
1730 use Digest::MD5;
1731
1732 # file baton members: path, mode_a, mode_b, pool, fh, blob, base
1733 sub new {
1734         my ($class, $git_svn) = @_;
1735         my $self = SVN::Delta::Editor->new;
1736         bless $self, $class;
1737         $self->{c} = $git_svn->{last_commit} if exists $git_svn->{last_commit};
1738         $self->{empty} = {};
1739         $self->{dir_prop} = {};
1740         $self->{file_prop} = {};
1741         $self->{absent_dir} = {};
1742         $self->{absent_file} = {};
1743         $self->{gii} = $git_svn->tmp_index_do(sub { Git::IndexInfo->new });
1744         $self;
1745 }
1746
1747 sub set_path_strip {
1748         my ($self, $path) = @_;
1749         $self->{path_strip} = qr/^\Q$path\E\/?/;
1750 }
1751
1752 sub open_root {
1753         { path => '' };
1754 }
1755
1756 sub open_directory {
1757         my ($self, $path, $pb, $rev) = @_;
1758         { path => $path };
1759 }
1760
1761 sub git_path {
1762         my ($self, $path) = @_;
1763         if ($self->{path_strip}) {
1764                 $path =~ s!$self->{path_strip}!! or
1765                   die "Failed to strip path '$path' ($self->{path_strip})\n";
1766         }
1767         $path;
1768 }
1769
1770 sub delete_entry {
1771         my ($self, $path, $rev, $pb) = @_;
1772
1773         my $gpath = $self->git_path($path);
1774         return undef if ($gpath eq '');
1775
1776         # remove entire directories.
1777         if (command('ls-tree', $self->{c}, '--', $gpath) =~ /^040000 tree/) {
1778                 my ($ls, $ctx) = command_output_pipe(qw/ls-tree
1779                                                      -r --name-only -z/,
1780                                                      $self->{c}, '--', $gpath);
1781                 local $/ = "\0";
1782                 while (<$ls>) {
1783                         chomp;
1784                         $self->{gii}->remove($_);
1785                         print "\tD\t$_\n" unless $self->{q};
1786                 }
1787                 print "\tD\t$gpath/\n" unless $self->{q};
1788                 command_close_pipe($ls, $ctx);
1789                 $self->{empty}->{$path} = 0
1790         } else {
1791                 $self->{gii}->remove($gpath);
1792                 print "\tD\t$gpath\n" unless $self->{q};
1793         }
1794         undef;
1795 }
1796
1797 sub open_file {
1798         my ($self, $path, $pb, $rev) = @_;
1799         my $gpath = $self->git_path($path);
1800         my ($mode, $blob) = (command('ls-tree', $self->{c}, '--', $gpath)
1801                              =~ /^(\d{6}) blob ([a-f\d]{40})\t/);
1802         unless (defined $mode && defined $blob) {
1803                 die "$path was not found in commit $self->{c} (r$rev)\n";
1804         }
1805         { path => $path, mode_a => $mode, mode_b => $mode, blob => $blob,
1806           pool => SVN::Pool->new, action => 'M' };
1807 }
1808
1809 sub add_file {
1810         my ($self, $path, $pb, $cp_path, $cp_rev) = @_;
1811         my ($dir, $file) = ($path =~ m#^(.*?)/?([^/]+)$#);
1812         delete $self->{empty}->{$dir};
1813         { path => $path, mode_a => 100644, mode_b => 100644,
1814           pool => SVN::Pool->new, action => 'A' };
1815 }
1816
1817 sub add_directory {
1818         my ($self, $path, $cp_path, $cp_rev) = @_;
1819         my ($dir, $file) = ($path =~ m#^(.*?)/?([^/]+)$#);
1820         delete $self->{empty}->{$dir};
1821         $self->{empty}->{$path} = 1;
1822         { path => $path };
1823 }
1824
1825 sub change_dir_prop {
1826         my ($self, $db, $prop, $value) = @_;
1827         $self->{dir_prop}->{$db->{path}} ||= {};
1828         $self->{dir_prop}->{$db->{path}}->{$prop} = $value;
1829         undef;
1830 }
1831
1832 sub absent_directory {
1833         my ($self, $path, $pb) = @_;
1834         $self->{absent_dir}->{$pb->{path}} ||= [];
1835         push @{$self->{absent_dir}->{$pb->{path}}}, $path;
1836         undef;
1837 }
1838
1839 sub absent_file {
1840         my ($self, $path, $pb) = @_;
1841         $self->{absent_file}->{$pb->{path}} ||= [];
1842         push @{$self->{absent_file}->{$pb->{path}}}, $path;
1843         undef;
1844 }
1845
1846 sub change_file_prop {
1847         my ($self, $fb, $prop, $value) = @_;
1848         if ($prop eq 'svn:executable') {
1849                 if ($fb->{mode_b} != 120000) {
1850                         $fb->{mode_b} = defined $value ? 100755 : 100644;
1851                 }
1852         } elsif ($prop eq 'svn:special') {
1853                 $fb->{mode_b} = defined $value ? 120000 : 100644;
1854         } else {
1855                 $self->{file_prop}->{$fb->{path}} ||= {};
1856                 $self->{file_prop}->{$fb->{path}}->{$prop} = $value;
1857         }
1858         undef;
1859 }
1860
1861 sub apply_textdelta {
1862         my ($self, $fb, $exp) = @_;
1863         my $fh = IO::File->new_tmpfile;
1864         $fh->autoflush(1);
1865         # $fh gets auto-closed() by SVN::TxDelta::apply(),
1866         # (but $base does not,) so dup() it for reading in close_file
1867         open my $dup, '<&', $fh or croak $!;
1868         my $base = IO::File->new_tmpfile;
1869         $base->autoflush(1);
1870         if ($fb->{blob}) {
1871                 defined (my $pid = fork) or croak $!;
1872                 if (!$pid) {
1873                         open STDOUT, '>&', $base or croak $!;
1874                         print STDOUT 'link ' if ($fb->{mode_a} == 120000);
1875                         exec qw/git-cat-file blob/, $fb->{blob} or croak $!;
1876                 }
1877                 waitpid $pid, 0;
1878                 croak $? if $?;
1879
1880                 if (defined $exp) {
1881                         seek $base, 0, 0 or croak $!;
1882                         my $md5 = Digest::MD5->new;
1883                         $md5->addfile($base);
1884                         my $got = $md5->hexdigest;
1885                         die "Checksum mismatch: $fb->{path} $fb->{blob}\n",
1886                             "expected: $exp\n",
1887                             "     got: $got\n" if ($got ne $exp);
1888                 }
1889         }
1890         seek $base, 0, 0 or croak $!;
1891         $fb->{fh} = $dup;
1892         $fb->{base} = $base;
1893         [ SVN::TxDelta::apply($base, $fh, undef, $fb->{path}, $fb->{pool}) ];
1894 }
1895
1896 sub close_file {
1897         my ($self, $fb, $exp) = @_;
1898         my $hash;
1899         my $path = $self->git_path($fb->{path});
1900         if (my $fh = $fb->{fh}) {
1901                 seek($fh, 0, 0) or croak $!;
1902                 my $md5 = Digest::MD5->new;
1903                 $md5->addfile($fh);
1904                 my $got = $md5->hexdigest;
1905                 die "Checksum mismatch: $path\n",
1906                     "expected: $exp\n    got: $got\n" if ($got ne $exp);
1907                 seek($fh, 0, 0) or croak $!;
1908                 if ($fb->{mode_b} == 120000) {
1909                         read($fh, my $buf, 5) == 5 or croak $!;
1910                         $buf eq 'link ' or die "$path has mode 120000",
1911                                                "but is not a link\n";
1912                 }
1913                 defined(my $pid = open my $out,'-|') or die "Can't fork: $!\n";
1914                 if (!$pid) {
1915                         open STDIN, '<&', $fh or croak $!;
1916                         exec qw/git-hash-object -w --stdin/ or croak $!;
1917                 }
1918                 chomp($hash = do { local $/; <$out> });
1919                 close $out or croak $!;
1920                 close $fh or croak $!;
1921                 $hash =~ /^[a-f\d]{40}$/ or die "not a sha1: $hash\n";
1922                 close $fb->{base} or croak $!;
1923         } else {
1924                 $hash = $fb->{blob} or die "no blob information\n";
1925         }
1926         $fb->{pool}->clear;
1927         $self->{gii}->update($fb->{mode_b}, $hash, $path) or croak $!;
1928         print "\t$fb->{action}\t$path\n" if $fb->{action} && ! $self->{q};
1929         undef;
1930 }
1931
1932 sub abort_edit {
1933         my $self = shift;
1934         $self->{nr} = $self->{gii}->{nr};
1935         delete $self->{gii};
1936         $self->SUPER::abort_edit(@_);
1937 }
1938
1939 sub close_edit {
1940         my $self = shift;
1941         $self->{git_commit_ok} = 1;
1942         $self->{nr} = $self->{gii}->{nr};
1943         delete $self->{gii};
1944         $self->SUPER::close_edit(@_);
1945 }
1946
1947 package SVN::Git::Editor;
1948 use vars qw/@ISA $_rmdir $_cp_similarity $_find_copies_harder $_rename_limit/;
1949 use strict;
1950 use warnings;
1951 use Carp qw/croak/;
1952 use IO::File;
1953 use Digest::MD5;
1954
1955 sub new {
1956         my ($class, $opts) = @_;
1957         foreach (qw/svn_path r ra tree_a tree_b log editor_cb/) {
1958                 die "$_ required!\n" unless (defined $opts->{$_});
1959         }
1960
1961         my $pool = SVN::Pool->new;
1962         my $mods = generate_diff($opts->{tree_a}, $opts->{tree_b});
1963         my $types = check_diff_paths($opts->{ra}, $opts->{svn_path},
1964                                      $opts->{r}, $mods);
1965
1966         # $opts->{ra} functions should not be used after this:
1967         my @ce  = $opts->{ra}->get_commit_editor($opts->{log},
1968                                                 $opts->{editor_cb}, $pool);
1969         my $self = SVN::Delta::Editor->new(@ce, $pool);
1970         bless $self, $class;
1971         foreach (qw/svn_path r tree_a tree_b/) {
1972                 $self->{$_} = $opts->{$_};
1973         }
1974         $self->{url} = $opts->{ra}->{url};
1975         $self->{mods} = $mods;
1976         $self->{types} = $types;
1977         $self->{pool} = $pool;
1978         $self->{bat} = { '' => $self->open_root($self->{r}, $self->{pool}) };
1979         $self->{rm} = { };
1980         $self->{path_prefix} = length $self->{svn_path} ?
1981                                "$self->{svn_path}/" : '';
1982         return $self;
1983 }
1984
1985 sub generate_diff {
1986         my ($tree_a, $tree_b) = @_;
1987         my @diff_tree = qw(diff-tree -z -r);
1988         if ($_cp_similarity) {
1989                 push @diff_tree, "-C$_cp_similarity";
1990         } else {
1991                 push @diff_tree, '-C';
1992         }
1993         push @diff_tree, '--find-copies-harder' if $_find_copies_harder;
1994         push @diff_tree, "-l$_rename_limit" if defined $_rename_limit;
1995         push @diff_tree, $tree_a, $tree_b;
1996         my ($diff_fh, $ctx) = command_output_pipe(@diff_tree);
1997         local $/ = "\0";
1998         my $state = 'meta';
1999         my @mods;
2000         while (<$diff_fh>) {
2001                 chomp $_; # this gets rid of the trailing "\0"
2002                 if ($state eq 'meta' && /^:(\d{6})\s(\d{6})\s
2003                                         $::sha1\s($::sha1)\s
2004                                         ([MTCRAD])\d*$/xo) {
2005                         push @mods, {   mode_a => $1, mode_b => $2,
2006                                         sha1_b => $3, chg => $4 };
2007                         if ($4 =~ /^(?:C|R)$/) {
2008                                 $state = 'file_a';
2009                         } else {
2010                                 $state = 'file_b';
2011                         }
2012                 } elsif ($state eq 'file_a') {
2013                         my $x = $mods[$#mods] or croak "Empty array\n";
2014                         if ($x->{chg} !~ /^(?:C|R)$/) {
2015                                 croak "Error parsing $_, $x->{chg}\n";
2016                         }
2017                         $x->{file_a} = $_;
2018                         $state = 'file_b';
2019                 } elsif ($state eq 'file_b') {
2020                         my $x = $mods[$#mods] or croak "Empty array\n";
2021                         if (exists $x->{file_a} && $x->{chg} !~ /^(?:C|R)$/) {
2022                                 croak "Error parsing $_, $x->{chg}\n";
2023                         }
2024                         if (!exists $x->{file_a} && $x->{chg} =~ /^(?:C|R)$/) {
2025                                 croak "Error parsing $_, $x->{chg}\n";
2026                         }
2027                         $x->{file_b} = $_;
2028                         $state = 'meta';
2029                 } else {
2030                         croak "Error parsing $_\n";
2031                 }
2032         }
2033         command_close_pipe($diff_fh, $ctx);
2034         \@mods;
2035 }
2036
2037 sub check_diff_paths {
2038         my ($ra, $pfx, $rev, $mods) = @_;
2039         my %types;
2040         $pfx .= '/' if length $pfx;
2041
2042         sub type_diff_paths {
2043                 my ($ra, $types, $path, $rev) = @_;
2044                 my @p = split m#/+#, $path;
2045                 my $c = shift @p;
2046                 unless (defined $types->{$c}) {
2047                         $types->{$c} = $ra->check_path($c, $rev);
2048                 }
2049                 while (@p) {
2050                         $c .= '/' . shift @p;
2051                         next if defined $types->{$c};
2052                         $types->{$c} = $ra->check_path($c, $rev);
2053                 }
2054         }
2055
2056         foreach my $m (@$mods) {
2057                 foreach my $f (qw/file_a file_b/) {
2058                         next unless defined $m->{$f};
2059                         my ($dir) = ($m->{$f} =~ m#^(.*?)/?(?:[^/]+)$#);
2060                         if (length $pfx.$dir && ! defined $types{$dir}) {
2061                                 type_diff_paths($ra, \%types, $pfx.$dir, $rev);
2062                         }
2063                 }
2064         }
2065         \%types;
2066 }
2067
2068 sub split_path {
2069         return ($_[0] =~ m#^(.*?)/?([^/]+)$#);
2070 }
2071
2072 sub repo_path {
2073         my ($self, $path) = @_;
2074         $self->{path_prefix}.(defined $path ? $path : '');
2075 }
2076
2077 sub url_path {
2078         my ($self, $path) = @_;
2079         $self->{url} . '/' . $self->repo_path($path);
2080 }
2081
2082 sub rmdirs {
2083         my ($self) = @_;
2084         my $rm = $self->{rm};
2085         delete $rm->{''}; # we never delete the url we're tracking
2086         return unless %$rm;
2087
2088         foreach (keys %$rm) {
2089                 my @d = split m#/#, $_;
2090                 my $c = shift @d;
2091                 $rm->{$c} = 1;
2092                 while (@d) {
2093                         $c .= '/' . shift @d;
2094                         $rm->{$c} = 1;
2095                 }
2096         }
2097         delete $rm->{$self->{svn_path}};
2098         delete $rm->{''}; # we never delete the url we're tracking
2099         return unless %$rm;
2100
2101         my ($fh, $ctx) = command_output_pipe(qw/ls-tree --name-only -r -z/,
2102                                              $self->{tree_b});
2103         local $/ = "\0";
2104         while (<$fh>) {
2105                 chomp;
2106                 my @dn = split m#/#, $_;
2107                 while (pop @dn) {
2108                         delete $rm->{join '/', @dn};
2109                 }
2110                 unless (%$rm) {
2111                         close $fh;
2112                         return;
2113                 }
2114         }
2115         command_close_pipe($fh, $ctx);
2116
2117         my ($r, $p, $bat) = ($self->{r}, $self->{pool}, $self->{bat});
2118         foreach my $d (sort { $b =~ tr#/#/# <=> $a =~ tr#/#/# } keys %$rm) {
2119                 $self->close_directory($bat->{$d}, $p);
2120                 my ($dn) = ($d =~ m#^(.*?)/?(?:[^/]+)$#);
2121                 print "\tD+\t$d/\n" unless $::_q;
2122                 $self->SUPER::delete_entry($d, $r, $bat->{$dn}, $p);
2123                 delete $bat->{$d};
2124         }
2125 }
2126
2127 sub open_or_add_dir {
2128         my ($self, $full_path, $baton) = @_;
2129         my $t = $self->{types}->{$full_path};
2130         if (!defined $t) {
2131                 die "$full_path not known in r$self->{r} or we have a bug!\n";
2132         }
2133         if ($t == $SVN::Node::none) {
2134                 return $self->add_directory($full_path, $baton,
2135                                                 undef, -1, $self->{pool});
2136         } elsif ($t == $SVN::Node::dir) {
2137                 return $self->open_directory($full_path, $baton,
2138                                                 $self->{r}, $self->{pool});
2139         }
2140         print STDERR "$full_path already exists in repository at ",
2141                 "r$self->{r} and it is not a directory (",
2142                 ($t == $SVN::Node::file ? 'file' : 'unknown'),"/$t)\n";
2143         exit 1;
2144 }
2145
2146 sub ensure_path {
2147         my ($self, $path) = @_;
2148         my $bat = $self->{bat};
2149         my $repo_path = $self->repo_path($path);
2150         return $bat->{''} unless (length $repo_path);
2151         my @p = split m#/+#, $repo_path;
2152         my $c = shift @p;
2153         $bat->{$c} ||= $self->open_or_add_dir($c, $bat->{''});
2154         while (@p) {
2155                 my $c0 = $c;
2156                 $c .= '/' . shift @p;
2157                 $bat->{$c} ||= $self->open_or_add_dir($c, $bat->{$c0});
2158         }
2159         return $bat->{$c};
2160 }
2161
2162 sub A {
2163         my ($self, $m) = @_;
2164         my ($dir, $file) = split_path($m->{file_b});
2165         my $pbat = $self->ensure_path($dir);
2166         my $fbat = $self->add_file($self->repo_path($m->{file_b}), $pbat,
2167                                         undef, -1);
2168         print "\tA\t$m->{file_b}\n" unless $::_q;
2169         $self->chg_file($fbat, $m);
2170         $self->close_file($fbat,undef,$self->{pool});
2171 }
2172
2173 sub C {
2174         my ($self, $m) = @_;
2175         my ($dir, $file) = split_path($m->{file_b});
2176         my $pbat = $self->ensure_path($dir);
2177         my $fbat = $self->add_file($self->repo_path($m->{file_b}), $pbat,
2178                                 $self->url_path($m->{file_a}), $self->{r});
2179         print "\tC\t$m->{file_a} => $m->{file_b}\n" unless $::_q;
2180         $self->chg_file($fbat, $m);
2181         $self->close_file($fbat,undef,$self->{pool});
2182 }
2183
2184 sub delete_entry {
2185         my ($self, $path, $pbat) = @_;
2186         my $rpath = $self->repo_path($path);
2187         my ($dir, $file) = split_path($rpath);
2188         $self->{rm}->{$dir} = 1;
2189         $self->SUPER::delete_entry($rpath, $self->{r}, $pbat, $self->{pool});
2190 }
2191
2192 sub R {
2193         my ($self, $m) = @_;
2194         my ($dir, $file) = split_path($m->{file_b});
2195         my $pbat = $self->ensure_path($dir);
2196         my $fbat = $self->add_file($self->repo_path($m->{file_b}), $pbat,
2197                                 $self->url_path($m->{file_a}), $self->{r});
2198         print "\tR\t$m->{file_a} => $m->{file_b}\n" unless $::_q;
2199         $self->chg_file($fbat, $m);
2200         $self->close_file($fbat,undef,$self->{pool});
2201
2202         ($dir, $file) = split_path($m->{file_a});
2203         $pbat = $self->ensure_path($dir);
2204         $self->delete_entry($m->{file_a}, $pbat);
2205 }
2206
2207 sub M {
2208         my ($self, $m) = @_;
2209         my ($dir, $file) = split_path($m->{file_b});
2210         my $pbat = $self->ensure_path($dir);
2211         my $fbat = $self->open_file($self->repo_path($m->{file_b}),
2212                                 $pbat,$self->{r},$self->{pool});
2213         print "\t$m->{chg}\t$m->{file_b}\n" unless $::_q;
2214         $self->chg_file($fbat, $m);
2215         $self->close_file($fbat,undef,$self->{pool});
2216 }
2217
2218 sub T { shift->M(@_) }
2219
2220 sub change_file_prop {
2221         my ($self, $fbat, $pname, $pval) = @_;
2222         $self->SUPER::change_file_prop($fbat, $pname, $pval, $self->{pool});
2223 }
2224
2225 sub chg_file {
2226         my ($self, $fbat, $m) = @_;
2227         if ($m->{mode_b} =~ /755$/ && $m->{mode_a} !~ /755$/) {
2228                 $self->change_file_prop($fbat,'svn:executable','*');
2229         } elsif ($m->{mode_b} !~ /755$/ && $m->{mode_a} =~ /755$/) {
2230                 $self->change_file_prop($fbat,'svn:executable',undef);
2231         }
2232         my $fh = IO::File->new_tmpfile or croak $!;
2233         if ($m->{mode_b} =~ /^120/) {
2234                 print $fh 'link ' or croak $!;
2235                 $self->change_file_prop($fbat,'svn:special','*');
2236         } elsif ($m->{mode_a} =~ /^120/ && $m->{mode_b} !~ /^120/) {
2237                 $self->change_file_prop($fbat,'svn:special',undef);
2238         }
2239         defined(my $pid = fork) or croak $!;
2240         if (!$pid) {
2241                 open STDOUT, '>&', $fh or croak $!;
2242                 exec qw/git-cat-file blob/, $m->{sha1_b} or croak $!;
2243         }
2244         waitpid $pid, 0;
2245         croak $? if $?;
2246         $fh->flush == 0 or croak $!;
2247         seek $fh, 0, 0 or croak $!;
2248
2249         my $md5 = Digest::MD5->new;
2250         $md5->addfile($fh) or croak $!;
2251         seek $fh, 0, 0 or croak $!;
2252
2253         my $exp = $md5->hexdigest;
2254         my $pool = SVN::Pool->new;
2255         my $atd = $self->apply_textdelta($fbat, undef, $pool);
2256         my $got = SVN::TxDelta::send_stream($fh, @$atd, $pool);
2257         die "Checksum mismatch\nexpected: $exp\ngot: $got\n" if ($got ne $exp);
2258         $pool->clear;
2259
2260         close $fh or croak $!;
2261 }
2262
2263 sub D {
2264         my ($self, $m) = @_;
2265         my ($dir, $file) = split_path($m->{file_b});
2266         my $pbat = $self->ensure_path($dir);
2267         print "\tD\t$m->{file_b}\n" unless $::_q;
2268         $self->delete_entry($m->{file_b}, $pbat);
2269 }
2270
2271 sub close_edit {
2272         my ($self) = @_;
2273         my ($p,$bat) = ($self->{pool}, $self->{bat});
2274         foreach (sort { $b =~ tr#/#/# <=> $a =~ tr#/#/# } keys %$bat) {
2275                 $self->close_directory($bat->{$_}, $p);
2276         }
2277         $self->SUPER::close_edit($p);
2278         $p->clear;
2279 }
2280
2281 sub abort_edit {
2282         my ($self) = @_;
2283         $self->SUPER::abort_edit($self->{pool});
2284 }
2285
2286 sub DESTROY {
2287         my $self = shift;
2288         $self->SUPER::DESTROY(@_);
2289         $self->{pool}->clear;
2290 }
2291
2292 # this drives the editor
2293 sub apply_diff {
2294         my ($self) = @_;
2295         my $mods = $self->{mods};
2296         my %o = ( D => 1, R => 0, C => -1, A => 3, M => 3, T => 3 );
2297         foreach my $m (sort { $o{$a->{chg}} <=> $o{$b->{chg}} } @$mods) {
2298                 my $f = $m->{chg};
2299                 if (defined $o{$f}) {
2300                         $self->$f($m);
2301                 } else {
2302                         fatal("Invalid change type: $f\n");
2303                 }
2304         }
2305         $self->rmdirs if $_rmdir;
2306         if (@$mods == 0) {
2307                 $self->abort_edit;
2308         } else {
2309                 $self->close_edit;
2310         }
2311         return scalar @$mods;
2312 }
2313
2314 package Git::SVN::Ra;
2315 use vars qw/@ISA $config_dir/;
2316 use strict;
2317 use warnings;
2318 my ($can_do_switch);
2319 my $RA;
2320
2321 BEGIN {
2322         # enforce temporary pool usage for some simple functions
2323         my $e;
2324         foreach (qw/get_latest_revnum rev_proplist get_file
2325                     check_path get_dir get_uuid get_repos_root/) {
2326                 $e .= "sub $_ {
2327                         my \$self = shift;
2328                         my \$pool = SVN::Pool->new;
2329                         my \@ret = \$self->SUPER::$_(\@_,\$pool);
2330                         \$pool->clear;
2331                         wantarray ? \@ret : \$ret[0]; }\n";
2332         }
2333         eval $e;
2334 }
2335
2336 sub new {
2337         my ($class, $url) = @_;
2338         $url =~ s!/+$!!;
2339         return $RA if ($RA && $RA->{url} eq $url);
2340
2341         SVN::_Core::svn_config_ensure($config_dir, undef);
2342         my ($baton, $callbacks) = SVN::Core::auth_open_helper([
2343             SVN::Client::get_simple_provider(),
2344             SVN::Client::get_ssl_server_trust_file_provider(),
2345             SVN::Client::get_simple_prompt_provider(
2346               \&Git::SVN::Prompt::simple, 2),
2347             SVN::Client::get_ssl_client_cert_prompt_provider(
2348               \&Git::SVN::Prompt::ssl_client_cert, 2),
2349             SVN::Client::get_ssl_client_cert_pw_prompt_provider(
2350               \&Git::SVN::Prompt::ssl_client_cert_pw, 2),
2351             SVN::Client::get_username_provider(),
2352             SVN::Client::get_ssl_server_trust_prompt_provider(
2353               \&Git::SVN::Prompt::ssl_server_trust),
2354             SVN::Client::get_username_prompt_provider(
2355               \&Git::SVN::Prompt::username, 2),
2356           ]);
2357         my $config = SVN::Core::config_get_config($config_dir);
2358         my $self = SVN::Ra->new(url => $url, auth => $baton,
2359                               config => $config,
2360                               pool => SVN::Pool->new,
2361                               auth_provider_callbacks => $callbacks);
2362         $self->{svn_path} = $url;
2363         $self->{repos_root} = $self->get_repos_root;
2364         $self->{svn_path} =~ s#^\Q$self->{repos_root}\E/*##;
2365         $RA = bless $self, $class;
2366 }
2367
2368 sub DESTROY {
2369         # do not call the real DESTROY since we store ourselves in $RA
2370 }
2371
2372 sub get_log {
2373         my ($self, @args) = @_;
2374         my $pool = SVN::Pool->new;
2375         splice(@args, 3, 1) if ($SVN::Core::VERSION le '1.2.0');
2376         my $ret = $self->SUPER::get_log(@args, $pool);
2377         $pool->clear;
2378         $ret;
2379 }
2380
2381 sub get_commit_editor {
2382         my ($self, $log, $cb, $pool) = @_;
2383         my @lock = $SVN::Core::VERSION ge '1.2.0' ? (undef, 0) : ();
2384         $self->SUPER::get_commit_editor($log, $cb, @lock, $pool);
2385 }
2386
2387 sub uuid {
2388         my ($self) = @_;
2389         $self->{uuid} ||= $self->get_uuid;
2390 }
2391
2392 sub gs_do_update {
2393         my ($self, $rev_a, $rev_b, $gs, $editor) = @_;
2394         my $new = ($rev_a == $rev_b);
2395         my $path = $gs->{path};
2396
2397         my $ta = $self->check_path($path, $rev_a);
2398         my $tb = $new ? $ta : $self->check_path($path, $rev_b);
2399         return 1 if ($tb != $SVN::Node::dir && $ta != $SVN::Node::dir);
2400         if ($ta == $SVN::Node::none) {
2401                 $rev_a = $rev_b;
2402                 $new = 1;
2403         }
2404
2405         my $pool = SVN::Pool->new;
2406         $editor->set_path_strip($path);
2407         my (@pc) = split m#/#, $path;
2408         my $reporter = $self->do_update($rev_b, (@pc ? shift @pc : ''),
2409                                         1, $editor, $pool);
2410         my @lock = $SVN::Core::VERSION ge '1.2.0' ? (undef) : ();
2411
2412         # Since we can't rely on svn_ra_reparent being available, we'll
2413         # just have to do some magic with set_path to make it so
2414         # we only want a partial path.
2415         my $sp = '';
2416         my $final = join('/', @pc);
2417         while (@pc) {
2418                 $reporter->set_path($sp, $rev_b, 0, @lock, $pool);
2419                 $sp .= '/' if length $sp;
2420                 $sp .= shift @pc;
2421         }
2422         die "BUG: '$sp' != '$final'\n" if ($sp ne $final);
2423
2424         $reporter->set_path($sp, $rev_a, $new, @lock, $pool);
2425
2426         $reporter->finish_report($pool);
2427         $pool->clear;
2428         $editor->{git_commit_ok};
2429 }
2430
2431 # this requires SVN 1.4.3 or later (do_switch didn't work before 1.4.3, and
2432 # svn_ra_reparent didn't work before 1.4)
2433 sub gs_do_switch {
2434         my ($self, $rev_a, $rev_b, $gs, $url_b, $editor) = @_;
2435         my $path = $gs->{path};
2436         my $pool = SVN::Pool->new;
2437
2438         my $full_url = $self->{url};
2439         my $old_url = $full_url;
2440         $full_url .= "/$path" if length $path;
2441         my ($ra, $reparented);
2442         if ($old_url ne $full_url) {
2443                 if ($old_url !~ m#^svn(\+ssh)?://#) {
2444                         SVN::_Ra::svn_ra_reparent($self->{session}, $full_url,
2445                                                   $pool);
2446                         $self->{url} = $full_url;
2447                         $reparented = 1;
2448                 } else {
2449                         $ra = Git::SVN::Ra->new($full_url);
2450                 }
2451         }
2452         $ra ||= $self;
2453         my $reporter = $ra->do_switch($rev_b, '', 1, $url_b, $editor, $pool);
2454         my @lock = $SVN::Core::VERSION ge '1.2.0' ? (undef) : ();
2455         $reporter->set_path('', $rev_a, 0, @lock, $pool);
2456         $reporter->finish_report($pool);
2457
2458         if ($reparented) {
2459                 SVN::_Ra::svn_ra_reparent($self->{session}, $old_url, $pool);
2460                 $self->{url} = $old_url;
2461         }
2462
2463         $pool->clear;
2464         $editor->{git_commit_ok};
2465 }
2466
2467 sub gs_fetch_loop_common {
2468         my ($self, $base, $head, $gsv, $globs) = @_;
2469         return if ($base > $head);
2470         my $inc = 1000;
2471         my ($min, $max) = ($base, $head < $base + $inc ? $head : $base + $inc);
2472         my %common;
2473         my $common_max = scalar @$gsv;
2474
2475         foreach my $gs (@$gsv) {
2476                 if (my $last_commit = $gs->last_commit) {
2477                         $gs->assert_index_clean($last_commit);
2478                 }
2479                 my @tmp = split m#/#, $gs->{path};
2480                 my $p = '';
2481                 foreach (@tmp) {
2482                         $p .= length($p) ? "/$_" : $_;
2483                         $common{$p} ||= 0;
2484                         $common{$p}++;
2485                 }
2486         }
2487         $globs ||= [];
2488         $common_max += scalar @$globs;
2489         foreach my $glob (@$globs) {
2490                 my @tmp = split m#/#, $glob->{path}->{left};
2491                 my $p = '';
2492                 foreach (@tmp) {
2493                         $p .= length($p) ? "/$_" : $_;
2494                         $common{$p} ||= 0;
2495                         $common{$p}++;
2496                 }
2497         }
2498
2499         my $longest_path = '';
2500         foreach (sort {length $b <=> length $a} keys %common) {
2501                 if ($common{$_} == $common_max) {
2502                         $longest_path = $_;
2503                         last;
2504                 }
2505         }
2506         while (1) {
2507                 my %revs;
2508                 my $err;
2509                 my $err_handler = $SVN::Error::handler;
2510                 $SVN::Error::handler = sub {
2511                         ($err) = @_;
2512                         skip_unknown_revs($err);
2513                 };
2514                 sub _cb {
2515                         my ($paths, $r, $author, $date, $log) = @_;
2516                         [ dup_changed_paths($paths),
2517                           { author => $author, date => $date, log => $log } ];
2518                 }
2519                 $self->get_log([$longest_path], $min, $max, 0, 1, 1,
2520                                sub { $revs{$_[1]} = _cb(@_) });
2521                 if ($err && $max >= $head) {
2522                         print STDERR "Path '$longest_path' ",
2523                                      "was probably deleted:\n",
2524                                      $err->expanded_message,
2525                                      "\nWill attempt to follow ",
2526                                      "revisions r$min .. r$max ",
2527                                      "committed before the deletion\n";
2528                         my $hi = $max;
2529                         while (--$hi >= $min) {
2530                                 my $ok;
2531                                 $self->get_log([$longest_path], $min, $hi,
2532                                                0, 1, 1, sub {
2533                                                $ok ||= $_[1];
2534                                                $revs{$_[1]} = _cb(@_) });
2535                                 if ($ok) {
2536                                         print STDERR "r$min .. r$ok OK\n";
2537                                         last;
2538                                 }
2539                         }
2540                 }
2541                 $SVN::Error::handler = $err_handler;
2542
2543                 my %exists = map { $_->{path} => $_ } @$gsv;
2544                 foreach my $r (sort {$a <=> $b} keys %revs) {
2545                         my ($paths, $logged) = @{$revs{$r}};
2546
2547                         foreach my $gs ($self->match_globs(\%exists, $paths,
2548                                                            $globs, $r)) {
2549                                 if ($gs->rev_db_max >= $r) {
2550                                         next;
2551                                 }
2552                                 next unless $gs->match_paths($paths, $r);
2553                                 $gs->{logged_rev_props} = $logged;
2554                                 my $log_entry = $gs->do_fetch($paths, $r);
2555                                 if ($log_entry) {
2556                                         $gs->do_git_commit($log_entry);
2557                                 }
2558                         }
2559                         foreach my $g (@$globs) {
2560                                 my $f = "$ENV{GIT_DIR}/svn/." .
2561                                         $self->uuid . ".$g->{t}";
2562                                 open my $fh, '>', "$f.tmp" or
2563                                       die "Can't open $f.tmp for writing: $!";
2564                                 print $fh "$r\n" or
2565                                       die "Couldn't write to $f: $!\n";
2566                                 close $fh or die "Error closing $f: $!\n";
2567                                 rename "$f.tmp", $f or
2568                                        die "Couldn't rename ",
2569                                            "$f.tmp => $f: $!\n";
2570                         }
2571                 }
2572                 # pre-fill the .rev_db since it'll eventually get filled in
2573                 # with '0' x40 if something new gets committed
2574                 foreach my $gs (@$gsv) {
2575                         next if defined $gs->rev_db_get($max);
2576                         $gs->rev_db_set($max, 0 x40);
2577                 }
2578                 last if $max >= $head;
2579                 $min = $max + 1;
2580                 $max += $inc;
2581                 $max = $head if ($max > $head);
2582         }
2583 }
2584
2585 sub match_globs {
2586         my ($self, $exists, $paths, $globs, $r) = @_;
2587         foreach my $g (@$globs) {
2588                 foreach (keys %$paths) {
2589                         next unless /$g->{path}->{regex}/;
2590                         my $p = $1;
2591                         my $pathname = $g->{path}->full_path($p);
2592                         next if $exists->{$pathname};
2593                         $exists->{$pathname} = Git::SVN->init(
2594                                               $self->{url}, $pathname, undef,
2595                                               $g->{ref}->full_path($p), 1);
2596                 }
2597                 my $c = '';
2598                 foreach (split m#/#, $g->{path}->{left}) {
2599                         $c .= "/$_";
2600                         next unless ($paths->{$c} &&
2601                                      ($paths->{$c}->{action} eq 'A'));
2602                         my @x = eval { $self->get_dir($g->{path}->{left}, $r) };
2603                         next unless scalar @x == 3;
2604                         my $dirents = $x[0];
2605                         foreach my $de (keys %$dirents) {
2606                                 next if $dirents->{$de}->kind !=
2607                                         $SVN::Node::dir;
2608                                 my $p = $g->{path}->full_path($de);
2609                                 next if $exists->{$p};
2610                                 next if (length $g->{path}->{right} &&
2611                                          ($self->check_path($p, $r) !=
2612                                           $SVN::Node::dir));
2613                                 $exists->{$p} = Git::SVN->init($self->{url},
2614                                                  $p, undef,
2615                                                  $g->{ref}->full_path($de), 1);
2616                         }
2617                 }
2618         }
2619         values %$exists;
2620 }
2621
2622 sub minimize_url {
2623         my ($self) = @_;
2624         return $self->{url} if ($self->{url} eq $self->{repos_root});
2625         my $url = $self->{repos_root};
2626         my @components = split(m!/!, $self->{svn_path});
2627         my $c = '';
2628         do {
2629                 $url .= "/$c" if length $c;
2630                 eval { (ref $self)->new($url)->get_latest_revnum };
2631         } while ($@ && ($c = shift @components));
2632         $url;
2633 }
2634
2635 sub can_do_switch {
2636         my $self = shift;
2637         unless (defined $can_do_switch) {
2638                 my $pool = SVN::Pool->new;
2639                 my $rep = eval {
2640                         $self->do_switch(1, '', 0, $self->{url},
2641                                          SVN::Delta::Editor->new, $pool);
2642                 };
2643                 if ($@) {
2644                         $can_do_switch = 0;
2645                 } else {
2646                         $rep->abort_report($pool);
2647                         $can_do_switch = 1;
2648                 }
2649                 $pool->clear;
2650         }
2651         $can_do_switch;
2652 }
2653
2654 sub skip_unknown_revs {
2655         my ($err) = @_;
2656         my $errno = $err->apr_err();
2657         # Maybe the branch we're tracking didn't
2658         # exist when the repo started, so it's
2659         # not an error if it doesn't, just continue
2660         #
2661         # Wonderfully consistent library, eh?
2662         # 160013 - svn:// and file://
2663         # 175002 - http(s)://
2664         # 175007 - http(s):// (this repo required authorization, too...)
2665         #   More codes may be discovered later...
2666         if ($errno == 175007 || $errno == 175002 || $errno == 160013) {
2667                 return;
2668         }
2669         die "Error from SVN, ($errno): ", $err->expanded_message,"\n";
2670 }
2671
2672 # svn_log_changed_path_t objects passed to get_log are likely to be
2673 # overwritten even if only the refs are copied to an external variable,
2674 # so we should dup the structures in their entirety.  Using an externally
2675 # passed pool (instead of our temporary and quickly cleared pool in
2676 # Git::SVN::Ra) does not help matters at all...
2677 sub dup_changed_paths {
2678         my ($paths) = @_;
2679         return undef unless $paths;
2680         my %ret;
2681         foreach my $p (keys %$paths) {
2682                 my $i = $paths->{$p};
2683                 my %s = map { $_ => $i->$_ }
2684                               qw/copyfrom_path copyfrom_rev action/;
2685                 $ret{$p} = \%s;
2686         }
2687         \%ret;
2688 }
2689
2690 package Git::SVN::Log;
2691 use strict;
2692 use warnings;
2693 use POSIX qw/strftime/;
2694 use vars qw/$TZ $limit $color $pager $non_recursive $verbose $oneline
2695             %rusers $show_commit $incremental/;
2696 my $l_fmt;
2697
2698 sub cmt_showable {
2699         my ($c) = @_;
2700         return 1 if defined $c->{r};
2701         if ($c->{l} && $c->{l}->[-1] eq "...\n" &&
2702                                 $c->{a_raw} =~ /\@([a-f\d\-]+)>$/) {
2703                 my @log = command(qw/cat-file commit/, $c->{c});
2704                 shift @log while ($log[0] ne "\n");
2705                 shift @log;
2706                 @{$c->{l}} = grep !/^git-svn-id: /, @log;
2707
2708                 (undef, $c->{r}, undef) = ::extract_metadata(
2709                                 (grep(/^git-svn-id: /, @log))[-1]);
2710         }
2711         return defined $c->{r};
2712 }
2713
2714 sub log_use_color {
2715         return 1 if $color;
2716         my ($dc, $dcvar);
2717         $dcvar = 'color.diff';
2718         $dc = `git-config --get $dcvar`;
2719         if ($dc eq '') {
2720                 # nothing at all; fallback to "diff.color"
2721                 $dcvar = 'diff.color';
2722                 $dc = `git-config --get $dcvar`;
2723         }
2724         chomp($dc);
2725         if ($dc eq 'auto') {
2726                 my $pc;
2727                 $pc = `git-config --get color.pager`;
2728                 if ($pc eq '') {
2729                         # does not have it -- fallback to pager.color
2730                         $pc = `git-config --bool --get pager.color`;
2731                 }
2732                 else {
2733                         $pc = `git-config --bool --get color.pager`;
2734                         if ($?) {
2735                                 $pc = 'false';
2736                         }
2737                 }
2738                 chomp($pc);
2739                 if (-t *STDOUT || (defined $pager && $pc eq 'true')) {
2740                         return ($ENV{TERM} && $ENV{TERM} ne 'dumb');
2741                 }
2742                 return 0;
2743         }
2744         return 0 if $dc eq 'never';
2745         return 1 if $dc eq 'always';
2746         chomp($dc = `git-config --bool --get $dcvar`);
2747         return ($dc eq 'true');
2748 }
2749
2750 sub git_svn_log_cmd {
2751         my ($r_min, $r_max) = @_;
2752         my $gs = Git::SVN->_new;
2753         my @cmd = (qw/log --abbrev-commit --pretty=raw --default/,
2754                    $gs->refname);
2755         push @cmd, '-r' unless $non_recursive;
2756         push @cmd, qw/--raw --name-status/ if $verbose;
2757         push @cmd, '--color' if log_use_color();
2758         return @cmd unless defined $r_max;
2759         if ($r_max == $r_min) {
2760                 push @cmd, '--max-count=1';
2761                 if (my $c = $gs->rev_db_get($r_max)) {
2762                         push @cmd, $c;
2763                 }
2764         } else {
2765                 my ($c_min, $c_max);
2766                 $c_max = $gs->rev_db_get($r_max);
2767                 $c_min = $gs->rev_db_get($r_min);
2768                 if (defined $c_min && defined $c_max) {
2769                         if ($r_max > $r_max) {
2770                                 push @cmd, "$c_min..$c_max";
2771                         } else {
2772                                 push @cmd, "$c_max..$c_min";
2773                         }
2774                 } elsif ($r_max > $r_min) {
2775                         push @cmd, $c_max;
2776                 } else {
2777                         push @cmd, $c_min;
2778                 }
2779         }
2780         return @cmd;
2781 }
2782
2783 # adapted from pager.c
2784 sub config_pager {
2785         $pager ||= $ENV{GIT_PAGER} || $ENV{PAGER};
2786         if (!defined $pager) {
2787                 $pager = 'less';
2788         } elsif (length $pager == 0 || $pager eq 'cat') {
2789                 $pager = undef;
2790         }
2791 }
2792
2793 sub run_pager {
2794         return unless -t *STDOUT;
2795         pipe my $rfd, my $wfd or return;
2796         defined(my $pid = fork) or ::fatal "Can't fork: $!\n";
2797         if (!$pid) {
2798                 open STDOUT, '>&', $wfd or
2799                                      ::fatal "Can't redirect to stdout: $!\n";
2800                 return;
2801         }
2802         open STDIN, '<&', $rfd or ::fatal "Can't redirect stdin: $!\n";
2803         $ENV{LESS} ||= 'FRSX';
2804         exec $pager or ::fatal "Can't run pager: $! ($pager)\n";
2805 }
2806
2807 sub tz_to_s_offset {
2808         my ($tz) = @_;
2809         $tz =~ s/(\d\d)$//;
2810         return ($1 * 60) + ($tz * 3600);
2811 }
2812
2813 sub get_author_info {
2814         my ($dest, $author, $t, $tz) = @_;
2815         $author =~ s/(?:^\s*|\s*$)//g;
2816         $dest->{a_raw} = $author;
2817         my $au;
2818         if ($::_authors) {
2819                 $au = $rusers{$author} || undef;
2820         }
2821         if (!$au) {
2822                 ($au) = ($author =~ /<([^>]+)\@[^>]+>$/);
2823         }
2824         $dest->{t} = $t;
2825         $dest->{tz} = $tz;
2826         $dest->{a} = $au;
2827         # Date::Parse isn't in the standard Perl distro :(
2828         if ($tz =~ s/^\+//) {
2829                 $t += tz_to_s_offset($tz);
2830         } elsif ($tz =~ s/^\-//) {
2831                 $t -= tz_to_s_offset($tz);
2832         }
2833         $dest->{t_utc} = $t;
2834 }
2835
2836 sub process_commit {
2837         my ($c, $r_min, $r_max, $defer) = @_;
2838         if (defined $r_min && defined $r_max) {
2839                 if ($r_min == $c->{r} && $r_min == $r_max) {
2840                         show_commit($c);
2841                         return 0;
2842                 }
2843                 return 1 if $r_min == $r_max;
2844                 if ($r_min < $r_max) {
2845                         # we need to reverse the print order
2846                         return 0 if (defined $limit && --$limit < 0);
2847                         push @$defer, $c;
2848                         return 1;
2849                 }
2850                 if ($r_min != $r_max) {
2851                         return 1 if ($r_min < $c->{r});
2852                         return 1 if ($r_max > $c->{r});
2853                 }
2854         }
2855         return 0 if (defined $limit && --$limit < 0);
2856         show_commit($c);
2857         return 1;
2858 }
2859
2860 sub show_commit {
2861         my $c = shift;
2862         if ($oneline) {
2863                 my $x = "\n";
2864                 if (my $l = $c->{l}) {
2865                         while ($l->[0] =~ /^\s*$/) { shift @$l }
2866                         $x = $l->[0];
2867                 }
2868                 $l_fmt ||= 'A' . length($c->{r});
2869                 print 'r',pack($l_fmt, $c->{r}),' | ';
2870                 print "$c->{c} | " if $show_commit;
2871                 print $x;
2872         } else {
2873                 show_commit_normal($c);
2874         }
2875 }
2876
2877 sub show_commit_changed_paths {
2878         my ($c) = @_;
2879         return unless $c->{changed};
2880         print "Changed paths:\n", @{$c->{changed}};
2881 }
2882
2883 sub show_commit_normal {
2884         my ($c) = @_;
2885         print '-' x72, "\nr$c->{r} | ";
2886         print "$c->{c} | " if $show_commit;
2887         print "$c->{a} | ", strftime("%Y-%m-%d %H:%M:%S %z (%a, %d %b %Y)",
2888                                  localtime($c->{t_utc})), ' | ';
2889         my $nr_line = 0;
2890
2891         if (my $l = $c->{l}) {
2892                 while ($l->[$#$l] eq "\n" && $#$l > 0
2893                                           && $l->[($#$l - 1)] eq "\n") {
2894                         pop @$l;
2895                 }
2896                 $nr_line = scalar @$l;
2897                 if (!$nr_line) {
2898                         print "1 line\n\n\n";
2899                 } else {
2900                         if ($nr_line == 1) {
2901                                 $nr_line = '1 line';
2902                         } else {
2903                                 $nr_line .= ' lines';
2904                         }
2905                         print $nr_line, "\n";
2906                         show_commit_changed_paths($c);
2907                         print "\n";
2908                         print $_ foreach @$l;
2909                 }
2910         } else {
2911                 print "1 line\n";
2912                 show_commit_changed_paths($c);
2913                 print "\n";
2914
2915         }
2916         foreach my $x (qw/raw diff/) {
2917                 if ($c->{$x}) {
2918                         print "\n";
2919                         print $_ foreach @{$c->{$x}}
2920                 }
2921         }
2922 }
2923
2924 sub cmd_show_log {
2925         my (@args) = @_;
2926         my ($r_min, $r_max);
2927         my $r_last = -1; # prevent dupes
2928         if (defined $TZ) {
2929                 $ENV{TZ} = $TZ;
2930         } else {
2931                 delete $ENV{TZ};
2932         }
2933         if (defined $::_revision) {
2934                 if ($::_revision =~ /^(\d+):(\d+)$/) {
2935                         ($r_min, $r_max) = ($1, $2);
2936                 } elsif ($::_revision =~ /^\d+$/) {
2937                         $r_min = $r_max = $::_revision;
2938                 } else {
2939                         ::fatal "-r$::_revision is not supported, use ",
2940                                 "standard \'git log\' arguments instead\n";
2941                 }
2942         }
2943
2944         config_pager();
2945         @args = (git_svn_log_cmd($r_min, $r_max), @args);
2946         my $log = command_output_pipe(@args);
2947         run_pager();
2948         my (@k, $c, $d);
2949         my $esc_color = qr/(?:\033\[(?:(?:\d+;)*\d*)?m)*/;
2950         while (<$log>) {
2951                 if (/^${esc_color}commit ($::sha1_short)/o) {
2952                         my $cmt = $1;
2953                         if ($c && cmt_showable($c) && $c->{r} != $r_last) {
2954                                 $r_last = $c->{r};
2955                                 process_commit($c, $r_min, $r_max, \@k) or
2956                                                                 goto out;
2957                         }
2958                         $d = undef;
2959                         $c = { c => $cmt };
2960                 } elsif (/^${esc_color}author (.+) (\d+) ([\-\+]?\d+)$/o) {
2961                         get_author_info($c, $1, $2, $3);
2962                 } elsif (/^${esc_color}(?:tree|parent|committer) /o) {
2963                         # ignore
2964                 } elsif (/^${esc_color}:\d{6} \d{6} $::sha1_short/o) {
2965                         push @{$c->{raw}}, $_;
2966                 } elsif (/^${esc_color}[ACRMDT]\t/) {
2967                         # we could add $SVN->{svn_path} here, but that requires
2968                         # remote access at the moment (repo_path_split)...
2969                         s#^(${esc_color})([ACRMDT])\t#$1   $2 #o;
2970                         push @{$c->{changed}}, $_;
2971                 } elsif (/^${esc_color}diff /o) {
2972                         $d = 1;
2973                         push @{$c->{diff}}, $_;
2974                 } elsif ($d) {
2975                         push @{$c->{diff}}, $_;
2976                 } elsif (/^${esc_color}    (git-svn-id:.+)$/o) {
2977                         ($c->{url}, $c->{r}, undef) = ::extract_metadata($1);
2978                 } elsif (s/^${esc_color}    //o) {
2979                         push @{$c->{l}}, $_;
2980                 }
2981         }
2982         if ($c && defined $c->{r} && $c->{r} != $r_last) {
2983                 $r_last = $c->{r};
2984                 process_commit($c, $r_min, $r_max, \@k);
2985         }
2986         if (@k) {
2987                 my $swap = $r_max;
2988                 $r_max = $r_min;
2989                 $r_min = $swap;
2990                 process_commit($_, $r_min, $r_max) foreach reverse @k;
2991         }
2992 out:
2993         close $log;
2994         print '-' x72,"\n" unless $incremental || $oneline;
2995 }
2996
2997 package Git::SVN::Migration;
2998 # these version numbers do NOT correspond to actual version numbers
2999 # of git nor git-svn.  They are just relative.
3000 #
3001 # v0 layout: .git/$id/info/url, refs/heads/$id-HEAD
3002 #
3003 # v1 layout: .git/$id/info/url, refs/remotes/$id
3004 #
3005 # v2 layout: .git/svn/$id/info/url, refs/remotes/$id
3006 #
3007 # v3 layout: .git/svn/$id, refs/remotes/$id
3008 #            - info/url may remain for backwards compatibility
3009 #            - this is what we migrate up to this layout automatically,
3010 #            - this will be used by git svn init on single branches
3011 #
3012 # v4 layout: .git/svn/$repo_id/$id, refs/remotes/$repo_id/$id
3013 #            - this is only created for newly multi-init-ed
3014 #              repositories.  Similar in spirit to the
3015 #              --use-separate-remotes option in git-clone (now default)
3016 #            - we do not automatically migrate to this (following
3017 #              the example set by core git)
3018 use strict;
3019 use warnings;
3020 use Carp qw/croak/;
3021 use File::Path qw/mkpath/;
3022 use File::Basename qw/dirname basename/;
3023 use vars qw/$_minimize/;
3024
3025 sub migrate_from_v0 {
3026         my $git_dir = $ENV{GIT_DIR};
3027         return undef unless -d $git_dir;
3028         my ($fh, $ctx) = command_output_pipe(qw/rev-parse --symbolic --all/);
3029         my $migrated = 0;
3030         while (<$fh>) {
3031                 chomp;
3032                 my ($id, $orig_ref) = ($_, $_);
3033                 next unless $id =~ s#^refs/heads/(.+)-HEAD$#$1#;
3034                 next unless -f "$git_dir/$id/info/url";
3035                 my $new_ref = "refs/remotes/$id";
3036                 if (::verify_ref("$new_ref^0")) {
3037                         print STDERR "W: $orig_ref is probably an old ",
3038                                      "branch used by an ancient version of ",
3039                                      "git-svn.\n",
3040                                      "However, $new_ref also exists.\n",
3041                                      "We will not be able ",
3042                                      "to use this branch until this ",
3043                                      "ambiguity is resolved.\n";
3044                         next;
3045                 }
3046                 print STDERR "Migrating from v0 layout...\n" if !$migrated;
3047                 print STDERR "Renaming ref: $orig_ref => $new_ref\n";
3048                 command_noisy('update-ref', $new_ref, $orig_ref);
3049                 command_noisy('update-ref', '-d', $orig_ref, $orig_ref);
3050                 $migrated++;
3051         }
3052         command_close_pipe($fh, $ctx);
3053         print STDERR "Done migrating from v0 layout...\n" if $migrated;
3054         $migrated;
3055 }
3056
3057 sub migrate_from_v1 {
3058         my $git_dir = $ENV{GIT_DIR};
3059         my $migrated = 0;
3060         return $migrated unless -d $git_dir;
3061         my $svn_dir = "$git_dir/svn";
3062
3063         # just in case somebody used 'svn' as their $id at some point...
3064         return $migrated if -d $svn_dir && ! -f "$svn_dir/info/url";
3065
3066         print STDERR "Migrating from a git-svn v1 layout...\n";
3067         mkpath([$svn_dir]);
3068         print STDERR "Data from a previous version of git-svn exists, but\n\t",
3069                      "$svn_dir\n\t(required for this version ",
3070                      "($::VERSION) of git-svn) does not. exist\n";
3071         my ($fh, $ctx) = command_output_pipe(qw/rev-parse --symbolic --all/);
3072         while (<$fh>) {
3073                 my $x = $_;
3074                 next unless $x =~ s#^refs/remotes/##;
3075                 chomp $x;
3076                 next unless -f "$git_dir/$x/info/url";
3077                 my $u = eval { ::file_to_s("$git_dir/$x/info/url") };
3078                 next unless $u;
3079                 my $dn = dirname("$git_dir/svn/$x");
3080                 mkpath([$dn]) unless -d $dn;
3081                 if ($x eq 'svn') { # they used 'svn' as GIT_SVN_ID:
3082                         mkpath(["$git_dir/svn/svn"]);
3083                         print STDERR " - $git_dir/$x/info => ",
3084                                         "$git_dir/svn/$x/info\n";
3085                         rename "$git_dir/$x/info", "$git_dir/svn/$x/info" or
3086                                croak "$!: $x";
3087                         # don't worry too much about these, they probably
3088                         # don't exist with repos this old (save for index,
3089                         # and we can easily regenerate that)
3090                         foreach my $f (qw/unhandled.log index .rev_db/) {
3091                                 rename "$git_dir/$x/$f", "$git_dir/svn/$x/$f";
3092                         }
3093                 } else {
3094                         print STDERR " - $git_dir/$x => $git_dir/svn/$x\n";
3095                         rename "$git_dir/$x", "$git_dir/svn/$x" or
3096                                croak "$!: $x";
3097                 }
3098                 $migrated++;
3099         }
3100         command_close_pipe($fh, $ctx);
3101         print STDERR "Done migrating from a git-svn v1 layout\n";
3102         $migrated;
3103 }
3104
3105 sub read_old_urls {
3106         my ($l_map, $pfx, $path) = @_;
3107         my @dir;
3108         foreach (<$path/*>) {
3109                 if (-r "$_/info/url") {
3110                         $pfx .= '/' if $pfx && $pfx !~ m!/$!;
3111                         my $ref_id = $pfx . basename $_;
3112                         my $url = ::file_to_s("$_/info/url");
3113                         $l_map->{$ref_id} = $url;
3114                 } elsif (-d $_) {
3115                         push @dir, $_;
3116                 }
3117         }
3118         foreach (@dir) {
3119                 my $x = $_;
3120                 $x =~ s!^\Q$ENV{GIT_DIR}\E/svn/!!o;
3121                 read_old_urls($l_map, $x, $_);
3122         }
3123 }
3124
3125 sub migrate_from_v2 {
3126         my @cfg = command(qw/config -l/);
3127         return if grep /^svn-remote\..+\.url=/, @cfg;
3128         my %l_map;
3129         read_old_urls(\%l_map, '', "$ENV{GIT_DIR}/svn");
3130         my $migrated = 0;
3131
3132         foreach my $ref_id (sort keys %l_map) {
3133                 eval { Git::SVN->init($l_map{$ref_id}, '', undef, $ref_id) };
3134                 if ($@) {
3135                         Git::SVN->init($l_map{$ref_id}, '', $ref_id, $ref_id);
3136                 }
3137                 $migrated++;
3138         }
3139         $migrated;
3140 }
3141
3142 sub minimize_connections {
3143         my $r = Git::SVN::read_all_remotes();
3144         my $new_urls = {};
3145         my $root_repos = {};
3146         foreach my $repo_id (keys %$r) {
3147                 my $url = $r->{$repo_id}->{url} or next;
3148                 my $fetch = $r->{$repo_id}->{fetch} or next;
3149                 my $ra = Git::SVN::Ra->new($url);
3150
3151                 # skip existing cases where we already connect to the root
3152                 if (($ra->{url} eq $ra->{repos_root}) ||
3153                     (Git::SVN::sanitize_remote_name($ra->{repos_root}) eq
3154                      $repo_id)) {
3155                         $root_repos->{$ra->{url}} = $repo_id;
3156                         next;
3157                 }
3158
3159                 my $root_ra = Git::SVN::Ra->new($ra->{repos_root});
3160                 my $root_path = $ra->{url};
3161                 $root_path =~ s#^\Q$ra->{repos_root}\E/*##;
3162                 foreach my $path (keys %$fetch) {
3163                         my $ref_id = $fetch->{$path};
3164                         my $gs = Git::SVN->new($ref_id, $repo_id, $path);
3165
3166                         # make sure we can read when connecting to
3167                         # a higher level of a repository
3168                         my ($last_rev, undef) = $gs->last_rev_commit;
3169                         if (!defined $last_rev) {
3170                                 $last_rev = eval {
3171                                         $root_ra->get_latest_revnum;
3172                                 };
3173                                 next if $@;
3174                         }
3175                         my $new = $root_path;
3176                         $new .= length $path ? "/$path" : '';
3177                         eval {
3178                                 $root_ra->get_log([$new], $last_rev, $last_rev,
3179                                                   0, 0, 1, sub { });
3180                         };
3181                         next if $@;
3182                         $new_urls->{$ra->{repos_root}}->{$new} =
3183                                 { ref_id => $ref_id,
3184                                   old_repo_id => $repo_id,
3185                                   old_path => $path };
3186                 }
3187         }
3188
3189         my @emptied;
3190         foreach my $url (keys %$new_urls) {
3191                 # see if we can re-use an existing [svn-remote "repo_id"]
3192                 # instead of creating a(n ugly) new section:
3193                 my $repo_id = $root_repos->{$url} ||
3194                               Git::SVN::sanitize_remote_name($url);
3195
3196                 my $fetch = $new_urls->{$url};
3197                 foreach my $path (keys %$fetch) {
3198                         my $x = $fetch->{$path};
3199                         Git::SVN->init($url, $path, $repo_id, $x->{ref_id});
3200                         my $pfx = "svn-remote.$x->{old_repo_id}";
3201
3202                         my $old_fetch = quotemeta("$x->{old_path}:".
3203                                                   "refs/remotes/$x->{ref_id}");
3204                         command_noisy(qw/config --unset/,
3205                                       "$pfx.fetch", '^'. $old_fetch . '$');
3206                         delete $r->{$x->{old_repo_id}}->
3207                                {fetch}->{$x->{old_path}};
3208                         if (!keys %{$r->{$x->{old_repo_id}}->{fetch}}) {
3209                                 command_noisy(qw/config --unset/,
3210                                               "$pfx.url");
3211                                 push @emptied, $x->{old_repo_id}
3212                         }
3213                 }
3214         }
3215         if (@emptied) {
3216                 my $file = $ENV{GIT_CONFIG} || $ENV{GIT_CONFIG_LOCAL} ||
3217                            "$ENV{GIT_DIR}/config";
3218                 print STDERR <<EOF;
3219 The following [svn-remote] sections in your config file ($file) are empty
3220 and can be safely removed:
3221 EOF
3222                 print STDERR "[svn-remote \"$_\"]\n" foreach @emptied;
3223         }
3224 }
3225
3226 sub migration_check {
3227         migrate_from_v0();
3228         migrate_from_v1();
3229         migrate_from_v2();
3230         minimize_connections() if $_minimize;
3231 }
3232
3233 package Git::IndexInfo;
3234 use strict;
3235 use warnings;
3236 use Git qw/command_input_pipe command_close_pipe/;
3237
3238 sub new {
3239         my ($class) = @_;
3240         my ($gui, $ctx) = command_input_pipe(qw/update-index -z --index-info/);
3241         bless { gui => $gui, ctx => $ctx, nr => 0}, $class;
3242 }
3243
3244 sub remove {
3245         my ($self, $path) = @_;
3246         if (print { $self->{gui} } '0 ', 0 x 40, "\t", $path, "\0") {
3247                 return ++$self->{nr};
3248         }
3249         undef;
3250 }
3251
3252 sub update {
3253         my ($self, $mode, $hash, $path) = @_;
3254         if (print { $self->{gui} } $mode, ' ', $hash, "\t", $path, "\0") {
3255                 return ++$self->{nr};
3256         }
3257         undef;
3258 }
3259
3260 sub DESTROY {
3261         my ($self) = @_;
3262         command_close_pipe($self->{gui}, $self->{ctx});
3263 }
3264
3265 package Git::SVN::GlobSpec;
3266 use strict;
3267 use warnings;
3268
3269 sub new {
3270         my ($class, $glob) = @_;
3271         my $re = $glob;
3272         $re =~ s!/+$!!g; # no need for trailing slashes
3273         my $nr = ($re =~ s!^(.*/?)\*(/?.*)$!\(\[^/\]+\)!g);
3274         my ($left, $right) = ($1, $2);
3275         if ($nr > 1) {
3276                 die "Only one '*' wildcard expansion ",
3277                     "is supported (got $nr): '$glob'\n";
3278         } elsif ($nr == 0) {
3279                 die "One '*' is needed for glob: '$glob'\n";
3280         }
3281         $re = quotemeta($left) . $re . quotemeta($right);
3282         $left =~ s!/+$!!g;
3283         $right =~ s!^/+!!g;
3284         bless { left => $left, right => $right,
3285                 regex => qr/$re/, glob => $glob }, $class;
3286 }
3287
3288 sub full_path {
3289         my ($self, $path) = @_;
3290         return (length $self->{left} ? "$self->{left}/" : '') .
3291                $path . (length $self->{right} ? "/$self->{right}" : '');
3292 }
3293
3294 __END__
3295
3296 Data structures:
3297
3298
3299 $remotes = { # returned by read_all_remotes()
3300         'svn' => {
3301                 # svn-remote.svn.url=https://svn.musicpd.org
3302                 url => 'https://svn.musicpd.org',
3303                 # svn-remote.svn.fetch=mpd/trunk:trunk
3304                 fetch => {
3305                         'mpd/trunk' => 'trunk',
3306                 },
3307                 # svn-remote.svn.tags=mpd/tags/*:tags/*
3308                 tags => {
3309                         path => {
3310                                 left => 'mpd/tags',
3311                                 right => '',
3312                                 regex => qr!mpd/tags/([^/]+)$!,
3313                                 glob => 'tags/*',
3314                         },
3315                         ref => {
3316                                 left => 'tags',
3317                                 right => '',
3318                                 regex => qr!tags/([^/]+)$!,
3319                                 glob => 'tags/*',
3320                         },
3321                 }
3322         }
3323 };
3324
3325 $log_entry hashref as returned by libsvn_log_entry()
3326 {
3327         log => 'whitespace-formatted log entry
3328 ',                                              # trailing newline is preserved
3329         revision => '8',                        # integer
3330         date => '2004-02-24T17:01:44.108345Z',  # commit date
3331         author => 'committer name'
3332 };
3333
3334
3335 # this is generated by generate_diff();
3336 @mods = array of diff-index line hashes, each element represents one line
3337         of diff-index output
3338
3339 diff-index line ($m hash)
3340 {
3341         mode_a => first column of diff-index output, no leading ':',
3342         mode_b => second column of diff-index output,
3343         sha1_b => sha1sum of the final blob,
3344         chg => change type [MCRADT],
3345         file_a => original file name of a file (iff chg is 'C' or 'R')
3346         file_b => new/current file name of a file (any chg)
3347 }
3348 ;
3349
3350 # retval of read_url_paths{,_all}();
3351 $l_map = {
3352         # repository root url
3353         'https://svn.musicpd.org' => {
3354                 # repository path               # GIT_SVN_ID
3355                 'mpd/trunk'             =>      'trunk',
3356                 'mpd/tags/0.11.5'       =>      'tags/0.11.5',
3357         },
3358 }
3359
3360 Notes:
3361         I don't trust the each() function on unless I created %hash myself
3362         because the internal iterator may not have started at base.