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