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