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