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