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