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