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