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