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