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