git svn info: make info relative to the current directory
[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 $_repository
8                 $_q $_authors %users/;
9 $AUTHOR = 'Eric Wong <normalperson@yhbt.net>';
10 $VERSION = '@@GIT_VERSION@@';
11
12 # From which subdir have we been invoked?
13 my $cmd_dir_prefix = eval {
14         command_oneline([qw/rev-parse --show-prefix/], STDERR => 0)
15 } || '';
16
17 my $git_dir_user_set = 1 if defined $ENV{GIT_DIR};
18 $ENV{GIT_DIR} ||= '.git';
19 $Git::SVN::default_repo_id = 'svn';
20 $Git::SVN::default_ref_id = $ENV{GIT_SVN_ID} || 'git-svn';
21 $Git::SVN::Ra::_log_window_size = 100;
22
23 $Git::SVN::Log::TZ = $ENV{TZ};
24 $ENV{TZ} = 'UTC';
25 $| = 1; # unbuffer STDOUT
26
27 sub fatal (@) { print STDERR "@_\n"; exit 1 }
28 require SVN::Core; # use()-ing this causes segfaults for me... *shrug*
29 require SVN::Ra;
30 require SVN::Delta;
31 if ($SVN::Core::VERSION lt '1.1.0') {
32         fatal "Need SVN::Core 1.1.0 or better (got $SVN::Core::VERSION)";
33 }
34 push @Git::SVN::Ra::ISA, 'SVN::Ra';
35 push @SVN::Git::Editor::ISA, 'SVN::Delta::Editor';
36 push @SVN::Git::Fetcher::ISA, 'SVN::Delta::Editor';
37 use Carp qw/croak/;
38 use Digest::MD5;
39 use IO::File qw//;
40 use File::Basename qw/dirname basename/;
41 use File::Path qw/mkpath/;
42 use Getopt::Long qw/:config gnu_getopt no_ignore_case auto_abbrev/;
43 use IPC::Open3;
44 use Git;
45
46 BEGIN {
47         # import functions from Git into our packages, en masse
48         no strict 'refs';
49         foreach (qw/command command_oneline command_noisy command_output_pipe
50                     command_input_pipe command_close_pipe/) {
51                 for my $package ( qw(SVN::Git::Editor SVN::Git::Fetcher
52                         Git::SVN::Migration Git::SVN::Log Git::SVN),
53                         __PACKAGE__) {
54                         *{"${package}::$_"} = \&{"Git::$_"};
55                 }
56         }
57 }
58
59 my ($SVN);
60
61 $sha1 = qr/[a-f\d]{40}/;
62 $sha1_short = qr/[a-f\d]{4,40}/;
63 my ($_stdin, $_help, $_edit,
64         $_message, $_file,
65         $_template, $_shared,
66         $_version, $_fetch_all, $_no_rebase,
67         $_merge, $_strategy, $_dry_run, $_local,
68         $_prefix, $_no_checkout, $_url, $_verbose,
69         $_git_format, $_commit_url);
70 $Git::SVN::_follow_parent = 1;
71 my %remote_opts = ( 'username=s' => \$Git::SVN::Prompt::_username,
72                     'config-dir=s' => \$Git::SVN::Ra::config_dir,
73                     'no-auth-cache' => \$Git::SVN::Prompt::_no_auth_cache );
74 my %fc_opts = ( 'follow-parent|follow!' => \$Git::SVN::_follow_parent,
75                 'authors-file|A=s' => \$_authors,
76                 'repack:i' => \$Git::SVN::_repack,
77                 'noMetadata' => \$Git::SVN::_no_metadata,
78                 'useSvmProps' => \$Git::SVN::_use_svm_props,
79                 'useSvnsyncProps' => \$Git::SVN::_use_svnsync_props,
80                 'log-window-size=i' => \$Git::SVN::Ra::_log_window_size,
81                 'no-checkout' => \$_no_checkout,
82                 'quiet|q' => \$_q,
83                 'repack-flags|repack-args|repack-opts=s' =>
84                    \$Git::SVN::_repack_flags,
85                 'use-log-author' => \$Git::SVN::_use_log_author,
86                 'add-author-from' => \$Git::SVN::_add_author_from,
87                 %remote_opts );
88
89 my ($_trunk, $_tags, $_branches, $_stdlayout);
90 my %icv;
91 my %init_opts = ( 'template=s' => \$_template, 'shared:s' => \$_shared,
92                   'trunk|T=s' => \$_trunk, 'tags|t=s' => \$_tags,
93                   'branches|b=s' => \$_branches, 'prefix=s' => \$_prefix,
94                   'stdlayout|s' => \$_stdlayout,
95                   'minimize-url|m' => \$Git::SVN::_minimize_url,
96                   'no-metadata' => sub { $icv{noMetadata} = 1 },
97                   'use-svm-props' => sub { $icv{useSvmProps} = 1 },
98                   'use-svnsync-props' => sub { $icv{useSvnsyncProps} = 1 },
99                   'rewrite-root=s' => sub { $icv{rewriteRoot} = $_[1] },
100                   %remote_opts );
101 my %cmt_opts = ( 'edit|e' => \$_edit,
102                 'rmdir' => \$SVN::Git::Editor::_rmdir,
103                 'find-copies-harder' => \$SVN::Git::Editor::_find_copies_harder,
104                 'l=i' => \$SVN::Git::Editor::_rename_limit,
105                 'copy-similarity|C=i'=> \$SVN::Git::Editor::_cp_similarity
106 );
107
108 my %cmd = (
109         fetch => [ \&cmd_fetch, "Download new revisions from SVN",
110                         { 'revision|r=s' => \$_revision,
111                           'fetch-all|all' => \$_fetch_all,
112                            %fc_opts } ],
113         clone => [ \&cmd_clone, "Initialize and fetch revisions",
114                         { 'revision|r=s' => \$_revision,
115                            %fc_opts, %init_opts } ],
116         init => [ \&cmd_init, "Initialize a repo for tracking" .
117                           " (requires URL argument)",
118                           \%init_opts ],
119         'multi-init' => [ \&cmd_multi_init,
120                           "Deprecated alias for ".
121                           "'$0 init -T<trunk> -b<branches> -t<tags>'",
122                           \%init_opts ],
123         dcommit => [ \&cmd_dcommit,
124                      'Commit several diffs to merge with upstream',
125                         { 'merge|m|M' => \$_merge,
126                           'strategy|s=s' => \$_strategy,
127                           'verbose|v' => \$_verbose,
128                           'dry-run|n' => \$_dry_run,
129                           'fetch-all|all' => \$_fetch_all,
130                           'commit-url=s' => \$_commit_url,
131                           'revision|r=i' => \$_revision,
132                           'no-rebase' => \$_no_rebase,
133                         %cmt_opts, %fc_opts } ],
134         'set-tree' => [ \&cmd_set_tree,
135                         "Set an SVN repository to a git tree-ish",
136                         { 'stdin|' => \$_stdin, %cmt_opts, %fc_opts, } ],
137         'create-ignore' => [ \&cmd_create_ignore,
138                              'Create a .gitignore per svn:ignore',
139                              { 'revision|r=i' => \$_revision
140                              } ],
141         'propget' => [ \&cmd_propget,
142                        'Print the value of a property on a file or directory',
143                        { 'revision|r=i' => \$_revision } ],
144         'proplist' => [ \&cmd_proplist,
145                        'List all properties of a file or directory',
146                        { 'revision|r=i' => \$_revision } ],
147         'show-ignore' => [ \&cmd_show_ignore, "Show svn:ignore listings",
148                         { 'revision|r=i' => \$_revision
149                         } ],
150         'show-externals' => [ \&cmd_show_externals, "Show svn:externals listings",
151                         { 'revision|r=i' => \$_revision
152                         } ],
153         'multi-fetch' => [ \&cmd_multi_fetch,
154                            "Deprecated alias for $0 fetch --all",
155                            { 'revision|r=s' => \$_revision, %fc_opts } ],
156         'migrate' => [ sub { },
157                        # no-op, we automatically run this anyways,
158                        'Migrate configuration/metadata/layout from
159                         previous versions of git-svn',
160                        { 'minimize' => \$Git::SVN::Migration::_minimize,
161                          %remote_opts } ],
162         'log' => [ \&Git::SVN::Log::cmd_show_log, 'Show commit logs',
163                         { 'limit=i' => \$Git::SVN::Log::limit,
164                           'revision|r=s' => \$_revision,
165                           'verbose|v' => \$Git::SVN::Log::verbose,
166                           'incremental' => \$Git::SVN::Log::incremental,
167                           'oneline' => \$Git::SVN::Log::oneline,
168                           'show-commit' => \$Git::SVN::Log::show_commit,
169                           'non-recursive' => \$Git::SVN::Log::non_recursive,
170                           'authors-file|A=s' => \$_authors,
171                           'color' => \$Git::SVN::Log::color,
172                           'pager=s' => \$Git::SVN::Log::pager
173                         } ],
174         'find-rev' => [ \&cmd_find_rev,
175                         "Translate between SVN revision numbers and tree-ish",
176                         {} ],
177         'rebase' => [ \&cmd_rebase, "Fetch and rebase your working directory",
178                         { 'merge|m|M' => \$_merge,
179                           'verbose|v' => \$_verbose,
180                           'strategy|s=s' => \$_strategy,
181                           'local|l' => \$_local,
182                           'fetch-all|all' => \$_fetch_all,
183                           'dry-run|n' => \$_dry_run,
184                           %fc_opts } ],
185         'commit-diff' => [ \&cmd_commit_diff,
186                            'Commit a diff between two trees',
187                         { 'message|m=s' => \$_message,
188                           'file|F=s' => \$_file,
189                           'revision|r=s' => \$_revision,
190                         %cmt_opts } ],
191         'info' => [ \&cmd_info,
192                     "Show info about the latest SVN revision
193                      on the current branch",
194                     { 'url' => \$_url, } ],
195         'blame' => [ \&Git::SVN::Log::cmd_blame,
196                     "Show what revision and author last modified each line of a file",
197                     { 'git-format' => \$_git_format } ],
198 );
199
200 my $cmd;
201 for (my $i = 0; $i < @ARGV; $i++) {
202         if (defined $cmd{$ARGV[$i]}) {
203                 $cmd = $ARGV[$i];
204                 splice @ARGV, $i, 1;
205                 last;
206         }
207 };
208
209 # make sure we're always running at the top-level working directory
210 unless ($cmd && $cmd =~ /(?:clone|init|multi-init)$/) {
211         unless (-d $ENV{GIT_DIR}) {
212                 if ($git_dir_user_set) {
213                         die "GIT_DIR=$ENV{GIT_DIR} explicitly set, ",
214                             "but it is not a directory\n";
215                 }
216                 my $git_dir = delete $ENV{GIT_DIR};
217                 chomp(my $cdup = command_oneline(qw/rev-parse --show-cdup/));
218                 unless (length $cdup) {
219                         die "Already at toplevel, but $git_dir ",
220                             "not found '$cdup'\n";
221                 }
222                 chdir $cdup or die "Unable to chdir up to '$cdup'\n";
223                 unless (-d $git_dir) {
224                         die "$git_dir still not found after going to ",
225                             "'$cdup'\n";
226                 }
227                 $ENV{GIT_DIR} = $git_dir;
228         }
229         $_repository = Git->repository(Repository => $ENV{GIT_DIR});
230 }
231
232 my %opts = %{$cmd{$cmd}->[2]} if (defined $cmd);
233
234 read_repo_config(\%opts);
235 if ($cmd && ($cmd eq 'log' || $cmd eq 'blame')) {
236         Getopt::Long::Configure('pass_through');
237 }
238 my $rv = GetOptions(%opts, 'help|H|h' => \$_help, 'version|V' => \$_version,
239                     'minimize-connections' => \$Git::SVN::Migration::_minimize,
240                     'id|i=s' => \$Git::SVN::default_ref_id,
241                     'svn-remote|remote|R=s' => sub {
242                        $Git::SVN::no_reuse_existing = 1;
243                        $Git::SVN::default_repo_id = $_[1] });
244 exit 1 if (!$rv && $cmd && $cmd ne 'log');
245
246 usage(0) if $_help;
247 version() if $_version;
248 usage(1) unless defined $cmd;
249 load_authors() if $_authors;
250
251 unless ($cmd =~ /^(?:clone|init|multi-init|commit-diff)$/) {
252         Git::SVN::Migration::migration_check();
253 }
254 Git::SVN::init_vars();
255 eval {
256         Git::SVN::verify_remotes_sanity();
257         $cmd{$cmd}->[0]->(@ARGV);
258 };
259 fatal $@ if $@;
260 post_fetch_checkout();
261 exit 0;
262
263 ####################### primary functions ######################
264 sub usage {
265         my $exit = shift || 0;
266         my $fd = $exit ? \*STDERR : \*STDOUT;
267         print $fd <<"";
268 git-svn - bidirectional operations between a single Subversion tree and git
269 Usage: git svn <command> [options] [arguments]\n
270
271         print $fd "Available commands:\n" unless $cmd;
272
273         foreach (sort keys %cmd) {
274                 next if $cmd && $cmd ne $_;
275                 next if /^multi-/; # don't show deprecated commands
276                 print $fd '  ',pack('A17',$_),$cmd{$_}->[1],"\n";
277                 foreach (sort keys %{$cmd{$_}->[2]}) {
278                         # mixed-case options are for .git/config only
279                         next if /[A-Z]/ && /^[a-z]+$/i;
280                         # prints out arguments as they should be passed:
281                         my $x = s#[:=]s$## ? '<arg>' : s#[:=]i$## ? '<num>' : '';
282                         print $fd ' ' x 21, join(', ', map { length $_ > 1 ?
283                                                         "--$_" : "-$_" }
284                                                 split /\|/,$_)," $x\n";
285                 }
286         }
287         print $fd <<"";
288 \nGIT_SVN_ID may be set in the environment or via the --id/-i switch to an
289 arbitrary identifier if you're tracking multiple SVN branches/repositories in
290 one git repository and want to keep them separate.  See git-svn(1) for more
291 information.
292
293         exit $exit;
294 }
295
296 sub version {
297         print "git-svn version $VERSION (svn $SVN::Core::VERSION)\n";
298         exit 0;
299 }
300
301 sub do_git_init_db {
302         unless (-d $ENV{GIT_DIR}) {
303                 my @init_db = ('init');
304                 push @init_db, "--template=$_template" if defined $_template;
305                 if (defined $_shared) {
306                         if ($_shared =~ /[a-z]/) {
307                                 push @init_db, "--shared=$_shared";
308                         } else {
309                                 push @init_db, "--shared";
310                         }
311                 }
312                 command_noisy(@init_db);
313                 $_repository = Git->repository(Repository => ".git");
314         }
315         my $set;
316         my $pfx = "svn-remote.$Git::SVN::default_repo_id";
317         foreach my $i (keys %icv) {
318                 die "'$set' and '$i' cannot both be set\n" if $set;
319                 next unless defined $icv{$i};
320                 command_noisy('config', "$pfx.$i", $icv{$i});
321                 $set = $i;
322         }
323 }
324
325 sub init_subdir {
326         my $repo_path = shift or return;
327         mkpath([$repo_path]) unless -d $repo_path;
328         chdir $repo_path or die "Couldn't chdir to $repo_path: $!\n";
329         $ENV{GIT_DIR} = '.git';
330         $_repository = Git->repository(Repository => $ENV{GIT_DIR});
331 }
332
333 sub cmd_clone {
334         my ($url, $path) = @_;
335         if (!defined $path &&
336             (defined $_trunk || defined $_branches || defined $_tags ||
337              defined $_stdlayout) &&
338             $url !~ m#^[a-z\+]+://#) {
339                 $path = $url;
340         }
341         $path = basename($url) if !defined $path || !length $path;
342         cmd_init($url, $path);
343         Git::SVN::fetch_all($Git::SVN::default_repo_id);
344 }
345
346 sub cmd_init {
347         if (defined $_stdlayout) {
348                 $_trunk = 'trunk' if (!defined $_trunk);
349                 $_tags = 'tags' if (!defined $_tags);
350                 $_branches = 'branches' if (!defined $_branches);
351         }
352         if (defined $_trunk || defined $_branches || defined $_tags) {
353                 return cmd_multi_init(@_);
354         }
355         my $url = shift or die "SVN repository location required ",
356                                "as a command-line argument\n";
357         init_subdir(@_);
358         do_git_init_db();
359
360         Git::SVN->init($url);
361 }
362
363 sub cmd_fetch {
364         if (grep /^\d+=./, @_) {
365                 die "'<rev>=<commit>' fetch arguments are ",
366                     "no longer supported.\n";
367         }
368         my ($remote) = @_;
369         if (@_ > 1) {
370                 die "Usage: $0 fetch [--all] [svn-remote]\n";
371         }
372         $remote ||= $Git::SVN::default_repo_id;
373         if ($_fetch_all) {
374                 cmd_multi_fetch();
375         } else {
376                 Git::SVN::fetch_all($remote, Git::SVN::read_all_remotes());
377         }
378 }
379
380 sub cmd_set_tree {
381         my (@commits) = @_;
382         if ($_stdin || !@commits) {
383                 print "Reading from stdin...\n";
384                 @commits = ();
385                 while (<STDIN>) {
386                         if (/\b($sha1_short)\b/o) {
387                                 unshift @commits, $1;
388                         }
389                 }
390         }
391         my @revs;
392         foreach my $c (@commits) {
393                 my @tmp = command('rev-parse',$c);
394                 if (scalar @tmp == 1) {
395                         push @revs, $tmp[0];
396                 } elsif (scalar @tmp > 1) {
397                         push @revs, reverse(command('rev-list',@tmp));
398                 } else {
399                         fatal "Failed to rev-parse $c";
400                 }
401         }
402         my $gs = Git::SVN->new;
403         my ($r_last, $cmt_last) = $gs->last_rev_commit;
404         $gs->fetch;
405         if (defined $gs->{last_rev} && $r_last != $gs->{last_rev}) {
406                 fatal "There are new revisions that were fetched ",
407                       "and need to be merged (or acknowledged) ",
408                       "before committing.\nlast rev: $r_last\n",
409                       " current: $gs->{last_rev}";
410         }
411         $gs->set_tree($_) foreach @revs;
412         print "Done committing ",scalar @revs," revisions to SVN\n";
413         unlink $gs->{index};
414 }
415
416 sub cmd_dcommit {
417         my $head = shift;
418         git_cmd_try { command_oneline(qw/diff-index --quiet HEAD/) }
419                 'Cannot dcommit with a dirty index.  Commit your changes first, '
420                 . "or stash them with `git stash'.\n";
421         $head ||= 'HEAD';
422         my @refs;
423         my ($url, $rev, $uuid, $gs) = working_head_info($head, \@refs);
424         unless ($gs) {
425                 die "Unable to determine upstream SVN information from ",
426                     "$head history.\nPerhaps the repository is empty.";
427         }
428         $url = defined $_commit_url ? $_commit_url : $gs->full_url;
429         my $last_rev = $_revision if defined $_revision;
430         if ($url) {
431                 print "Committing to $url ...\n";
432         }
433         my ($linear_refs, $parents) = linearize_history($gs, \@refs);
434         if ($_no_rebase && scalar(@$linear_refs) > 1) {
435                 warn "Attempting to commit more than one change while ",
436                      "--no-rebase is enabled.\n",
437                      "If these changes depend on each other, re-running ",
438                      "without --no-rebase may be required."
439         }
440         my $expect_url = $url;
441         Git::SVN::remove_username($expect_url);
442         while (1) {
443                 my $d = shift @$linear_refs or last;
444                 unless (defined $last_rev) {
445                         (undef, $last_rev, undef) = cmt_metadata("$d~1");
446                         unless (defined $last_rev) {
447                                 fatal "Unable to extract revision information ",
448                                       "from commit $d~1";
449                         }
450                 }
451                 if ($_dry_run) {
452                         print "diff-tree $d~1 $d\n";
453                 } else {
454                         my $cmt_rev;
455                         my %ed_opts = ( r => $last_rev,
456                                         log => get_commit_entry($d)->{log},
457                                         ra => Git::SVN::Ra->new($url),
458                                         config => SVN::Core::config_get_config(
459                                                 $Git::SVN::Ra::config_dir
460                                         ),
461                                         tree_a => "$d~1",
462                                         tree_b => $d,
463                                         editor_cb => sub {
464                                                print "Committed r$_[0]\n";
465                                                $cmt_rev = $_[0];
466                                         },
467                                         svn_path => '');
468                         if (!SVN::Git::Editor->new(\%ed_opts)->apply_diff) {
469                                 print "No changes\n$d~1 == $d\n";
470                         } elsif ($parents->{$d} && @{$parents->{$d}}) {
471                                 $gs->{inject_parents_dcommit}->{$cmt_rev} =
472                                                                $parents->{$d};
473                         }
474                         $_fetch_all ? $gs->fetch_all : $gs->fetch;
475                         $last_rev = $cmt_rev;
476                         next if $_no_rebase;
477
478                         # we always want to rebase against the current HEAD,
479                         # not any head that was passed to us
480                         my @diff = command('diff-tree', $d,
481                                            $gs->refname, '--');
482                         my @finish;
483                         if (@diff) {
484                                 @finish = rebase_cmd();
485                                 print STDERR "W: $d and ", $gs->refname,
486                                              " differ, using @finish:\n",
487                                              join("\n", @diff), "\n";
488                         } else {
489                                 print "No changes between current HEAD and ",
490                                       $gs->refname,
491                                       "\nResetting to the latest ",
492                                       $gs->refname, "\n";
493                                 @finish = qw/reset --mixed/;
494                         }
495                         command_noisy(@finish, $gs->refname);
496                         if (@diff) {
497                                 @refs = ();
498                                 my ($url_, $rev_, $uuid_, $gs_) =
499                                               working_head_info($head, \@refs);
500                                 my ($linear_refs_, $parents_) =
501                                               linearize_history($gs_, \@refs);
502                                 if (scalar(@$linear_refs) !=
503                                     scalar(@$linear_refs_)) {
504                                         fatal "# of revisions changed ",
505                                           "\nbefore:\n",
506                                           join("\n", @$linear_refs),
507                                           "\n\nafter:\n",
508                                           join("\n", @$linear_refs_), "\n",
509                                           'If you are attempting to commit ',
510                                           "merges, try running:\n\t",
511                                           'git rebase --interactive',
512                                           '--preserve-merges ',
513                                           $gs->refname,
514                                           "\nBefore dcommitting";
515                                 }
516                                 if ($url_ ne $expect_url) {
517                                         fatal "URL mismatch after rebase: ",
518                                               "$url_ != $expect_url";
519                                 }
520                                 if ($uuid_ ne $uuid) {
521                                         fatal "uuid mismatch after rebase: ",
522                                               "$uuid_ != $uuid";
523                                 }
524                                 # remap parents
525                                 my (%p, @l, $i);
526                                 for ($i = 0; $i < scalar @$linear_refs; $i++) {
527                                         my $new = $linear_refs_->[$i] or next;
528                                         $p{$new} =
529                                                 $parents->{$linear_refs->[$i]};
530                                         push @l, $new;
531                                 }
532                                 $parents = \%p;
533                                 $linear_refs = \@l;
534                         }
535                 }
536         }
537         unlink $gs->{index};
538 }
539
540 sub cmd_find_rev {
541         my $revision_or_hash = shift or die "SVN or git revision required ",
542                                             "as a command-line argument\n";
543         my $result;
544         if ($revision_or_hash =~ /^r\d+$/) {
545                 my $head = shift;
546                 $head ||= 'HEAD';
547                 my @refs;
548                 my (undef, undef, $uuid, $gs) = working_head_info($head, \@refs);
549                 unless ($gs) {
550                         die "Unable to determine upstream SVN information from ",
551                             "$head history\n";
552                 }
553                 my $desired_revision = substr($revision_or_hash, 1);
554                 $result = $gs->rev_map_get($desired_revision, $uuid);
555         } else {
556                 my (undef, $rev, undef) = cmt_metadata($revision_or_hash);
557                 $result = $rev;
558         }
559         print "$result\n" if $result;
560 }
561
562 sub cmd_rebase {
563         command_noisy(qw/update-index --refresh/);
564         my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
565         unless ($gs) {
566                 die "Unable to determine upstream SVN information from ",
567                     "working tree history\n";
568         }
569         if ($_dry_run) {
570                 print "Remote Branch: " . $gs->refname . "\n";
571                 print "SVN URL: " . $url . "\n";
572                 return;
573         }
574         if (command(qw/diff-index HEAD --/)) {
575                 print STDERR "Cannot rebase with uncommited changes:\n";
576                 command_noisy('status');
577                 exit 1;
578         }
579         unless ($_local) {
580                 # rebase will checkout for us, so no need to do it explicitly
581                 $_no_checkout = 'true';
582                 $_fetch_all ? $gs->fetch_all : $gs->fetch;
583         }
584         command_noisy(rebase_cmd(), $gs->refname);
585 }
586
587 sub cmd_show_ignore {
588         my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
589         $gs ||= Git::SVN->new;
590         my $r = (defined $_revision ? $_revision : $gs->ra->get_latest_revnum);
591         $gs->prop_walk($gs->{path}, $r, sub {
592                 my ($gs, $path, $props) = @_;
593                 print STDOUT "\n# $path\n";
594                 my $s = $props->{'svn:ignore'} or return;
595                 $s =~ s/[\r\n]+/\n/g;
596                 chomp $s;
597                 $s =~ s#^#$path#gm;
598                 print STDOUT "$s\n";
599         });
600 }
601
602 sub cmd_show_externals {
603         my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
604         $gs ||= Git::SVN->new;
605         my $r = (defined $_revision ? $_revision : $gs->ra->get_latest_revnum);
606         $gs->prop_walk($gs->{path}, $r, sub {
607                 my ($gs, $path, $props) = @_;
608                 print STDOUT "\n# $path\n";
609                 my $s = $props->{'svn:externals'} or return;
610                 $s =~ s/[\r\n]+/\n/g;
611                 chomp $s;
612                 $s =~ s#^#$path#gm;
613                 print STDOUT "$s\n";
614         });
615 }
616
617 sub cmd_create_ignore {
618         my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
619         $gs ||= Git::SVN->new;
620         my $r = (defined $_revision ? $_revision : $gs->ra->get_latest_revnum);
621         $gs->prop_walk($gs->{path}, $r, sub {
622                 my ($gs, $path, $props) = @_;
623                 # $path is of the form /path/to/dir/
624                 my $ignore = '.' . $path . '.gitignore';
625                 my $s = $props->{'svn:ignore'} or return;
626                 open(GITIGNORE, '>', $ignore)
627                   or fatal("Failed to open `$ignore' for writing: $!");
628                 $s =~ s/[\r\n]+/\n/g;
629                 chomp $s;
630                 # Prefix all patterns so that the ignore doesn't apply
631                 # to sub-directories.
632                 $s =~ s#^#/#gm;
633                 print GITIGNORE "$s\n";
634                 close(GITIGNORE)
635                   or fatal("Failed to close `$ignore': $!");
636                 command_noisy('add', '-f', $ignore);
637         });
638 }
639
640 sub canonicalize_path {
641         my ($path) = @_;
642         my $dot_slash_added = 0;
643         if (substr($path, 0, 1) ne "/") {
644                 $path = "./" . $path;
645                 $dot_slash_added = 1;
646         }
647         # File::Spec->canonpath doesn't collapse x/../y into y (for a
648         # good reason), so let's do this manually.
649         $path =~ s#/+#/#g;
650         $path =~ s#/\.(?:/|$)#/#g;
651         $path =~ s#/[^/]+/\.\.##g;
652         $path =~ s#/$##g;
653         $path =~ s#^\./## if $dot_slash_added;
654         $path =~ s#^/##;
655         $path =~ s#^\.$##;
656         return $path;
657 }
658
659 # get_svnprops(PATH)
660 # ------------------
661 # Helper for cmd_propget and cmd_proplist below.
662 sub get_svnprops {
663         my $path = shift;
664         my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
665         $gs ||= Git::SVN->new;
666
667         # prefix THE PATH by the sub-directory from which the user
668         # invoked us.
669         $path = $cmd_dir_prefix . $path;
670         fatal("No such file or directory: $path") unless -e $path;
671         my $is_dir = -d $path ? 1 : 0;
672         $path = $gs->{path} . '/' . $path;
673
674         # canonicalize the path (otherwise libsvn will abort or fail to
675         # find the file)
676         $path = canonicalize_path($path);
677
678         my $r = (defined $_revision ? $_revision : $gs->ra->get_latest_revnum);
679         my $props;
680         if ($is_dir) {
681                 (undef, undef, $props) = $gs->ra->get_dir($path, $r);
682         }
683         else {
684                 (undef, $props) = $gs->ra->get_file($path, $r, undef);
685         }
686         return $props;
687 }
688
689 # cmd_propget (PROP, PATH)
690 # ------------------------
691 # Print the SVN property PROP for PATH.
692 sub cmd_propget {
693         my ($prop, $path) = @_;
694         $path = '.' if not defined $path;
695         usage(1) if not defined $prop;
696         my $props = get_svnprops($path);
697         if (not defined $props->{$prop}) {
698                 fatal("`$path' does not have a `$prop' SVN property.");
699         }
700         print $props->{$prop} . "\n";
701 }
702
703 # cmd_proplist (PATH)
704 # -------------------
705 # Print the list of SVN properties for PATH.
706 sub cmd_proplist {
707         my $path = shift;
708         $path = '.' if not defined $path;
709         my $props = get_svnprops($path);
710         print "Properties on '$path':\n";
711         foreach (sort keys %{$props}) {
712                 print "  $_\n";
713         }
714 }
715
716 sub cmd_multi_init {
717         my $url = shift;
718         unless (defined $_trunk || defined $_branches || defined $_tags) {
719                 usage(1);
720         }
721
722         # there are currently some bugs that prevent multi-init/multi-fetch
723         # setups from working well without this.
724         $Git::SVN::_minimize_url = 1;
725
726         $_prefix = '' unless defined $_prefix;
727         if (defined $url) {
728                 $url =~ s#/+$##;
729                 init_subdir(@_);
730         }
731         do_git_init_db();
732         if (defined $_trunk) {
733                 my $trunk_ref = $_prefix . 'trunk';
734                 # try both old-style and new-style lookups:
735                 my $gs_trunk = eval { Git::SVN->new($trunk_ref) };
736                 unless ($gs_trunk) {
737                         my ($trunk_url, $trunk_path) =
738                                               complete_svn_url($url, $_trunk);
739                         $gs_trunk = Git::SVN->init($trunk_url, $trunk_path,
740                                                    undef, $trunk_ref);
741                 }
742         }
743         return unless defined $_branches || defined $_tags;
744         my $ra = $url ? Git::SVN::Ra->new($url) : undef;
745         complete_url_ls_init($ra, $_branches, '--branches/-b', $_prefix);
746         complete_url_ls_init($ra, $_tags, '--tags/-t', $_prefix . 'tags/');
747 }
748
749 sub cmd_multi_fetch {
750         my $remotes = Git::SVN::read_all_remotes();
751         foreach my $repo_id (sort keys %$remotes) {
752                 if ($remotes->{$repo_id}->{url}) {
753                         Git::SVN::fetch_all($repo_id, $remotes);
754                 }
755         }
756 }
757
758 # this command is special because it requires no metadata
759 sub cmd_commit_diff {
760         my ($ta, $tb, $url) = @_;
761         my $usage = "Usage: $0 commit-diff -r<revision> ".
762                     "<tree-ish> <tree-ish> [<URL>]";
763         fatal($usage) if (!defined $ta || !defined $tb);
764         my $svn_path = '';
765         if (!defined $url) {
766                 my $gs = eval { Git::SVN->new };
767                 if (!$gs) {
768                         fatal("Needed URL or usable git-svn --id in ",
769                               "the command-line\n", $usage);
770                 }
771                 $url = $gs->{url};
772                 $svn_path = $gs->{path};
773         }
774         unless (defined $_revision) {
775                 fatal("-r|--revision is a required argument\n", $usage);
776         }
777         if (defined $_message && defined $_file) {
778                 fatal("Both --message/-m and --file/-F specified ",
779                       "for the commit message.\n",
780                       "I have no idea what you mean");
781         }
782         if (defined $_file) {
783                 $_message = file_to_s($_file);
784         } else {
785                 $_message ||= get_commit_entry($tb)->{log};
786         }
787         my $ra ||= Git::SVN::Ra->new($url);
788         my $r = $_revision;
789         if ($r eq 'HEAD') {
790                 $r = $ra->get_latest_revnum;
791         } elsif ($r !~ /^\d+$/) {
792                 die "revision argument: $r not understood by git-svn\n";
793         }
794         my %ed_opts = ( r => $r,
795                         log => $_message,
796                         ra => $ra,
797                         tree_a => $ta,
798                         tree_b => $tb,
799                         editor_cb => sub { print "Committed r$_[0]\n" },
800                         svn_path => $svn_path );
801         if (!SVN::Git::Editor->new(\%ed_opts)->apply_diff) {
802                 print "No changes\n$ta == $tb\n";
803         }
804 }
805
806 sub cmd_info {
807         my $path = canonicalize_path(defined($_[0]) ? $_[0] : ".");
808         my $fullpath = canonicalize_path($cmd_dir_prefix . $path);
809         if (exists $_[1]) {
810                 die "Too many arguments specified\n";
811         }
812
813         my ($file_type, $diff_status) = find_file_type_and_diff_status($path);
814
815         if (!$file_type && !$diff_status) {
816                 print STDERR "$path:  (Not a versioned resource)\n\n";
817                 return;
818         }
819
820         my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
821         unless ($gs) {
822                 die "Unable to determine upstream SVN information from ",
823                     "working tree history\n";
824         }
825
826         # canonicalize_path() will return "" to make libsvn 1.5.x happy,
827         $path = "." if $path eq "";
828
829         my $full_url = $url . ($fullpath eq "" ? "" : "/$fullpath");
830
831         if ($_url) {
832                 print $full_url, "\n";
833                 return;
834         }
835
836         my $result = "Path: $path\n";
837         $result .= "Name: " . basename($path) . "\n" if $file_type ne "dir";
838         $result .= "URL: " . $full_url . "\n";
839
840         eval {
841                 my $repos_root = $gs->repos_root;
842                 Git::SVN::remove_username($repos_root);
843                 $result .= "Repository Root: $repos_root\n";
844         };
845         if ($@) {
846                 $result .= "Repository Root: (offline)\n";
847         }
848         $result .= "Repository UUID: $uuid\n" unless $diff_status eq "A";
849         $result .= "Revision: " . ($diff_status eq "A" ? 0 : $rev) . "\n";
850
851         $result .= "Node Kind: " .
852                    ($file_type eq "dir" ? "directory" : "file") . "\n";
853
854         my $schedule = $diff_status eq "A"
855                        ? "add"
856                        : ($diff_status eq "D" ? "delete" : "normal");
857         $result .= "Schedule: $schedule\n";
858
859         if ($diff_status eq "A") {
860                 print $result, "\n";
861                 return;
862         }
863
864         my ($lc_author, $lc_rev, $lc_date_utc);
865         my @args = Git::SVN::Log::git_svn_log_cmd($rev, $rev, "--", $fullpath);
866         my $log = command_output_pipe(@args);
867         my $esc_color = qr/(?:\033\[(?:(?:\d+;)*\d*)?m)*/;
868         while (<$log>) {
869                 if (/^${esc_color}author (.+) <[^>]+> (\d+) ([\-\+]?\d+)$/o) {
870                         $lc_author = $1;
871                         $lc_date_utc = Git::SVN::Log::parse_git_date($2, $3);
872                 } elsif (/^${esc_color}    (git-svn-id:.+)$/o) {
873                         (undef, $lc_rev, undef) = ::extract_metadata($1);
874                 }
875         }
876         close $log;
877
878         Git::SVN::Log::set_local_timezone();
879
880         $result .= "Last Changed Author: $lc_author\n";
881         $result .= "Last Changed Rev: $lc_rev\n";
882         $result .= "Last Changed Date: " .
883                    Git::SVN::Log::format_svn_date($lc_date_utc) . "\n";
884
885         if ($file_type ne "dir") {
886                 my $text_last_updated_date =
887                     ($diff_status eq "D" ? $lc_date_utc : (stat $path)[9]);
888                 $result .=
889                     "Text Last Updated: " .
890                     Git::SVN::Log::format_svn_date($text_last_updated_date) .
891                     "\n";
892                 my $checksum;
893                 if ($diff_status eq "D") {
894                         my ($fh, $ctx) =
895                             command_output_pipe(qw(cat-file blob), "HEAD:$path");
896                         if ($file_type eq "link") {
897                                 my $file_name = <$fh>;
898                                 $checksum = md5sum("link $file_name");
899                         } else {
900                                 $checksum = md5sum($fh);
901                         }
902                         command_close_pipe($fh, $ctx);
903                 } elsif ($file_type eq "link") {
904                         my $file_name =
905                             command(qw(cat-file blob), "HEAD:$path");
906                         $checksum =
907                             md5sum("link " . $file_name);
908                 } else {
909                         open FILE, "<", $path or die $!;
910                         $checksum = md5sum(\*FILE);
911                         close FILE or die $!;
912                 }
913                 $result .= "Checksum: " . $checksum . "\n";
914         }
915
916         print $result, "\n";
917 }
918
919 ########################### utility functions #########################
920
921 sub rebase_cmd {
922         my @cmd = qw/rebase/;
923         push @cmd, '-v' if $_verbose;
924         push @cmd, qw/--merge/ if $_merge;
925         push @cmd, "--strategy=$_strategy" if $_strategy;
926         @cmd;
927 }
928
929 sub post_fetch_checkout {
930         return if $_no_checkout;
931         my $gs = $Git::SVN::_head or return;
932         return if verify_ref('refs/heads/master^0');
933
934         my $valid_head = verify_ref('HEAD^0');
935         command_noisy(qw(update-ref refs/heads/master), $gs->refname);
936         return if ($valid_head || !verify_ref('HEAD^0'));
937
938         return if $ENV{GIT_DIR} !~ m#^(?:.*/)?\.git$#;
939         my $index = $ENV{GIT_INDEX_FILE} || "$ENV{GIT_DIR}/index";
940         return if -f $index;
941
942         return if command_oneline(qw/rev-parse --is-inside-work-tree/) eq 'false';
943         return if command_oneline(qw/rev-parse --is-inside-git-dir/) eq 'true';
944         command_noisy(qw/read-tree -m -u -v HEAD HEAD/);
945         print STDERR "Checked out HEAD:\n  ",
946                      $gs->full_url, " r", $gs->last_rev, "\n";
947 }
948
949 sub complete_svn_url {
950         my ($url, $path) = @_;
951         $path =~ s#/+$##;
952         if ($path !~ m#^[a-z\+]+://#) {
953                 if (!defined $url || $url !~ m#^[a-z\+]+://#) {
954                         fatal("E: '$path' is not a complete URL ",
955                               "and a separate URL is not specified");
956                 }
957                 return ($url, $path);
958         }
959         return ($path, '');
960 }
961
962 sub complete_url_ls_init {
963         my ($ra, $repo_path, $switch, $pfx) = @_;
964         unless ($repo_path) {
965                 print STDERR "W: $switch not specified\n";
966                 return;
967         }
968         $repo_path =~ s#/+$##;
969         if ($repo_path =~ m#^[a-z\+]+://#) {
970                 $ra = Git::SVN::Ra->new($repo_path);
971                 $repo_path = '';
972         } else {
973                 $repo_path =~ s#^/+##;
974                 unless ($ra) {
975                         fatal("E: '$repo_path' is not a complete URL ",
976                               "and a separate URL is not specified");
977                 }
978         }
979         my $url = $ra->{url};
980         my $gs = Git::SVN->init($url, undef, undef, undef, 1);
981         my $k = "svn-remote.$gs->{repo_id}.url";
982         my $orig_url = eval { command_oneline(qw/config --get/, $k) };
983         if ($orig_url && ($orig_url ne $gs->{url})) {
984                 die "$k already set: $orig_url\n",
985                     "wanted to set to: $gs->{url}\n";
986         }
987         command_oneline('config', $k, $gs->{url}) unless $orig_url;
988         my $remote_path = "$ra->{svn_path}/$repo_path";
989         $remote_path =~ s#/+#/#g;
990         $remote_path =~ s#^/##g;
991         $remote_path .= "/*" if $remote_path !~ /\*/;
992         my ($n) = ($switch =~ /^--(\w+)/);
993         if (length $pfx && $pfx !~ m#/$#) {
994                 die "--prefix='$pfx' must have a trailing slash '/'\n";
995         }
996         command_noisy('config',
997                       "svn-remote.$gs->{repo_id}.$n",
998                       "$remote_path:refs/remotes/$pfx*" .
999                         ('/*' x (($remote_path =~ tr/*/*/) - 1)) );
1000 }
1001
1002 sub verify_ref {
1003         my ($ref) = @_;
1004         eval { command_oneline([ 'rev-parse', '--verify', $ref ],
1005                                { STDERR => 0 }); };
1006 }
1007
1008 sub get_tree_from_treeish {
1009         my ($treeish) = @_;
1010         # $treeish can be a symbolic ref, too:
1011         my $type = command_oneline(qw/cat-file -t/, $treeish);
1012         my $expected;
1013         while ($type eq 'tag') {
1014                 ($treeish, $type) = command(qw/cat-file tag/, $treeish);
1015         }
1016         if ($type eq 'commit') {
1017                 $expected = (grep /^tree /, command(qw/cat-file commit/,
1018                                                     $treeish))[0];
1019                 ($expected) = ($expected =~ /^tree ($sha1)$/o);
1020                 die "Unable to get tree from $treeish\n" unless $expected;
1021         } elsif ($type eq 'tree') {
1022                 $expected = $treeish;
1023         } else {
1024                 die "$treeish is a $type, expected tree, tag or commit\n";
1025         }
1026         return $expected;
1027 }
1028
1029 sub get_commit_entry {
1030         my ($treeish) = shift;
1031         my %log_entry = ( log => '', tree => get_tree_from_treeish($treeish) );
1032         my $commit_editmsg = "$ENV{GIT_DIR}/COMMIT_EDITMSG";
1033         my $commit_msg = "$ENV{GIT_DIR}/COMMIT_MSG";
1034         open my $log_fh, '>', $commit_editmsg or croak $!;
1035
1036         my $type = command_oneline(qw/cat-file -t/, $treeish);
1037         if ($type eq 'commit' || $type eq 'tag') {
1038                 my ($msg_fh, $ctx) = command_output_pipe('cat-file',
1039                                                          $type, $treeish);
1040                 my $in_msg = 0;
1041                 my $author;
1042                 my $saw_from = 0;
1043                 my $msgbuf = "";
1044                 while (<$msg_fh>) {
1045                         if (!$in_msg) {
1046                                 $in_msg = 1 if (/^\s*$/);
1047                                 $author = $1 if (/^author (.*>)/);
1048                         } elsif (/^git-svn-id: /) {
1049                                 # skip this for now, we regenerate the
1050                                 # correct one on re-fetch anyways
1051                                 # TODO: set *:merge properties or like...
1052                         } else {
1053                                 if (/^From:/ || /^Signed-off-by:/) {
1054                                         $saw_from = 1;
1055                                 }
1056                                 $msgbuf .= $_;
1057                         }
1058                 }
1059                 $msgbuf =~ s/\s+$//s;
1060                 if ($Git::SVN::_add_author_from && defined($author)
1061                     && !$saw_from) {
1062                         $msgbuf .= "\n\nFrom: $author";
1063                 }
1064                 print $log_fh $msgbuf or croak $!;
1065                 command_close_pipe($msg_fh, $ctx);
1066         }
1067         close $log_fh or croak $!;
1068
1069         if ($_edit || ($type eq 'tree')) {
1070                 my $editor = $ENV{VISUAL} || $ENV{EDITOR} || 'vi';
1071                 # TODO: strip out spaces, comments, like git-commit.sh
1072                 system($editor, $commit_editmsg);
1073         }
1074         rename $commit_editmsg, $commit_msg or croak $!;
1075         open $log_fh, '<', $commit_msg or croak $!;
1076         { local $/; chomp($log_entry{log} = <$log_fh>); }
1077         close $log_fh or croak $!;
1078         unlink $commit_msg;
1079         \%log_entry;
1080 }
1081
1082 sub s_to_file {
1083         my ($str, $file, $mode) = @_;
1084         open my $fd,'>',$file or croak $!;
1085         print $fd $str,"\n" or croak $!;
1086         close $fd or croak $!;
1087         chmod ($mode &~ umask, $file) if (defined $mode);
1088 }
1089
1090 sub file_to_s {
1091         my $file = shift;
1092         open my $fd,'<',$file or croak "$!: file: $file\n";
1093         local $/;
1094         my $ret = <$fd>;
1095         close $fd or croak $!;
1096         $ret =~ s/\s*$//s;
1097         return $ret;
1098 }
1099
1100 # '<svn username> = real-name <email address>' mapping based on git-svnimport:
1101 sub load_authors {
1102         open my $authors, '<', $_authors or die "Can't open $_authors $!\n";
1103         my $log = $cmd eq 'log';
1104         while (<$authors>) {
1105                 chomp;
1106                 next unless /^(.+?|\(no author\))\s*=\s*(.+?)\s*<(.+)>\s*$/;
1107                 my ($user, $name, $email) = ($1, $2, $3);
1108                 if ($log) {
1109                         $Git::SVN::Log::rusers{"$name <$email>"} = $user;
1110                 } else {
1111                         $users{$user} = [$name, $email];
1112                 }
1113         }
1114         close $authors or croak $!;
1115 }
1116
1117 # convert GetOpt::Long specs for use by git-config
1118 sub read_repo_config {
1119         return unless -d $ENV{GIT_DIR};
1120         my $opts = shift;
1121         my @config_only;
1122         foreach my $o (keys %$opts) {
1123                 # if we have mixedCase and a long option-only, then
1124                 # it's a config-only variable that we don't need for
1125                 # the command-line.
1126                 push @config_only, $o if ($o =~ /[A-Z]/ && $o =~ /^[a-z]+$/i);
1127                 my $v = $opts->{$o};
1128                 my ($key) = ($o =~ /^([a-zA-Z\-]+)/);
1129                 $key =~ s/-//g;
1130                 my $arg = 'git-config';
1131                 $arg .= ' --int' if ($o =~ /[:=]i$/);
1132                 $arg .= ' --bool' if ($o !~ /[:=][sfi]$/);
1133                 if (ref $v eq 'ARRAY') {
1134                         chomp(my @tmp = `$arg --get-all svn.$key`);
1135                         @$v = @tmp if @tmp;
1136                 } else {
1137                         chomp(my $tmp = `$arg --get svn.$key`);
1138                         if ($tmp && !($arg =~ / --bool/ && $tmp eq 'false')) {
1139                                 $$v = $tmp;
1140                         }
1141                 }
1142         }
1143         delete @$opts{@config_only} if @config_only;
1144 }
1145
1146 sub extract_metadata {
1147         my $id = shift or return (undef, undef, undef);
1148         my ($url, $rev, $uuid) = ($id =~ /^\s*git-svn-id:\s+(.*)\@(\d+)
1149                                                         \s([a-f\d\-]+)$/x);
1150         if (!defined $rev || !$uuid || !$url) {
1151                 # some of the original repositories I made had
1152                 # identifiers like this:
1153                 ($rev, $uuid) = ($id =~/^\s*git-svn-id:\s(\d+)\@([a-f\d\-]+)/);
1154         }
1155         return ($url, $rev, $uuid);
1156 }
1157
1158 sub cmt_metadata {
1159         return extract_metadata((grep(/^git-svn-id: /,
1160                 command(qw/cat-file commit/, shift)))[-1]);
1161 }
1162
1163 sub working_head_info {
1164         my ($head, $refs) = @_;
1165         my @args = ('log', '--no-color', '--first-parent', '--pretty=medium');
1166         my ($fh, $ctx) = command_output_pipe(@args, $head);
1167         my $hash;
1168         my %max;
1169         while (<$fh>) {
1170                 if ( m{^commit ($::sha1)$} ) {
1171                         unshift @$refs, $hash if $hash and $refs;
1172                         $hash = $1;
1173                         next;
1174                 }
1175                 next unless s{^\s*(git-svn-id:)}{$1};
1176                 my ($url, $rev, $uuid) = extract_metadata($_);
1177                 if (defined $url && defined $rev) {
1178                         next if $max{$url} and $max{$url} < $rev;
1179                         if (my $gs = Git::SVN->find_by_url($url)) {
1180                                 my $c = $gs->rev_map_get($rev, $uuid);
1181                                 if ($c && $c eq $hash) {
1182                                         close $fh; # break the pipe
1183                                         return ($url, $rev, $uuid, $gs);
1184                                 } else {
1185                                         $max{$url} ||= $gs->rev_map_max;
1186                                 }
1187                         }
1188                 }
1189         }
1190         command_close_pipe($fh, $ctx);
1191         (undef, undef, undef, undef);
1192 }
1193
1194 sub read_commit_parents {
1195         my ($parents, $c) = @_;
1196         chomp(my $p = command_oneline(qw/rev-list --parents -1/, $c));
1197         $p =~ s/^($c)\s*// or die "rev-list --parents -1 $c failed!\n";
1198         @{$parents->{$c}} = split(/ /, $p);
1199 }
1200
1201 sub linearize_history {
1202         my ($gs, $refs) = @_;
1203         my %parents;
1204         foreach my $c (@$refs) {
1205                 read_commit_parents(\%parents, $c);
1206         }
1207
1208         my @linear_refs;
1209         my %skip = ();
1210         my $last_svn_commit = $gs->last_commit;
1211         foreach my $c (reverse @$refs) {
1212                 next if $c eq $last_svn_commit;
1213                 last if $skip{$c};
1214
1215                 unshift @linear_refs, $c;
1216                 $skip{$c} = 1;
1217
1218                 # we only want the first parent to diff against for linear
1219                 # history, we save the rest to inject when we finalize the
1220                 # svn commit
1221                 my $fp_a = verify_ref("$c~1");
1222                 my $fp_b = shift @{$parents{$c}} if $parents{$c};
1223                 if (!$fp_a || !$fp_b) {
1224                         die "Commit $c\n",
1225                             "has no parent commit, and therefore ",
1226                             "nothing to diff against.\n",
1227                             "You should be working from a repository ",
1228                             "originally created by git-svn\n";
1229                 }
1230                 if ($fp_a ne $fp_b) {
1231                         die "$c~1 = $fp_a, however parsing commit $c ",
1232                             "revealed that:\n$c~1 = $fp_b\nBUG!\n";
1233                 }
1234
1235                 foreach my $p (@{$parents{$c}}) {
1236                         $skip{$p} = 1;
1237                 }
1238         }
1239         (\@linear_refs, \%parents);
1240 }
1241
1242 sub find_file_type_and_diff_status {
1243         my ($path) = @_;
1244         return ('dir', '') if $path eq '';
1245
1246         my $diff_output =
1247             command_oneline(qw(diff --cached --name-status --), $path) || "";
1248         my $diff_status = (split(' ', $diff_output))[0] || "";
1249
1250         my $ls_tree = command_oneline(qw(ls-tree HEAD), $path) || "";
1251
1252         return (undef, undef) if !$diff_status && !$ls_tree;
1253
1254         if ($diff_status eq "A") {
1255                 return ("link", $diff_status) if -l $path;
1256                 return ("dir", $diff_status) if -d $path;
1257                 return ("file", $diff_status);
1258         }
1259
1260         my $mode = (split(' ', $ls_tree))[0] || "";
1261
1262         return ("link", $diff_status) if $mode eq "120000";
1263         return ("dir", $diff_status) if $mode eq "040000";
1264         return ("file", $diff_status);
1265 }
1266
1267 sub md5sum {
1268         my $arg = shift;
1269         my $ref = ref $arg;
1270         my $md5 = Digest::MD5->new();
1271         if ($ref eq 'GLOB' || $ref eq 'IO::File' || $ref eq 'File::Temp') {
1272                 $md5->addfile($arg) or croak $!;
1273         } elsif ($ref eq 'SCALAR') {
1274                 $md5->add($$arg) or croak $!;
1275         } elsif (!$ref) {
1276                 $md5->add($arg) or croak $!;
1277         } else {
1278                 ::fatal "Can't provide MD5 hash for unknown ref type: '", $ref, "'";
1279         }
1280         return $md5->hexdigest();
1281 }
1282
1283 package Git::SVN;
1284 use strict;
1285 use warnings;
1286 use Fcntl qw/:DEFAULT :seek/;
1287 use constant rev_map_fmt => 'NH40';
1288 use vars qw/$default_repo_id $default_ref_id $_no_metadata $_follow_parent
1289             $_repack $_repack_flags $_use_svm_props $_head
1290             $_use_svnsync_props $no_reuse_existing $_minimize_url
1291             $_use_log_author $_add_author_from/;
1292 use Carp qw/croak/;
1293 use File::Path qw/mkpath/;
1294 use File::Copy qw/copy/;
1295 use IPC::Open3;
1296
1297 my ($_gc_nr, $_gc_period);
1298
1299 # properties that we do not log:
1300 my %SKIP_PROP;
1301 BEGIN {
1302         %SKIP_PROP = map { $_ => 1 } qw/svn:wc:ra_dav:version-url
1303                                         svn:special svn:executable
1304                                         svn:entry:committed-rev
1305                                         svn:entry:last-author
1306                                         svn:entry:uuid
1307                                         svn:entry:committed-date/;
1308
1309         # some options are read globally, but can be overridden locally
1310         # per [svn-remote "..."] section.  Command-line options will *NOT*
1311         # override options set in an [svn-remote "..."] section
1312         no strict 'refs';
1313         for my $option (qw/follow_parent no_metadata use_svm_props
1314                            use_svnsync_props/) {
1315                 my $key = $option;
1316                 $key =~ tr/_//d;
1317                 my $prop = "-$option";
1318                 *$option = sub {
1319                         my ($self) = @_;
1320                         return $self->{$prop} if exists $self->{$prop};
1321                         my $k = "svn-remote.$self->{repo_id}.$key";
1322                         eval { command_oneline(qw/config --get/, $k) };
1323                         if ($@) {
1324                                 $self->{$prop} = ${"Git::SVN::_$option"};
1325                         } else {
1326                                 my $v = command_oneline(qw/config --bool/,$k);
1327                                 $self->{$prop} = $v eq 'false' ? 0 : 1;
1328                         }
1329                         return $self->{$prop};
1330                 }
1331         }
1332 }
1333
1334
1335 my (%LOCKFILES, %INDEX_FILES);
1336 END {
1337         unlink keys %LOCKFILES if %LOCKFILES;
1338         unlink keys %INDEX_FILES if %INDEX_FILES;
1339 }
1340
1341 sub resolve_local_globs {
1342         my ($url, $fetch, $glob_spec) = @_;
1343         return unless defined $glob_spec;
1344         my $ref = $glob_spec->{ref};
1345         my $path = $glob_spec->{path};
1346         foreach (command(qw#for-each-ref --format=%(refname) refs/remotes#)) {
1347                 next unless m#^refs/remotes/$ref->{regex}$#;
1348                 my $p = $1;
1349                 my $pathname = desanitize_refname($path->full_path($p));
1350                 my $refname = desanitize_refname($ref->full_path($p));
1351                 if (my $existing = $fetch->{$pathname}) {
1352                         if ($existing ne $refname) {
1353                                 die "Refspec conflict:\n",
1354                                     "existing: refs/remotes/$existing\n",
1355                                     " globbed: refs/remotes/$refname\n";
1356                         }
1357                         my $u = (::cmt_metadata("refs/remotes/$refname"))[0];
1358                         $u =~ s!^\Q$url\E(/|$)!! or die
1359                           "refs/remotes/$refname: '$url' not found in '$u'\n";
1360                         if ($pathname ne $u) {
1361                                 warn "W: Refspec glob conflict ",
1362                                      "(ref: refs/remotes/$refname):\n",
1363                                      "expected path: $pathname\n",
1364                                      "    real path: $u\n",
1365                                      "Continuing ahead with $u\n";
1366                                 next;
1367                         }
1368                 } else {
1369                         $fetch->{$pathname} = $refname;
1370                 }
1371         }
1372 }
1373
1374 sub parse_revision_argument {
1375         my ($base, $head) = @_;
1376         if (!defined $::_revision || $::_revision eq 'BASE:HEAD') {
1377                 return ($base, $head);
1378         }
1379         return ($1, $2) if ($::_revision =~ /^(\d+):(\d+)$/);
1380         return ($::_revision, $::_revision) if ($::_revision =~ /^\d+$/);
1381         return ($head, $head) if ($::_revision eq 'HEAD');
1382         return ($base, $1) if ($::_revision =~ /^BASE:(\d+)$/);
1383         return ($1, $head) if ($::_revision =~ /^(\d+):HEAD$/);
1384         die "revision argument: $::_revision not understood by git-svn\n";
1385 }
1386
1387 sub fetch_all {
1388         my ($repo_id, $remotes) = @_;
1389         if (ref $repo_id) {
1390                 my $gs = $repo_id;
1391                 $repo_id = undef;
1392                 $repo_id = $gs->{repo_id};
1393         }
1394         $remotes ||= read_all_remotes();
1395         my $remote = $remotes->{$repo_id} or
1396                      die "[svn-remote \"$repo_id\"] unknown\n";
1397         my $fetch = $remote->{fetch};
1398         my $url = $remote->{url} or die "svn-remote.$repo_id.url not defined\n";
1399         my (@gs, @globs);
1400         my $ra = Git::SVN::Ra->new($url);
1401         my $uuid = $ra->get_uuid;
1402         my $head = $ra->get_latest_revnum;
1403         my $base = defined $fetch ? $head : 0;
1404
1405         # read the max revs for wildcard expansion (branches/*, tags/*)
1406         foreach my $t (qw/branches tags/) {
1407                 defined $remote->{$t} or next;
1408                 push @globs, $remote->{$t};
1409                 my $max_rev = eval { tmp_config(qw/--int --get/,
1410                                          "svn-remote.$repo_id.${t}-maxRev") };
1411                 if (defined $max_rev && ($max_rev < $base)) {
1412                         $base = $max_rev;
1413                 } elsif (!defined $max_rev) {
1414                         $base = 0;
1415                 }
1416         }
1417
1418         if ($fetch) {
1419                 foreach my $p (sort keys %$fetch) {
1420                         my $gs = Git::SVN->new($fetch->{$p}, $repo_id, $p);
1421                         my $lr = $gs->rev_map_max;
1422                         if (defined $lr) {
1423                                 $base = $lr if ($lr < $base);
1424                         }
1425                         push @gs, $gs;
1426                 }
1427         }
1428
1429         ($base, $head) = parse_revision_argument($base, $head);
1430         $ra->gs_fetch_loop_common($base, $head, \@gs, \@globs);
1431 }
1432
1433 sub read_all_remotes {
1434         my $r = {};
1435         my $use_svm_props = eval { command_oneline(qw/config --bool
1436             svn.useSvmProps/) };
1437         $use_svm_props = $use_svm_props eq 'true' if $use_svm_props;
1438         foreach (grep { s/^svn-remote\.// } command(qw/config -l/)) {
1439                 if (m!^(.+)\.fetch=\s*(.*)\s*:\s*(.+)\s*$!) {
1440                         my ($remote, $local_ref, $_remote_ref) = ($1, $2, $3);
1441                         die("svn-remote.$remote: remote ref '$_remote_ref' "
1442                             . "must start with 'refs/remotes/'\n")
1443                                 unless $_remote_ref =~ m{^refs/remotes/(.+)};
1444                         my $remote_ref = $1;
1445                         $local_ref =~ s{^/}{};
1446                         $r->{$remote}->{fetch}->{$local_ref} = $remote_ref;
1447                         $r->{$remote}->{svm} = {} if $use_svm_props;
1448                 } elsif (m!^(.+)\.usesvmprops=\s*(.*)\s*$!) {
1449                         $r->{$1}->{svm} = {};
1450                 } elsif (m!^(.+)\.url=\s*(.*)\s*$!) {
1451                         $r->{$1}->{url} = $2;
1452                 } elsif (m!^(.+)\.(branches|tags)=
1453                            (.*):refs/remotes/(.+)\s*$/!x) {
1454                         my ($p, $g) = ($3, $4);
1455                         my $rs = $r->{$1}->{$2} = {
1456                                           t => $2,
1457                                           remote => $1,
1458                                           path => Git::SVN::GlobSpec->new($p),
1459                                           ref => Git::SVN::GlobSpec->new($g) };
1460                         if (length($rs->{ref}->{right}) != 0) {
1461                                 die "The '*' glob character must be the last ",
1462                                     "character of '$g'\n";
1463                         }
1464                 }
1465         }
1466
1467         map {
1468                 if (defined $r->{$_}->{svm}) {
1469                         my $svm;
1470                         eval {
1471                                 my $section = "svn-remote.$_";
1472                                 $svm = {
1473                                         source => tmp_config('--get',
1474                                             "$section.svm-source"),
1475                                         replace => tmp_config('--get',
1476                                             "$section.svm-replace"),
1477                                 }
1478                         };
1479                         $r->{$_}->{svm} = $svm;
1480                 }
1481         } keys %$r;
1482
1483         $r;
1484 }
1485
1486 sub init_vars {
1487         $_gc_nr = $_gc_period = 1000;
1488         if (defined $_repack || defined $_repack_flags) {
1489                warn "Repack options are obsolete; they have no effect.\n";
1490         }
1491 }
1492
1493 sub verify_remotes_sanity {
1494         return unless -d $ENV{GIT_DIR};
1495         my %seen;
1496         foreach (command(qw/config -l/)) {
1497                 if (m!^svn-remote\.(?:.+)\.fetch=.*:refs/remotes/(\S+)\s*$!) {
1498                         if ($seen{$1}) {
1499                                 die "Remote ref refs/remote/$1 is tracked by",
1500                                     "\n  \"$_\"\nand\n  \"$seen{$1}\"\n",
1501                                     "Please resolve this ambiguity in ",
1502                                     "your git configuration file before ",
1503                                     "continuing\n";
1504                         }
1505                         $seen{$1} = $_;
1506                 }
1507         }
1508 }
1509
1510 sub find_existing_remote {
1511         my ($url, $remotes) = @_;
1512         return undef if $no_reuse_existing;
1513         my $existing;
1514         foreach my $repo_id (keys %$remotes) {
1515                 my $u = $remotes->{$repo_id}->{url} or next;
1516                 next if $u ne $url;
1517                 $existing = $repo_id;
1518                 last;
1519         }
1520         $existing;
1521 }
1522
1523 sub init_remote_config {
1524         my ($self, $url, $no_write) = @_;
1525         $url =~ s!/+$!!; # strip trailing slash
1526         my $r = read_all_remotes();
1527         my $existing = find_existing_remote($url, $r);
1528         if ($existing) {
1529                 unless ($no_write) {
1530                         print STDERR "Using existing ",
1531                                      "[svn-remote \"$existing\"]\n";
1532                 }
1533                 $self->{repo_id} = $existing;
1534         } elsif ($_minimize_url) {
1535                 my $min_url = Git::SVN::Ra->new($url)->minimize_url;
1536                 $existing = find_existing_remote($min_url, $r);
1537                 if ($existing) {
1538                         unless ($no_write) {
1539                                 print STDERR "Using existing ",
1540                                              "[svn-remote \"$existing\"]\n";
1541                         }
1542                         $self->{repo_id} = $existing;
1543                 }
1544                 if ($min_url ne $url) {
1545                         unless ($no_write) {
1546                                 print STDERR "Using higher level of URL: ",
1547                                              "$url => $min_url\n";
1548                         }
1549                         my $old_path = $self->{path};
1550                         $self->{path} = $url;
1551                         $self->{path} =~ s!^\Q$min_url\E(/|$)!!;
1552                         if (length $old_path) {
1553                                 $self->{path} .= "/$old_path";
1554                         }
1555                         $url = $min_url;
1556                 }
1557         }
1558         my $orig_url;
1559         if (!$existing) {
1560                 # verify that we aren't overwriting anything:
1561                 $orig_url = eval {
1562                         command_oneline('config', '--get',
1563                                         "svn-remote.$self->{repo_id}.url")
1564                 };
1565                 if ($orig_url && ($orig_url ne $url)) {
1566                         die "svn-remote.$self->{repo_id}.url already set: ",
1567                             "$orig_url\nwanted to set to: $url\n";
1568                 }
1569         }
1570         my ($xrepo_id, $xpath) = find_ref($self->refname);
1571         if (defined $xpath) {
1572                 die "svn-remote.$xrepo_id.fetch already set to track ",
1573                     "$xpath:refs/remotes/", $self->refname, "\n";
1574         }
1575         unless ($no_write) {
1576                 command_noisy('config',
1577                               "svn-remote.$self->{repo_id}.url", $url);
1578                 $self->{path} =~ s{^/}{};
1579                 command_noisy('config', '--add',
1580                               "svn-remote.$self->{repo_id}.fetch",
1581                               "$self->{path}:".$self->refname);
1582         }
1583         $self->{url} = $url;
1584 }
1585
1586 sub find_by_url { # repos_root and, path are optional
1587         my ($class, $full_url, $repos_root, $path) = @_;
1588
1589         return undef unless defined $full_url;
1590         remove_username($full_url);
1591         remove_username($repos_root) if defined $repos_root;
1592         my $remotes = read_all_remotes();
1593         if (defined $full_url && defined $repos_root && !defined $path) {
1594                 $path = $full_url;
1595                 $path =~ s#^\Q$repos_root\E(?:/|$)##;
1596         }
1597         foreach my $repo_id (keys %$remotes) {
1598                 my $u = $remotes->{$repo_id}->{url} or next;
1599                 remove_username($u);
1600                 next if defined $repos_root && $repos_root ne $u;
1601
1602                 my $fetch = $remotes->{$repo_id}->{fetch} || {};
1603                 foreach (qw/branches tags/) {
1604                         resolve_local_globs($u, $fetch,
1605                                             $remotes->{$repo_id}->{$_});
1606                 }
1607                 my $p = $path;
1608                 my $rwr = rewrite_root({repo_id => $repo_id});
1609                 my $svm = $remotes->{$repo_id}->{svm}
1610                         if defined $remotes->{$repo_id}->{svm};
1611                 unless (defined $p) {
1612                         $p = $full_url;
1613                         my $z = $u;
1614                         my $prefix = '';
1615                         if ($rwr) {
1616                                 $z = $rwr;
1617                         } elsif (defined $svm) {
1618                                 $z = $svm->{source};
1619                                 $prefix = $svm->{replace};
1620                                 $prefix =~ s#^\Q$u\E(?:/|$)##;
1621                                 $prefix =~ s#/$##;
1622                         }
1623                         $p =~ s#^\Q$z\E(?:/|$)#$prefix# or next;
1624                 }
1625                 foreach my $f (keys %$fetch) {
1626                         next if $f ne $p;
1627                         return Git::SVN->new($fetch->{$f}, $repo_id, $f);
1628                 }
1629         }
1630         undef;
1631 }
1632
1633 sub init {
1634         my ($class, $url, $path, $repo_id, $ref_id, $no_write) = @_;
1635         my $self = _new($class, $repo_id, $ref_id, $path);
1636         if (defined $url) {
1637                 $self->init_remote_config($url, $no_write);
1638         }
1639         $self;
1640 }
1641
1642 sub find_ref {
1643         my ($ref_id) = @_;
1644         foreach (command(qw/config -l/)) {
1645                 next unless m!^svn-remote\.(.+)\.fetch=
1646                               \s*(.*)\s*:\s*refs/remotes/(.+)\s*$!x;
1647                 my ($repo_id, $path, $ref) = ($1, $2, $3);
1648                 if ($ref eq $ref_id) {
1649                         $path = '' if ($path =~ m#^\./?#);
1650                         return ($repo_id, $path);
1651                 }
1652         }
1653         (undef, undef, undef);
1654 }
1655
1656 sub new {
1657         my ($class, $ref_id, $repo_id, $path) = @_;
1658         if (defined $ref_id && !defined $repo_id && !defined $path) {
1659                 ($repo_id, $path) = find_ref($ref_id);
1660                 if (!defined $repo_id) {
1661                         die "Could not find a \"svn-remote.*.fetch\" key ",
1662                             "in the repository configuration matching: ",
1663                             "refs/remotes/$ref_id\n";
1664                 }
1665         }
1666         my $self = _new($class, $repo_id, $ref_id, $path);
1667         if (!defined $self->{path} || !length $self->{path}) {
1668                 my $fetch = command_oneline('config', '--get',
1669                                             "svn-remote.$repo_id.fetch",
1670                                             ":refs/remotes/$ref_id\$") or
1671                      die "Failed to read \"svn-remote.$repo_id.fetch\" ",
1672                          "\":refs/remotes/$ref_id\$\" in config\n";
1673                 ($self->{path}, undef) = split(/\s*:\s*/, $fetch);
1674         }
1675         $self->{url} = command_oneline('config', '--get',
1676                                        "svn-remote.$repo_id.url") or
1677                   die "Failed to read \"svn-remote.$repo_id.url\" in config\n";
1678         $self->rebuild;
1679         $self;
1680 }
1681
1682 sub refname {
1683         my ($refname) = "refs/remotes/$_[0]->{ref_id}" ;
1684
1685         # It cannot end with a slash /, we'll throw up on this because
1686         # SVN can't have directories with a slash in their name, either:
1687         if ($refname =~ m{/$}) {
1688                 die "ref: '$refname' ends with a trailing slash, this is ",
1689                     "not permitted by git nor Subversion\n";
1690         }
1691
1692         # It cannot have ASCII control character space, tilde ~, caret ^,
1693         # colon :, question-mark ?, asterisk *, space, or open bracket [
1694         # anywhere.
1695         #
1696         # Additionally, % must be escaped because it is used for escaping
1697         # and we want our escaped refname to be reversible
1698         $refname =~ s{([ \%~\^:\?\*\[\t])}{uc sprintf('%%%02x',ord($1))}eg;
1699
1700         # no slash-separated component can begin with a dot .
1701         # /.* becomes /%2E*
1702         $refname =~ s{/\.}{/%2E}g;
1703
1704         # It cannot have two consecutive dots .. anywhere
1705         # .. becomes %2E%2E
1706         $refname =~ s{\.\.}{%2E%2E}g;
1707
1708         return $refname;
1709 }
1710
1711 sub desanitize_refname {
1712         my ($refname) = @_;
1713         $refname =~ s{%(?:([0-9A-F]{2}))}{chr hex($1)}eg;
1714         return $refname;
1715 }
1716
1717 sub svm_uuid {
1718         my ($self) = @_;
1719         return $self->{svm}->{uuid} if $self->svm;
1720         $self->ra;
1721         unless ($self->{svm}) {
1722                 die "SVM UUID not cached, and reading remotely failed\n";
1723         }
1724         $self->{svm}->{uuid};
1725 }
1726
1727 sub svm {
1728         my ($self) = @_;
1729         return $self->{svm} if $self->{svm};
1730         my $svm;
1731         # see if we have it in our config, first:
1732         eval {
1733                 my $section = "svn-remote.$self->{repo_id}";
1734                 $svm = {
1735                   source => tmp_config('--get', "$section.svm-source"),
1736                   uuid => tmp_config('--get', "$section.svm-uuid"),
1737                   replace => tmp_config('--get', "$section.svm-replace"),
1738                 }
1739         };
1740         if ($svm && $svm->{source} && $svm->{uuid} && $svm->{replace}) {
1741                 $self->{svm} = $svm;
1742         }
1743         $self->{svm};
1744 }
1745
1746 sub _set_svm_vars {
1747         my ($self, $ra) = @_;
1748         return $ra if $self->svm;
1749
1750         my @err = ( "useSvmProps set, but failed to read SVM properties\n",
1751                     "(svm:source, svm:uuid) ",
1752                     "from the following URLs:\n" );
1753         sub read_svm_props {
1754                 my ($self, $ra, $path, $r) = @_;
1755                 my $props = ($ra->get_dir($path, $r))[2];
1756                 my $src = $props->{'svm:source'};
1757                 my $uuid = $props->{'svm:uuid'};
1758                 return undef if (!$src || !$uuid);
1759
1760                 chomp($src, $uuid);
1761
1762                 $uuid =~ m{^[0-9a-f\-]{30,}$}
1763                     or die "doesn't look right - svm:uuid is '$uuid'\n";
1764
1765                 # the '!' is used to mark the repos_root!/relative/path
1766                 $src =~ s{/?!/?}{/};
1767                 $src =~ s{/+$}{}; # no trailing slashes please
1768                 # username is of no interest
1769                 $src =~ s{(^[a-z\+]*://)[^/@]*@}{$1};
1770
1771                 my $replace = $ra->{url};
1772                 $replace .= "/$path" if length $path;
1773
1774                 my $section = "svn-remote.$self->{repo_id}";
1775                 tmp_config("$section.svm-source", $src);
1776                 tmp_config("$section.svm-replace", $replace);
1777                 tmp_config("$section.svm-uuid", $uuid);
1778                 $self->{svm} = {
1779                         source => $src,
1780                         uuid => $uuid,
1781                         replace => $replace
1782                 };
1783         }
1784
1785         my $r = $ra->get_latest_revnum;
1786         my $path = $self->{path};
1787         my %tried;
1788         while (length $path) {
1789                 unless ($tried{"$self->{url}/$path"}) {
1790                         return $ra if $self->read_svm_props($ra, $path, $r);
1791                         $tried{"$self->{url}/$path"} = 1;
1792                 }
1793                 $path =~ s#/?[^/]+$##;
1794         }
1795         die "Path: '$path' should be ''\n" if $path ne '';
1796         return $ra if $self->read_svm_props($ra, $path, $r);
1797         $tried{"$self->{url}/$path"} = 1;
1798
1799         if ($ra->{repos_root} eq $self->{url}) {
1800                 die @err, (map { "  $_\n" } keys %tried), "\n";
1801         }
1802
1803         # nope, make sure we're connected to the repository root:
1804         my $ok;
1805         my @tried_b;
1806         $path = $ra->{svn_path};
1807         $ra = Git::SVN::Ra->new($ra->{repos_root});
1808         while (length $path) {
1809                 unless ($tried{"$ra->{url}/$path"}) {
1810                         $ok = $self->read_svm_props($ra, $path, $r);
1811                         last if $ok;
1812                         $tried{"$ra->{url}/$path"} = 1;
1813                 }
1814                 $path =~ s#/?[^/]+$##;
1815         }
1816         die "Path: '$path' should be ''\n" if $path ne '';
1817         $ok ||= $self->read_svm_props($ra, $path, $r);
1818         $tried{"$ra->{url}/$path"} = 1;
1819         if (!$ok) {
1820                 die @err, (map { "  $_\n" } keys %tried), "\n";
1821         }
1822         Git::SVN::Ra->new($self->{url});
1823 }
1824
1825 sub svnsync {
1826         my ($self) = @_;
1827         return $self->{svnsync} if $self->{svnsync};
1828
1829         if ($self->no_metadata) {
1830                 die "Can't have both 'noMetadata' and ",
1831                     "'useSvnsyncProps' options set!\n";
1832         }
1833         if ($self->rewrite_root) {
1834                 die "Can't have both 'useSvnsyncProps' and 'rewriteRoot' ",
1835                     "options set!\n";
1836         }
1837
1838         my $svnsync;
1839         # see if we have it in our config, first:
1840         eval {
1841                 my $section = "svn-remote.$self->{repo_id}";
1842
1843                 my $url = tmp_config('--get', "$section.svnsync-url");
1844                 ($url) = ($url =~ m{^([a-z\+]+://\S+)$}) or
1845                    die "doesn't look right - svn:sync-from-url is '$url'\n";
1846
1847                 my $uuid = tmp_config('--get', "$section.svnsync-uuid");
1848                 ($uuid) = ($uuid =~ m{^([0-9a-f\-]{30,})$}) or
1849                    die "doesn't look right - svn:sync-from-uuid is '$uuid'\n";
1850
1851                 $svnsync = { url => $url, uuid => $uuid }
1852         };
1853         if ($svnsync && $svnsync->{url} && $svnsync->{uuid}) {
1854                 return $self->{svnsync} = $svnsync;
1855         }
1856
1857         my $err = "useSvnsyncProps set, but failed to read " .
1858                   "svnsync property: svn:sync-from-";
1859         my $rp = $self->ra->rev_proplist(0);
1860
1861         my $url = $rp->{'svn:sync-from-url'} or die $err . "url\n";
1862         ($url) = ($url =~ m{^([a-z\+]+://\S+)$}) or
1863                    die "doesn't look right - svn:sync-from-url is '$url'\n";
1864
1865         my $uuid = $rp->{'svn:sync-from-uuid'} or die $err . "uuid\n";
1866         ($uuid) = ($uuid =~ m{^([0-9a-f\-]{30,})$}) or
1867                    die "doesn't look right - svn:sync-from-uuid is '$uuid'\n";
1868
1869         my $section = "svn-remote.$self->{repo_id}";
1870         tmp_config('--add', "$section.svnsync-uuid", $uuid);
1871         tmp_config('--add', "$section.svnsync-url", $url);
1872         return $self->{svnsync} = { url => $url, uuid => $uuid };
1873 }
1874
1875 # this allows us to memoize our SVN::Ra UUID locally and avoid a
1876 # remote lookup (useful for 'git svn log').
1877 sub ra_uuid {
1878         my ($self) = @_;
1879         unless ($self->{ra_uuid}) {
1880                 my $key = "svn-remote.$self->{repo_id}.uuid";
1881                 my $uuid = eval { tmp_config('--get', $key) };
1882                 if (!$@ && $uuid && $uuid =~ /^([a-f\d\-]{30,})$/) {
1883                         $self->{ra_uuid} = $uuid;
1884                 } else {
1885                         die "ra_uuid called without URL\n" unless $self->{url};
1886                         $self->{ra_uuid} = $self->ra->get_uuid;
1887                         tmp_config('--add', $key, $self->{ra_uuid});
1888                 }
1889         }
1890         $self->{ra_uuid};
1891 }
1892
1893 sub _set_repos_root {
1894         my ($self, $repos_root) = @_;
1895         my $k = "svn-remote.$self->{repo_id}.reposRoot";
1896         $repos_root ||= $self->ra->{repos_root};
1897         tmp_config($k, $repos_root);
1898         $repos_root;
1899 }
1900
1901 sub repos_root {
1902         my ($self) = @_;
1903         my $k = "svn-remote.$self->{repo_id}.reposRoot";
1904         eval { tmp_config('--get', $k) } || $self->_set_repos_root;
1905 }
1906
1907 sub ra {
1908         my ($self) = shift;
1909         my $ra = Git::SVN::Ra->new($self->{url});
1910         $self->_set_repos_root($ra->{repos_root});
1911         if ($self->use_svm_props && !$self->{svm}) {
1912                 if ($self->no_metadata) {
1913                         die "Can't have both 'noMetadata' and ",
1914                             "'useSvmProps' options set!\n";
1915                 } elsif ($self->use_svnsync_props) {
1916                         die "Can't have both 'useSvnsyncProps' and ",
1917                             "'useSvmProps' options set!\n";
1918                 }
1919                 $ra = $self->_set_svm_vars($ra);
1920                 $self->{-want_revprops} = 1;
1921         }
1922         $ra;
1923 }
1924
1925 sub rel_path {
1926         my ($self) = @_;
1927         my $repos_root = $self->ra->{repos_root};
1928         return $self->{path} if ($self->{url} eq $repos_root);
1929         my $url = $self->{url} .
1930                   (length $self->{path} ? "/$self->{path}" : $self->{path});
1931         $url =~ s!^\Q$repos_root\E(?:/+|$)!!g;
1932         $url;
1933 }
1934
1935 # prop_walk(PATH, REV, SUB)
1936 # -------------------------
1937 # Recursively traverse PATH at revision REV and invoke SUB for each
1938 # directory that contains a SVN property.  SUB will be invoked as
1939 # follows:  &SUB(gs, path, props);  where `gs' is this instance of
1940 # Git::SVN, `path' the path to the directory where the properties
1941 # `props' were found.  The `path' will be relative to point of checkout,
1942 # that is, if url://repo/trunk is the current Git branch, and that
1943 # directory contains a sub-directory `d', SUB will be invoked with `/d/'
1944 # as `path' (note the trailing `/').
1945 sub prop_walk {
1946         my ($self, $path, $rev, $sub) = @_;
1947
1948         $path =~ s#^/##;
1949         my ($dirent, undef, $props) = $self->ra->get_dir($path, $rev);
1950         $path =~ s#^/*#/#g;
1951         my $p = $path;
1952         # Strip the irrelevant part of the path.
1953         $p =~ s#^/+\Q$self->{path}\E(/|$)#/#;
1954         # Ensure the path is terminated by a `/'.
1955         $p =~ s#/*$#/#;
1956
1957         # The properties contain all the internal SVN stuff nobody
1958         # (usually) cares about.
1959         my $interesting_props = 0;
1960         foreach (keys %{$props}) {
1961                 # If it doesn't start with `svn:', it must be a
1962                 # user-defined property.
1963                 ++$interesting_props and next if $_ !~ /^svn:/;
1964                 # FIXME: Fragile, if SVN adds new public properties,
1965                 # this needs to be updated.
1966                 ++$interesting_props if /^svn:(?:ignore|keywords|executable
1967                                                  |eol-style|mime-type
1968                                                  |externals|needs-lock)$/x;
1969         }
1970         &$sub($self, $p, $props) if $interesting_props;
1971
1972         foreach (sort keys %$dirent) {
1973                 next if $dirent->{$_}->{kind} != $SVN::Node::dir;
1974                 $self->prop_walk($self->{path} . $p . $_, $rev, $sub);
1975         }
1976 }
1977
1978 sub last_rev { ($_[0]->last_rev_commit)[0] }
1979 sub last_commit { ($_[0]->last_rev_commit)[1] }
1980
1981 # returns the newest SVN revision number and newest commit SHA1
1982 sub last_rev_commit {
1983         my ($self) = @_;
1984         if (defined $self->{last_rev} && defined $self->{last_commit}) {
1985                 return ($self->{last_rev}, $self->{last_commit});
1986         }
1987         my $c = ::verify_ref($self->refname.'^0');
1988         if ($c && !$self->use_svm_props && !$self->no_metadata) {
1989                 my $rev = (::cmt_metadata($c))[1];
1990                 if (defined $rev) {
1991                         ($self->{last_rev}, $self->{last_commit}) = ($rev, $c);
1992                         return ($rev, $c);
1993                 }
1994         }
1995         my $map_path = $self->map_path;
1996         unless (-e $map_path) {
1997                 ($self->{last_rev}, $self->{last_commit}) = (undef, undef);
1998                 return (undef, undef);
1999         }
2000         my ($rev, $commit) = $self->rev_map_max(1);
2001         ($self->{last_rev}, $self->{last_commit}) = ($rev, $commit);
2002         return ($rev, $commit);
2003 }
2004
2005 sub get_fetch_range {
2006         my ($self, $min, $max) = @_;
2007         $max ||= $self->ra->get_latest_revnum;
2008         $min ||= $self->rev_map_max;
2009         (++$min, $max);
2010 }
2011
2012 sub tmp_config {
2013         my (@args) = @_;
2014         my $old_def_config = "$ENV{GIT_DIR}/svn/config";
2015         my $config = "$ENV{GIT_DIR}/svn/.metadata";
2016         if (! -f $config && -f $old_def_config) {
2017                 rename $old_def_config, $config or
2018                        die "Failed rename $old_def_config => $config: $!\n";
2019         }
2020         my $old_config = $ENV{GIT_CONFIG};
2021         $ENV{GIT_CONFIG} = $config;
2022         $@ = undef;
2023         my @ret = eval {
2024                 unless (-f $config) {
2025                         mkfile($config);
2026                         open my $fh, '>', $config or
2027                             die "Can't open $config: $!\n";
2028                         print $fh "; This file is used internally by ",
2029                                   "git-svn\n" or die
2030                                   "Couldn't write to $config: $!\n";
2031                         print $fh "; You should not have to edit it\n" or
2032                               die "Couldn't write to $config: $!\n";
2033                         close $fh or die "Couldn't close $config: $!\n";
2034                 }
2035                 command('config', @args);
2036         };
2037         my $err = $@;
2038         if (defined $old_config) {
2039                 $ENV{GIT_CONFIG} = $old_config;
2040         } else {
2041                 delete $ENV{GIT_CONFIG};
2042         }
2043         die $err if $err;
2044         wantarray ? @ret : $ret[0];
2045 }
2046
2047 sub tmp_index_do {
2048         my ($self, $sub) = @_;
2049         my $old_index = $ENV{GIT_INDEX_FILE};
2050         $ENV{GIT_INDEX_FILE} = $self->{index};
2051         $@ = undef;
2052         my @ret = eval {
2053                 my ($dir, $base) = ($self->{index} =~ m#^(.*?)/?([^/]+)$#);
2054                 mkpath([$dir]) unless -d $dir;
2055                 &$sub;
2056         };
2057         my $err = $@;
2058         if (defined $old_index) {
2059                 $ENV{GIT_INDEX_FILE} = $old_index;
2060         } else {
2061                 delete $ENV{GIT_INDEX_FILE};
2062         }
2063         die $err if $err;
2064         wantarray ? @ret : $ret[0];
2065 }
2066
2067 sub assert_index_clean {
2068         my ($self, $treeish) = @_;
2069
2070         $self->tmp_index_do(sub {
2071                 command_noisy('read-tree', $treeish) unless -e $self->{index};
2072                 my $x = command_oneline('write-tree');
2073                 my ($y) = (command(qw/cat-file commit/, $treeish) =~
2074                            /^tree ($::sha1)/mo);
2075                 return if $y eq $x;
2076
2077                 warn "Index mismatch: $y != $x\nrereading $treeish\n";
2078                 unlink $self->{index} or die "unlink $self->{index}: $!\n";
2079                 command_noisy('read-tree', $treeish);
2080                 $x = command_oneline('write-tree');
2081                 if ($y ne $x) {
2082                         ::fatal "trees ($treeish) $y != $x\n",
2083                                 "Something is seriously wrong...";
2084                 }
2085         });
2086 }
2087
2088 sub get_commit_parents {
2089         my ($self, $log_entry) = @_;
2090         my (%seen, @ret, @tmp);
2091         # legacy support for 'set-tree'; this is only used by set_tree_cb:
2092         if (my $ip = $self->{inject_parents}) {
2093                 if (my $commit = delete $ip->{$log_entry->{revision}}) {
2094                         push @tmp, $commit;
2095                 }
2096         }
2097         if (my $cur = ::verify_ref($self->refname.'^0')) {
2098                 push @tmp, $cur;
2099         }
2100         if (my $ipd = $self->{inject_parents_dcommit}) {
2101                 if (my $commit = delete $ipd->{$log_entry->{revision}}) {
2102                         push @tmp, @$commit;
2103                 }
2104         }
2105         push @tmp, $_ foreach (@{$log_entry->{parents}}, @tmp);
2106         while (my $p = shift @tmp) {
2107                 next if $seen{$p};
2108                 $seen{$p} = 1;
2109                 push @ret, $p;
2110                 # MAXPARENT is defined to 16 in commit-tree.c:
2111                 last if @ret >= 16;
2112         }
2113         if (@tmp) {
2114                 die "r$log_entry->{revision}: No room for parents:\n\t",
2115                     join("\n\t", @tmp), "\n";
2116         }
2117         @ret;
2118 }
2119
2120 sub rewrite_root {
2121         my ($self) = @_;
2122         return $self->{-rewrite_root} if exists $self->{-rewrite_root};
2123         my $k = "svn-remote.$self->{repo_id}.rewriteRoot";
2124         my $rwr = eval { command_oneline(qw/config --get/, $k) };
2125         if ($rwr) {
2126                 $rwr =~ s#/+$##;
2127                 if ($rwr !~ m#^[a-z\+]+://#) {
2128                         die "$rwr is not a valid URL (key: $k)\n";
2129                 }
2130         }
2131         $self->{-rewrite_root} = $rwr;
2132 }
2133
2134 sub metadata_url {
2135         my ($self) = @_;
2136         ($self->rewrite_root || $self->{url}) .
2137            (length $self->{path} ? '/' . $self->{path} : '');
2138 }
2139
2140 sub full_url {
2141         my ($self) = @_;
2142         $self->{url} . (length $self->{path} ? '/' . $self->{path} : '');
2143 }
2144
2145
2146 sub set_commit_header_env {
2147         my ($log_entry) = @_;
2148         my %env;
2149         foreach my $ned (qw/NAME EMAIL DATE/) {
2150                 foreach my $ac (qw/AUTHOR COMMITTER/) {
2151                         $env{"GIT_${ac}_${ned}"} = $ENV{"GIT_${ac}_${ned}"};
2152                 }
2153         }
2154
2155         $ENV{GIT_AUTHOR_NAME} = $log_entry->{name};
2156         $ENV{GIT_AUTHOR_EMAIL} = $log_entry->{email};
2157         $ENV{GIT_AUTHOR_DATE} = $ENV{GIT_COMMITTER_DATE} = $log_entry->{date};
2158
2159         $ENV{GIT_COMMITTER_NAME} = (defined $log_entry->{commit_name})
2160                                                 ? $log_entry->{commit_name}
2161                                                 : $log_entry->{name};
2162         $ENV{GIT_COMMITTER_EMAIL} = (defined $log_entry->{commit_email})
2163                                                 ? $log_entry->{commit_email}
2164                                                 : $log_entry->{email};
2165         \%env;
2166 }
2167
2168 sub restore_commit_header_env {
2169         my ($env) = @_;
2170         foreach my $ned (qw/NAME EMAIL DATE/) {
2171                 foreach my $ac (qw/AUTHOR COMMITTER/) {
2172                         my $k = "GIT_${ac}_${ned}";
2173                         if (defined $env->{$k}) {
2174                                 $ENV{$k} = $env->{$k};
2175                         } else {
2176                                 delete $ENV{$k};
2177                         }
2178                 }
2179         }
2180 }
2181
2182 sub gc {
2183         command_noisy('gc', '--auto');
2184 };
2185
2186 sub do_git_commit {
2187         my ($self, $log_entry) = @_;
2188         my $lr = $self->last_rev;
2189         if (defined $lr && $lr >= $log_entry->{revision}) {
2190                 die "Last fetched revision of ", $self->refname,
2191                     " was r$lr, but we are about to fetch: ",
2192                     "r$log_entry->{revision}!\n";
2193         }
2194         if (my $c = $self->rev_map_get($log_entry->{revision})) {
2195                 croak "$log_entry->{revision} = $c already exists! ",
2196                       "Why are we refetching it?\n";
2197         }
2198         my $old_env = set_commit_header_env($log_entry);
2199         my $tree = $log_entry->{tree};
2200         if (!defined $tree) {
2201                 $tree = $self->tmp_index_do(sub {
2202                                             command_oneline('write-tree') });
2203         }
2204         die "Tree is not a valid sha1: $tree\n" if $tree !~ /^$::sha1$/o;
2205
2206         my @exec = ('git-commit-tree', $tree);
2207         foreach ($self->get_commit_parents($log_entry)) {
2208                 push @exec, '-p', $_;
2209         }
2210         defined(my $pid = open3(my $msg_fh, my $out_fh, '>&STDERR', @exec))
2211                                                                    or croak $!;
2212         print $msg_fh $log_entry->{log} or croak $!;
2213         restore_commit_header_env($old_env);
2214         unless ($self->no_metadata) {
2215                 print $msg_fh "\ngit-svn-id: $log_entry->{metadata}\n"
2216                               or croak $!;
2217         }
2218         $msg_fh->flush == 0 or croak $!;
2219         close $msg_fh or croak $!;
2220         chomp(my $commit = do { local $/; <$out_fh> });
2221         close $out_fh or croak $!;
2222         waitpid $pid, 0;
2223         croak $? if $?;
2224         if ($commit !~ /^$::sha1$/o) {
2225                 die "Failed to commit, invalid sha1: $commit\n";
2226         }
2227
2228         $self->rev_map_set($log_entry->{revision}, $commit, 1);
2229
2230         $self->{last_rev} = $log_entry->{revision};
2231         $self->{last_commit} = $commit;
2232         print "r$log_entry->{revision}";
2233         if (defined $log_entry->{svm_revision}) {
2234                  print " (\@$log_entry->{svm_revision})";
2235                  $self->rev_map_set($log_entry->{svm_revision}, $commit,
2236                                    0, $self->svm_uuid);
2237         }
2238         print " = $commit ($self->{ref_id})\n";
2239         if (--$_gc_nr == 0) {
2240                 $_gc_nr = $_gc_period;
2241                 gc();
2242         }
2243         return $commit;
2244 }
2245
2246 sub match_paths {
2247         my ($self, $paths, $r) = @_;
2248         return 1 if $self->{path} eq '';
2249         if (my $path = $paths->{"/$self->{path}"}) {
2250                 return ($path->{action} eq 'D') ? 0 : 1;
2251         }
2252         $self->{path_regex} ||= qr/^\/\Q$self->{path}\E\//;
2253         if (grep /$self->{path_regex}/, keys %$paths) {
2254                 return 1;
2255         }
2256         my $c = '';
2257         foreach (split m#/#, $self->{path}) {
2258                 $c .= "/$_";
2259                 next unless ($paths->{$c} &&
2260                              ($paths->{$c}->{action} =~ /^[AR]$/));
2261                 if ($self->ra->check_path($self->{path}, $r) ==
2262                     $SVN::Node::dir) {
2263                         return 1;
2264                 }
2265         }
2266         return 0;
2267 }
2268
2269 sub find_parent_branch {
2270         my ($self, $paths, $rev) = @_;
2271         return undef unless $self->follow_parent;
2272         unless (defined $paths) {
2273                 my $err_handler = $SVN::Error::handler;
2274                 $SVN::Error::handler = \&Git::SVN::Ra::skip_unknown_revs;
2275                 $self->ra->get_log([$self->{path}], $rev, $rev, 0, 1, 1, sub {
2276                                    $paths =
2277                                       Git::SVN::Ra::dup_changed_paths($_[0]) });
2278                 $SVN::Error::handler = $err_handler;
2279         }
2280         return undef unless defined $paths;
2281
2282         # look for a parent from another branch:
2283         my @b_path_components = split m#/#, $self->rel_path;
2284         my @a_path_components;
2285         my $i;
2286         while (@b_path_components) {
2287                 $i = $paths->{'/'.join('/', @b_path_components)};
2288                 last if $i && defined $i->{copyfrom_path};
2289                 unshift(@a_path_components, pop(@b_path_components));
2290         }
2291         return undef unless defined $i && defined $i->{copyfrom_path};
2292         my $branch_from = $i->{copyfrom_path};
2293         if (@a_path_components) {
2294                 print STDERR "branch_from: $branch_from => ";
2295                 $branch_from .= '/'.join('/', @a_path_components);
2296                 print STDERR $branch_from, "\n";
2297         }
2298         my $r = $i->{copyfrom_rev};
2299         my $repos_root = $self->ra->{repos_root};
2300         my $url = $self->ra->{url};
2301         my $new_url = $repos_root . $branch_from;
2302         print STDERR  "Found possible branch point: ",
2303                       "$new_url => ", $self->full_url, ", $r\n";
2304         $branch_from =~ s#^/##;
2305         my $gs = Git::SVN->find_by_url($new_url, $repos_root, $branch_from);
2306         unless ($gs) {
2307                 my $ref_id = $self->{ref_id};
2308                 $ref_id =~ s/\@\d+$//;
2309                 $ref_id .= "\@$r";
2310                 # just grow a tail if we're not unique enough :x
2311                 $ref_id .= '-' while find_ref($ref_id);
2312                 print STDERR "Initializing parent: $ref_id\n";
2313                 my ($u, $p, $repo_id) = ($new_url, '', $ref_id);
2314                 if ($u =~ s#^\Q$url\E(/|$)##) {
2315                         $p = $u;
2316                         $u = $url;
2317                         $repo_id = $self->{repo_id};
2318                 }
2319                 $gs = Git::SVN->init($u, $p, $repo_id, $ref_id, 1);
2320         }
2321         my ($r0, $parent) = $gs->find_rev_before($r, 1);
2322         if (!defined $r0 || !defined $parent) {
2323                 my ($base, $head) = parse_revision_argument(0, $r);
2324                 if ($base <= $r) {
2325                         $gs->fetch($base, $r);
2326                 }
2327                 ($r0, $parent) = $gs->last_rev_commit;
2328         }
2329         if (defined $r0 && defined $parent) {
2330                 print STDERR "Found branch parent: ($self->{ref_id}) $parent\n";
2331                 my $ed;
2332                 if ($self->ra->can_do_switch) {
2333                         $self->assert_index_clean($parent);
2334                         print STDERR "Following parent with do_switch\n";
2335                         # do_switch works with svn/trunk >= r22312, but that
2336                         # is not included with SVN 1.4.3 (the latest version
2337                         # at the moment), so we can't rely on it
2338                         $self->{last_commit} = $parent;
2339                         $ed = SVN::Git::Fetcher->new($self);
2340                         $gs->ra->gs_do_switch($r0, $rev, $gs,
2341                                               $self->full_url, $ed)
2342                           or die "SVN connection failed somewhere...\n";
2343                 } elsif ($self->ra->trees_match($new_url, $r0,
2344                                                 $self->full_url, $rev)) {
2345                         print STDERR "Trees match:\n",
2346                                      "  $new_url\@$r0\n",
2347                                      "  ${\$self->full_url}\@$rev\n",
2348                                      "Following parent with no changes\n";
2349                         $self->tmp_index_do(sub {
2350                             command_noisy('read-tree', $parent);
2351                         });
2352                         $self->{last_commit} = $parent;
2353                 } else {
2354                         print STDERR "Following parent with do_update\n";
2355                         $ed = SVN::Git::Fetcher->new($self);
2356                         $self->ra->gs_do_update($rev, $rev, $self, $ed)
2357                           or die "SVN connection failed somewhere...\n";
2358                 }
2359                 print STDERR "Successfully followed parent\n";
2360                 return $self->make_log_entry($rev, [$parent], $ed);
2361         }
2362         return undef;
2363 }
2364
2365 sub do_fetch {
2366         my ($self, $paths, $rev) = @_;
2367         my $ed;
2368         my ($last_rev, @parents);
2369         if (my $lc = $self->last_commit) {
2370                 # we can have a branch that was deleted, then re-added
2371                 # under the same name but copied from another path, in
2372                 # which case we'll have multiple parents (we don't
2373                 # want to break the original ref, nor lose copypath info):
2374                 if (my $log_entry = $self->find_parent_branch($paths, $rev)) {
2375                         push @{$log_entry->{parents}}, $lc;
2376                         return $log_entry;
2377                 }
2378                 $ed = SVN::Git::Fetcher->new($self);
2379                 $last_rev = $self->{last_rev};
2380                 $ed->{c} = $lc;
2381                 @parents = ($lc);
2382         } else {
2383                 $last_rev = $rev;
2384                 if (my $log_entry = $self->find_parent_branch($paths, $rev)) {
2385                         return $log_entry;
2386                 }
2387                 $ed = SVN::Git::Fetcher->new($self);
2388         }
2389         unless ($self->ra->gs_do_update($last_rev, $rev, $self, $ed)) {
2390                 die "SVN connection failed somewhere...\n";
2391         }
2392         $self->make_log_entry($rev, \@parents, $ed);
2393 }
2394
2395 sub get_untracked {
2396         my ($self, $ed) = @_;
2397         my @out;
2398         my $h = $ed->{empty};
2399         foreach (sort keys %$h) {
2400                 my $act = $h->{$_} ? '+empty_dir' : '-empty_dir';
2401                 push @out, "  $act: " . uri_encode($_);
2402                 warn "W: $act: $_\n";
2403         }
2404         foreach my $t (qw/dir_prop file_prop/) {
2405                 $h = $ed->{$t} or next;
2406                 foreach my $path (sort keys %$h) {
2407                         my $ppath = $path eq '' ? '.' : $path;
2408                         foreach my $prop (sort keys %{$h->{$path}}) {
2409                                 next if $SKIP_PROP{$prop};
2410                                 my $v = $h->{$path}->{$prop};
2411                                 my $t_ppath_prop = "$t: " .
2412                                                     uri_encode($ppath) . ' ' .
2413                                                     uri_encode($prop);
2414                                 if (defined $v) {
2415                                         push @out, "  +$t_ppath_prop " .
2416                                                    uri_encode($v);
2417                                 } else {
2418                                         push @out, "  -$t_ppath_prop";
2419                                 }
2420                         }
2421                 }
2422         }
2423         foreach my $t (qw/absent_file absent_directory/) {
2424                 $h = $ed->{$t} or next;
2425                 foreach my $parent (sort keys %$h) {
2426                         foreach my $path (sort @{$h->{$parent}}) {
2427                                 push @out, "  $t: " .
2428                                            uri_encode("$parent/$path");
2429                                 warn "W: $t: $parent/$path ",
2430                                      "Insufficient permissions?\n";
2431                         }
2432                 }
2433         }
2434         \@out;
2435 }
2436
2437 sub parse_svn_date {
2438         my $date = shift || return '+0000 1970-01-01 00:00:00';
2439         my ($Y,$m,$d,$H,$M,$S) = ($date =~ /^(\d{4})\-(\d\d)\-(\d\d)T
2440                                             (\d\d)\:(\d\d)\:(\d\d).\d+Z$/x) or
2441                                          croak "Unable to parse date: $date\n";
2442         "+0000 $Y-$m-$d $H:$M:$S";
2443 }
2444
2445 sub check_author {
2446         my ($author) = @_;
2447         if (!defined $author || length $author == 0) {
2448                 $author = '(no author)';
2449         } elsif (defined $::_authors && ! defined $::users{$author}) {
2450                 die "Author: $author not defined in $::_authors file\n";
2451         }
2452         $author;
2453 }
2454
2455 sub make_log_entry {
2456         my ($self, $rev, $parents, $ed) = @_;
2457         my $untracked = $self->get_untracked($ed);
2458
2459         open my $un, '>>', "$self->{dir}/unhandled.log" or croak $!;
2460         print $un "r$rev\n" or croak $!;
2461         print $un $_, "\n" foreach @$untracked;
2462         my %log_entry = ( parents => $parents || [], revision => $rev,
2463                           log => '');
2464
2465         my $headrev;
2466         my $logged = delete $self->{logged_rev_props};
2467         if (!$logged || $self->{-want_revprops}) {
2468                 my $rp = $self->ra->rev_proplist($rev);
2469                 foreach (sort keys %$rp) {
2470                         my $v = $rp->{$_};
2471                         if (/^svn:(author|date|log)$/) {
2472                                 $log_entry{$1} = $v;
2473                         } elsif ($_ eq 'svm:headrev') {
2474                                 $headrev = $v;
2475                         } else {
2476                                 print $un "  rev_prop: ", uri_encode($_), ' ',
2477                                           uri_encode($v), "\n";
2478                         }
2479                 }
2480         } else {
2481                 map { $log_entry{$_} = $logged->{$_} } keys %$logged;
2482         }
2483         close $un or croak $!;
2484
2485         $log_entry{date} = parse_svn_date($log_entry{date});
2486         $log_entry{log} .= "\n";
2487         my $author = $log_entry{author} = check_author($log_entry{author});
2488         my ($name, $email) = defined $::users{$author} ? @{$::users{$author}}
2489                                                        : ($author, undef);
2490
2491         my ($commit_name, $commit_email) = ($name, $email);
2492         if ($_use_log_author) {
2493                 my $name_field;
2494                 if ($log_entry{log} =~ /From:\s+(.*\S)\s*\n/i) {
2495                         $name_field = $1;
2496                 } elsif ($log_entry{log} =~ /Signed-off-by:\s+(.*\S)\s*\n/i) {
2497                         $name_field = $1;
2498                 }
2499                 if (!defined $name_field) {
2500                         if (!defined $email) {
2501                                 $email = $name;
2502                         }
2503                 } elsif ($name_field =~ /(.*?)\s+<(.*)>/) {
2504                         ($name, $email) = ($1, $2);
2505                 } elsif ($name_field =~ /(.*)@/) {
2506                         ($name, $email) = ($1, $name_field);
2507                 } else {
2508                         ($name, $email) = ($name_field, $name_field);
2509                 }
2510         }
2511         if (defined $headrev && $self->use_svm_props) {
2512                 if ($self->rewrite_root) {
2513                         die "Can't have both 'useSvmProps' and 'rewriteRoot' ",
2514                             "options set!\n";
2515                 }
2516                 my ($uuid, $r) = $headrev =~ m{^([a-f\d\-]{30,}):(\d+)$};
2517                 # we don't want "SVM: initializing mirror for junk" ...
2518                 return undef if $r == 0;
2519                 my $svm = $self->svm;
2520                 if ($uuid ne $svm->{uuid}) {
2521                         die "UUID mismatch on SVM path:\n",
2522                             "expected: $svm->{uuid}\n",
2523                             "     got: $uuid\n";
2524                 }
2525                 my $full_url = $self->full_url;
2526                 $full_url =~ s#^\Q$svm->{replace}\E(/|$)#$svm->{source}$1# or
2527                              die "Failed to replace '$svm->{replace}' with ",
2528                                  "'$svm->{source}' in $full_url\n";
2529                 # throw away username for storing in records
2530                 remove_username($full_url);
2531                 $log_entry{metadata} = "$full_url\@$r $uuid";
2532                 $log_entry{svm_revision} = $r;
2533                 $email ||= "$author\@$uuid";
2534                 $commit_email ||= "$author\@$uuid";
2535         } elsif ($self->use_svnsync_props) {
2536                 my $full_url = $self->svnsync->{url};
2537                 $full_url .= "/$self->{path}" if length $self->{path};
2538                 remove_username($full_url);
2539                 my $uuid = $self->svnsync->{uuid};
2540                 $log_entry{metadata} = "$full_url\@$rev $uuid";
2541                 $email ||= "$author\@$uuid";
2542                 $commit_email ||= "$author\@$uuid";
2543         } else {
2544                 my $url = $self->metadata_url;
2545                 remove_username($url);
2546                 $log_entry{metadata} = "$url\@$rev " .
2547                                        $self->ra->get_uuid;
2548                 $email ||= "$author\@" . $self->ra->get_uuid;
2549                 $commit_email ||= "$author\@" . $self->ra->get_uuid;
2550         }
2551         $log_entry{name} = $name;
2552         $log_entry{email} = $email;
2553         $log_entry{commit_name} = $commit_name;
2554         $log_entry{commit_email} = $commit_email;
2555         \%log_entry;
2556 }
2557
2558 sub fetch {
2559         my ($self, $min_rev, $max_rev, @parents) = @_;
2560         my ($last_rev, $last_commit) = $self->last_rev_commit;
2561         my ($base, $head) = $self->get_fetch_range($min_rev, $max_rev);
2562         $self->ra->gs_fetch_loop_common($base, $head, [$self]);
2563 }
2564
2565 sub set_tree_cb {
2566         my ($self, $log_entry, $tree, $rev, $date, $author) = @_;
2567         $self->{inject_parents} = { $rev => $tree };
2568         $self->fetch(undef, undef);
2569 }
2570
2571 sub set_tree {
2572         my ($self, $tree) = (shift, shift);
2573         my $log_entry = ::get_commit_entry($tree);
2574         unless ($self->{last_rev}) {
2575                 fatal("Must have an existing revision to commit");
2576         }
2577         my %ed_opts = ( r => $self->{last_rev},
2578                         log => $log_entry->{log},
2579                         ra => $self->ra,
2580                         tree_a => $self->{last_commit},
2581                         tree_b => $tree,
2582                         editor_cb => sub {
2583                                $self->set_tree_cb($log_entry, $tree, @_) },
2584                         svn_path => $self->{path} );
2585         if (!SVN::Git::Editor->new(\%ed_opts)->apply_diff) {
2586                 print "No changes\nr$self->{last_rev} = $tree\n";
2587         }
2588 }
2589
2590 sub rebuild_from_rev_db {
2591         my ($self, $path) = @_;
2592         my $r = -1;
2593         open my $fh, '<', $path or croak "open: $!";
2594         binmode $fh or croak "binmode: $!";
2595         while (<$fh>) {
2596                 length($_) == 41 or croak "inconsistent size in ($_) != 41";
2597                 chomp($_);
2598                 ++$r;
2599                 next if $_ eq ('0' x 40);
2600                 $self->rev_map_set($r, $_);
2601                 print "r$r = $_\n";
2602         }
2603         close $fh or croak "close: $!";
2604         unlink $path or croak "unlink: $!";
2605 }
2606
2607 sub rebuild {
2608         my ($self) = @_;
2609         my $map_path = $self->map_path;
2610         return if (-e $map_path && ! -z $map_path);
2611         return unless ::verify_ref($self->refname.'^0');
2612         if ($self->use_svm_props || $self->no_metadata) {
2613                 my $rev_db = $self->rev_db_path;
2614                 $self->rebuild_from_rev_db($rev_db);
2615                 if ($self->use_svm_props) {
2616                         my $svm_rev_db = $self->rev_db_path($self->svm_uuid);
2617                         $self->rebuild_from_rev_db($svm_rev_db);
2618                 }
2619                 $self->unlink_rev_db_symlink;
2620                 return;
2621         }
2622         print "Rebuilding $map_path ...\n";
2623         my ($log, $ctx) =
2624             command_output_pipe(qw/rev-list --pretty=raw --no-color --reverse/,
2625                                 $self->refname, '--');
2626         my $metadata_url = $self->metadata_url;
2627         remove_username($metadata_url);
2628         my $svn_uuid = $self->ra_uuid;
2629         my $c;
2630         while (<$log>) {
2631                 if ( m{^commit ($::sha1)$} ) {
2632                         $c = $1;
2633                         next;
2634                 }
2635                 next unless s{^\s*(git-svn-id:)}{$1};
2636                 my ($url, $rev, $uuid) = ::extract_metadata($_);
2637                 remove_username($url);
2638
2639                 # ignore merges (from set-tree)
2640                 next if (!defined $rev || !$uuid);
2641
2642                 # if we merged or otherwise started elsewhere, this is
2643                 # how we break out of it
2644                 if (($uuid ne $svn_uuid) ||
2645                     ($metadata_url && $url && ($url ne $metadata_url))) {
2646                         next;
2647                 }
2648
2649                 $self->rev_map_set($rev, $c);
2650                 print "r$rev = $c\n";
2651         }
2652         command_close_pipe($log, $ctx);
2653         print "Done rebuilding $map_path\n";
2654         my $rev_db_path = $self->rev_db_path;
2655         if (-f $self->rev_db_path) {
2656                 unlink $self->rev_db_path or croak "unlink: $!";
2657         }
2658         $self->unlink_rev_db_symlink;
2659 }
2660
2661 # rev_map:
2662 # Tie::File seems to be prone to offset errors if revisions get sparse,
2663 # it's not that fast, either.  Tie::File is also not in Perl 5.6.  So
2664 # one of my favorite modules is out :<  Next up would be one of the DBM
2665 # modules, but I'm not sure which is most portable...
2666 #
2667 # This is the replacement for the rev_db format, which was too big
2668 # and inefficient for large repositories with a lot of sparse history
2669 # (mainly tags)
2670 #
2671 # The format is this:
2672 #   - 24 bytes for every record,
2673 #     * 4 bytes for the integer representing an SVN revision number
2674 #     * 20 bytes representing the sha1 of a git commit
2675 #   - No empty padding records like the old format
2676 #     (except the last record, which can be overwritten)
2677 #   - new records are written append-only since SVN revision numbers
2678 #     increase monotonically
2679 #   - lookups on SVN revision number are done via a binary search
2680 #   - Piping the file to xxd -c24 is a good way of dumping it for
2681 #     viewing or editing (piped back through xxd -r), should the need
2682 #     ever arise.
2683 #   - The last record can be padding revision with an all-zero sha1
2684 #     This is used to optimize fetch performance when using multiple
2685 #     "fetch" directives in .git/config
2686 #
2687 # These files are disposable unless noMetadata or useSvmProps is set
2688
2689 sub _rev_map_set {
2690         my ($fh, $rev, $commit) = @_;
2691
2692         binmode $fh or croak "binmode: $!";
2693         my $size = (stat($fh))[7];
2694         ($size % 24) == 0 or croak "inconsistent size: $size";
2695
2696         my $wr_offset = 0;
2697         if ($size > 0) {
2698                 sysseek($fh, -24, SEEK_END) or croak "seek: $!";
2699                 my $read = sysread($fh, my $buf, 24) or croak "read: $!";
2700                 $read == 24 or croak "read only $read bytes (!= 24)";
2701                 my ($last_rev, $last_commit) = unpack(rev_map_fmt, $buf);
2702                 if ($last_commit eq ('0' x40)) {
2703                         if ($size >= 48) {
2704                                 sysseek($fh, -48, SEEK_END) or croak "seek: $!";
2705                                 $read = sysread($fh, $buf, 24) or
2706                                     croak "read: $!";
2707                                 $read == 24 or
2708                                     croak "read only $read bytes (!= 24)";
2709                                 ($last_rev, $last_commit) =
2710                                     unpack(rev_map_fmt, $buf);
2711                                 if ($last_commit eq ('0' x40)) {
2712                                         croak "inconsistent .rev_map\n";
2713                                 }
2714                         }
2715                         if ($last_rev >= $rev) {
2716                                 croak "last_rev is higher!: $last_rev >= $rev";
2717                         }
2718                         $wr_offset = -24;
2719                 }
2720         }
2721         sysseek($fh, $wr_offset, SEEK_END) or croak "seek: $!";
2722         syswrite($fh, pack(rev_map_fmt, $rev, $commit), 24) == 24 or
2723           croak "write: $!";
2724 }
2725
2726 sub mkfile {
2727         my ($path) = @_;
2728         unless (-e $path) {
2729                 my ($dir, $base) = ($path =~ m#^(.*?)/?([^/]+)$#);
2730                 mkpath([$dir]) unless -d $dir;
2731                 open my $fh, '>>', $path or die "Couldn't create $path: $!\n";
2732                 close $fh or die "Couldn't close (create) $path: $!\n";
2733         }
2734 }
2735
2736 sub rev_map_set {
2737         my ($self, $rev, $commit, $update_ref, $uuid) = @_;
2738         length $commit == 40 or die "arg3 must be a full SHA1 hexsum\n";
2739         my $db = $self->map_path($uuid);
2740         my $db_lock = "$db.lock";
2741         my $sig;
2742         if ($update_ref) {
2743                 $SIG{INT} = $SIG{HUP} = $SIG{TERM} = $SIG{ALRM} = $SIG{PIPE} =
2744                             $SIG{USR1} = $SIG{USR2} = sub { $sig = $_[0] };
2745         }
2746         mkfile($db);
2747
2748         $LOCKFILES{$db_lock} = 1;
2749         my $sync;
2750         # both of these options make our .rev_db file very, very important
2751         # and we can't afford to lose it because rebuild() won't work
2752         if ($self->use_svm_props || $self->no_metadata) {
2753                 $sync = 1;
2754                 copy($db, $db_lock) or die "rev_map_set(@_): ",
2755                                            "Failed to copy: ",
2756                                            "$db => $db_lock ($!)\n";
2757         } else {
2758                 rename $db, $db_lock or die "rev_map_set(@_): ",
2759                                             "Failed to rename: ",
2760                                             "$db => $db_lock ($!)\n";
2761         }
2762
2763         sysopen(my $fh, $db_lock, O_RDWR | O_CREAT)
2764              or croak "Couldn't open $db_lock: $!\n";
2765         _rev_map_set($fh, $rev, $commit);
2766         if ($sync) {
2767                 $fh->flush or die "Couldn't flush $db_lock: $!\n";
2768                 $fh->sync or die "Couldn't sync $db_lock: $!\n";
2769         }
2770         close $fh or croak $!;
2771         if ($update_ref) {
2772                 $_head = $self;
2773                 command_noisy('update-ref', '-m', "r$rev",
2774                               $self->refname, $commit);
2775         }
2776         rename $db_lock, $db or die "rev_map_set(@_): ", "Failed to rename: ",
2777                                     "$db_lock => $db ($!)\n";
2778         delete $LOCKFILES{$db_lock};
2779         if ($update_ref) {
2780                 $SIG{INT} = $SIG{HUP} = $SIG{TERM} = $SIG{ALRM} = $SIG{PIPE} =
2781                             $SIG{USR1} = $SIG{USR2} = 'DEFAULT';
2782                 kill $sig, $$ if defined $sig;
2783         }
2784 }
2785
2786 # If want_commit, this will return an array of (rev, commit) where
2787 # commit _must_ be a valid commit in the archive.
2788 # Otherwise, it'll return the max revision (whether or not the
2789 # commit is valid or just a 0x40 placeholder).
2790 sub rev_map_max {
2791         my ($self, $want_commit) = @_;
2792         $self->rebuild;
2793         my $map_path = $self->map_path;
2794         stat $map_path or return $want_commit ? (0, undef) : 0;
2795         sysopen(my $fh, $map_path, O_RDONLY) or croak "open: $!";
2796         binmode $fh or croak "binmode: $!";
2797         my $size = (stat($fh))[7];
2798         ($size % 24) == 0 or croak "inconsistent size: $size";
2799
2800         if ($size == 0) {
2801                 close $fh or croak "close: $!";
2802                 return $want_commit ? (0, undef) : 0;
2803         }
2804
2805         sysseek($fh, -24, SEEK_END) or croak "seek: $!";
2806         sysread($fh, my $buf, 24) == 24 or croak "read: $!";
2807         my ($r, $c) = unpack(rev_map_fmt, $buf);
2808         if ($want_commit && $c eq ('0' x40)) {
2809                 if ($size < 48) {
2810                         return $want_commit ? (0, undef) : 0;
2811                 }
2812                 sysseek($fh, -48, SEEK_END) or croak "seek: $!";
2813                 sysread($fh, $buf, 24) == 24 or croak "read: $!";
2814                 ($r, $c) = unpack(rev_map_fmt, $buf);
2815                 if ($c eq ('0'x40)) {
2816                         croak "Penultimate record is all-zeroes in $map_path";
2817                 }
2818         }
2819         close $fh or croak "close: $!";
2820         $want_commit ? ($r, $c) : $r;
2821 }
2822
2823 sub rev_map_get {
2824         my ($self, $rev, $uuid) = @_;
2825         my $map_path = $self->map_path($uuid);
2826         return undef unless -e $map_path;
2827
2828         sysopen(my $fh, $map_path, O_RDONLY) or croak "open: $!";
2829         binmode $fh or croak "binmode: $!";
2830         my $size = (stat($fh))[7];
2831         ($size % 24) == 0 or croak "inconsistent size: $size";
2832
2833         if ($size == 0) {
2834                 close $fh or croak "close: $fh";
2835                 return undef;
2836         }
2837
2838         my ($l, $u) = (0, $size - 24);
2839         my ($r, $c, $buf);
2840
2841         while ($l <= $u) {
2842                 my $i = int(($l/24 + $u/24) / 2) * 24;
2843                 sysseek($fh, $i, SEEK_SET) or croak "seek: $!";
2844                 sysread($fh, my $buf, 24) == 24 or croak "read: $!";
2845                 my ($r, $c) = unpack('NH40', $buf);
2846
2847                 if ($r < $rev) {
2848                         $l = $i + 24;
2849                 } elsif ($r > $rev) {
2850                         $u = $i - 24;
2851                 } else { # $r == $rev
2852                         close($fh) or croak "close: $!";
2853                         return $c eq ('0' x 40) ? undef : $c;
2854                 }
2855         }
2856         close($fh) or croak "close: $!";
2857         undef;
2858 }
2859
2860 # Finds the first svn revision that exists on (if $eq_ok is true) or
2861 # before $rev for the current branch.  It will not search any lower
2862 # than $min_rev.  Returns the git commit hash and svn revision number
2863 # if found, else (undef, undef).
2864 sub find_rev_before {
2865         my ($self, $rev, $eq_ok, $min_rev) = @_;
2866         --$rev unless $eq_ok;
2867         $min_rev ||= 1;
2868         while ($rev >= $min_rev) {
2869                 if (my $c = $self->rev_map_get($rev)) {
2870                         return ($rev, $c);
2871                 }
2872                 --$rev;
2873         }
2874         return (undef, undef);
2875 }
2876
2877 # Finds the first svn revision that exists on (if $eq_ok is true) or
2878 # after $rev for the current branch.  It will not search any higher
2879 # than $max_rev.  Returns the git commit hash and svn revision number
2880 # if found, else (undef, undef).
2881 sub find_rev_after {
2882         my ($self, $rev, $eq_ok, $max_rev) = @_;
2883         ++$rev unless $eq_ok;
2884         $max_rev ||= $self->rev_map_max;
2885         while ($rev <= $max_rev) {
2886                 if (my $c = $self->rev_map_get($rev)) {
2887                         return ($rev, $c);
2888                 }
2889                 ++$rev;
2890         }
2891         return (undef, undef);
2892 }
2893
2894 sub _new {
2895         my ($class, $repo_id, $ref_id, $path) = @_;
2896         unless (defined $repo_id && length $repo_id) {
2897                 $repo_id = $Git::SVN::default_repo_id;
2898         }
2899         unless (defined $ref_id && length $ref_id) {
2900                 $_[2] = $ref_id = $Git::SVN::default_ref_id;
2901         }
2902         $_[1] = $repo_id;
2903         my $dir = "$ENV{GIT_DIR}/svn/$ref_id";
2904         $_[3] = $path = '' unless (defined $path);
2905         mkpath(["$ENV{GIT_DIR}/svn"]);
2906         bless {
2907                 ref_id => $ref_id, dir => $dir, index => "$dir/index",
2908                 path => $path, config => "$ENV{GIT_DIR}/svn/config",
2909                 map_root => "$dir/.rev_map", repo_id => $repo_id }, $class;
2910 }
2911
2912 # for read-only access of old .rev_db formats
2913 sub unlink_rev_db_symlink {
2914         my ($self) = @_;
2915         my $link = $self->rev_db_path;
2916         $link =~ s/\.[\w-]+$// or croak "missing UUID at the end of $link";
2917         if (-l $link) {
2918                 unlink $link or croak "unlink: $link failed!";
2919         }
2920 }
2921
2922 sub rev_db_path {
2923         my ($self, $uuid) = @_;
2924         my $db_path = $self->map_path($uuid);
2925         $db_path =~ s{/\.rev_map\.}{/\.rev_db\.}
2926             or croak "map_path: $db_path does not contain '/.rev_map.' !";
2927         $db_path;
2928 }
2929
2930 # the new replacement for .rev_db
2931 sub map_path {
2932         my ($self, $uuid) = @_;
2933         $uuid ||= $self->ra_uuid;
2934         "$self->{map_root}.$uuid";
2935 }
2936
2937 sub uri_encode {
2938         my ($f) = @_;
2939         $f =~ s#([^a-zA-Z0-9\*!\:_\./\-])#uc sprintf("%%%02x",ord($1))#eg;
2940         $f
2941 }
2942
2943 sub remove_username {
2944         $_[0] =~ s{^([^:]*://)[^@]+@}{$1};
2945 }
2946
2947 package Git::SVN::Prompt;
2948 use strict;
2949 use warnings;
2950 require SVN::Core;
2951 use vars qw/$_no_auth_cache $_username/;
2952
2953 sub simple {
2954         my ($cred, $realm, $default_username, $may_save, $pool) = @_;
2955         $may_save = undef if $_no_auth_cache;
2956         $default_username = $_username if defined $_username;
2957         if (defined $default_username && length $default_username) {
2958                 if (defined $realm && length $realm) {
2959                         print STDERR "Authentication realm: $realm\n";
2960                         STDERR->flush;
2961                 }
2962                 $cred->username($default_username);
2963         } else {
2964                 username($cred, $realm, $may_save, $pool);
2965         }
2966         $cred->password(_read_password("Password for '" .
2967                                        $cred->username . "': ", $realm));
2968         $cred->may_save($may_save);
2969         $SVN::_Core::SVN_NO_ERROR;
2970 }
2971
2972 sub ssl_server_trust {
2973         my ($cred, $realm, $failures, $cert_info, $may_save, $pool) = @_;
2974         $may_save = undef if $_no_auth_cache;
2975         print STDERR "Error validating server certificate for '$realm':\n";
2976         {
2977                 no warnings 'once';
2978                 # All variables SVN::Auth::SSL::* are used only once,
2979                 # so we're shutting up Perl warnings about this.
2980                 if ($failures & $SVN::Auth::SSL::UNKNOWNCA) {
2981                         print STDERR " - The certificate is not issued ",
2982                             "by a trusted authority. Use the\n",
2983                             "   fingerprint to validate ",
2984                             "the certificate manually!\n";
2985                 }
2986                 if ($failures & $SVN::Auth::SSL::CNMISMATCH) {
2987                         print STDERR " - The certificate hostname ",
2988                             "does not match.\n";
2989                 }
2990                 if ($failures & $SVN::Auth::SSL::NOTYETVALID) {
2991                         print STDERR " - The certificate is not yet valid.\n";
2992                 }
2993                 if ($failures & $SVN::Auth::SSL::EXPIRED) {
2994                         print STDERR " - The certificate has expired.\n";
2995                 }
2996                 if ($failures & $SVN::Auth::SSL::OTHER) {
2997                         print STDERR " - The certificate has ",
2998                             "an unknown error.\n";
2999                 }
3000         } # no warnings 'once'
3001         printf STDERR
3002                 "Certificate information:\n".
3003                 " - Hostname: %s\n".
3004                 " - Valid: from %s until %s\n".
3005                 " - Issuer: %s\n".
3006                 " - Fingerprint: %s\n",
3007                 map $cert_info->$_, qw(hostname valid_from valid_until
3008                                        issuer_dname fingerprint);
3009         my $choice;
3010 prompt:
3011         print STDERR $may_save ?
3012               "(R)eject, accept (t)emporarily or accept (p)ermanently? " :
3013               "(R)eject or accept (t)emporarily? ";
3014         STDERR->flush;
3015         $choice = lc(substr(<STDIN> || 'R', 0, 1));
3016         if ($choice =~ /^t$/i) {
3017                 $cred->may_save(undef);
3018         } elsif ($choice =~ /^r$/i) {
3019                 return -1;
3020         } elsif ($may_save && $choice =~ /^p$/i) {
3021                 $cred->may_save($may_save);
3022         } else {
3023                 goto prompt;
3024         }
3025         $cred->accepted_failures($failures);
3026         $SVN::_Core::SVN_NO_ERROR;
3027 }
3028
3029 sub ssl_client_cert {
3030         my ($cred, $realm, $may_save, $pool) = @_;
3031         $may_save = undef if $_no_auth_cache;
3032         print STDERR "Client certificate filename: ";
3033         STDERR->flush;
3034         chomp(my $filename = <STDIN>);
3035         $cred->cert_file($filename);
3036         $cred->may_save($may_save);
3037         $SVN::_Core::SVN_NO_ERROR;
3038 }
3039
3040 sub ssl_client_cert_pw {
3041         my ($cred, $realm, $may_save, $pool) = @_;
3042         $may_save = undef if $_no_auth_cache;
3043         $cred->password(_read_password("Password: ", $realm));
3044         $cred->may_save($may_save);
3045         $SVN::_Core::SVN_NO_ERROR;
3046 }
3047
3048 sub username {
3049         my ($cred, $realm, $may_save, $pool) = @_;
3050         $may_save = undef if $_no_auth_cache;
3051         if (defined $realm && length $realm) {
3052                 print STDERR "Authentication realm: $realm\n";
3053         }
3054         my $username;
3055         if (defined $_username) {
3056                 $username = $_username;
3057         } else {
3058                 print STDERR "Username: ";
3059                 STDERR->flush;
3060                 chomp($username = <STDIN>);
3061         }
3062         $cred->username($username);
3063         $cred->may_save($may_save);
3064         $SVN::_Core::SVN_NO_ERROR;
3065 }
3066
3067 sub _read_password {
3068         my ($prompt, $realm) = @_;
3069         print STDERR $prompt;
3070         STDERR->flush;
3071         require Term::ReadKey;
3072         Term::ReadKey::ReadMode('noecho');
3073         my $password = '';
3074         while (defined(my $key = Term::ReadKey::ReadKey(0))) {
3075                 last if $key =~ /[\012\015]/; # \n\r
3076                 $password .= $key;
3077         }
3078         Term::ReadKey::ReadMode('restore');
3079         print STDERR "\n";
3080         STDERR->flush;
3081         $password;
3082 }
3083
3084 package SVN::Git::Fetcher;
3085 use vars qw/@ISA/;
3086 use strict;
3087 use warnings;
3088 use Carp qw/croak/;
3089 use File::Temp qw/tempfile/;
3090 use IO::File qw//;
3091
3092 # file baton members: path, mode_a, mode_b, pool, fh, blob, base
3093 sub new {
3094         my ($class, $git_svn) = @_;
3095         my $self = SVN::Delta::Editor->new;
3096         bless $self, $class;
3097         $self->{c} = $git_svn->{last_commit} if exists $git_svn->{last_commit};
3098         $self->{empty} = {};
3099         $self->{dir_prop} = {};
3100         $self->{file_prop} = {};
3101         $self->{absent_dir} = {};
3102         $self->{absent_file} = {};
3103         $self->{gii} = $git_svn->tmp_index_do(sub { Git::IndexInfo->new });
3104         $self;
3105 }
3106
3107 sub set_path_strip {
3108         my ($self, $path) = @_;
3109         $self->{path_strip} = qr/^\Q$path\E(\/|$)/ if length $path;
3110 }
3111
3112 sub open_root {
3113         { path => '' };
3114 }
3115
3116 sub open_directory {
3117         my ($self, $path, $pb, $rev) = @_;
3118         { path => $path };
3119 }
3120
3121 sub git_path {
3122         my ($self, $path) = @_;
3123         if ($self->{path_strip}) {
3124                 $path =~ s!$self->{path_strip}!! or
3125                   die "Failed to strip path '$path' ($self->{path_strip})\n";
3126         }
3127         $path;
3128 }
3129
3130 sub delete_entry {
3131         my ($self, $path, $rev, $pb) = @_;
3132
3133         my $gpath = $self->git_path($path);
3134         return undef if ($gpath eq '');
3135
3136         # remove entire directories.
3137         if (command('ls-tree', $self->{c}, '--', $gpath) =~ /^040000 tree/) {
3138                 my ($ls, $ctx) = command_output_pipe(qw/ls-tree
3139                                                      -r --name-only -z/,
3140                                                      $self->{c}, '--', $gpath);
3141                 local $/ = "\0";
3142                 while (<$ls>) {
3143                         chomp;
3144                         $self->{gii}->remove($_);
3145                         print "\tD\t$_\n" unless $::_q;
3146                 }
3147                 print "\tD\t$gpath/\n" unless $::_q;
3148                 command_close_pipe($ls, $ctx);
3149                 $self->{empty}->{$path} = 0
3150         } else {
3151                 $self->{gii}->remove($gpath);
3152                 print "\tD\t$gpath\n" unless $::_q;
3153         }
3154         undef;
3155 }
3156
3157 sub open_file {
3158         my ($self, $path, $pb, $rev) = @_;
3159         my $gpath = $self->git_path($path);
3160         my ($mode, $blob) = (command('ls-tree', $self->{c}, '--', $gpath)
3161                              =~ /^(\d{6}) blob ([a-f\d]{40})\t/);
3162         unless (defined $mode && defined $blob) {
3163                 die "$path was not found in commit $self->{c} (r$rev)\n";
3164         }
3165         { path => $path, mode_a => $mode, mode_b => $mode, blob => $blob,
3166           pool => SVN::Pool->new, action => 'M' };
3167 }
3168
3169 sub add_file {
3170         my ($self, $path, $pb, $cp_path, $cp_rev) = @_;
3171         my ($dir, $file) = ($path =~ m#^(.*?)/?([^/]+)$#);
3172         delete $self->{empty}->{$dir};
3173         { path => $path, mode_a => 100644, mode_b => 100644,
3174           pool => SVN::Pool->new, action => 'A' };
3175 }
3176
3177 sub add_directory {
3178         my ($self, $path, $cp_path, $cp_rev) = @_;
3179         my $gpath = $self->git_path($path);
3180         if ($gpath eq '') {
3181                 my ($ls, $ctx) = command_output_pipe(qw/ls-tree
3182                                                      -r --name-only -z/,
3183                                                      $self->{c});
3184                 local $/ = "\0";
3185                 while (<$ls>) {
3186                         chomp;
3187                         $self->{gii}->remove($_);
3188                         print "\tD\t$_\n" unless $::_q;
3189                 }
3190                 command_close_pipe($ls, $ctx);
3191                 $self->{empty}->{$path} = 0;
3192         }
3193         my ($dir, $file) = ($path =~ m#^(.*?)/?([^/]+)$#);
3194         delete $self->{empty}->{$dir};
3195         $self->{empty}->{$path} = 1;
3196         { path => $path };
3197 }
3198
3199 sub change_dir_prop {
3200         my ($self, $db, $prop, $value) = @_;
3201         $self->{dir_prop}->{$db->{path}} ||= {};
3202         $self->{dir_prop}->{$db->{path}}->{$prop} = $value;
3203         undef;
3204 }
3205
3206 sub absent_directory {
3207         my ($self, $path, $pb) = @_;
3208         $self->{absent_dir}->{$pb->{path}} ||= [];
3209         push @{$self->{absent_dir}->{$pb->{path}}}, $path;
3210         undef;
3211 }
3212
3213 sub absent_file {
3214         my ($self, $path, $pb) = @_;
3215         $self->{absent_file}->{$pb->{path}} ||= [];
3216         push @{$self->{absent_file}->{$pb->{path}}}, $path;
3217         undef;
3218 }
3219
3220 sub change_file_prop {
3221         my ($self, $fb, $prop, $value) = @_;
3222         if ($prop eq 'svn:executable') {
3223                 if ($fb->{mode_b} != 120000) {
3224                         $fb->{mode_b} = defined $value ? 100755 : 100644;
3225                 }
3226         } elsif ($prop eq 'svn:special') {
3227                 $fb->{mode_b} = defined $value ? 120000 : 100644;
3228         } else {
3229                 $self->{file_prop}->{$fb->{path}} ||= {};
3230                 $self->{file_prop}->{$fb->{path}}->{$prop} = $value;
3231         }
3232         undef;
3233 }
3234
3235 sub apply_textdelta {
3236         my ($self, $fb, $exp) = @_;
3237         my $fh = Git::temp_acquire('svn_delta');
3238         # $fh gets auto-closed() by SVN::TxDelta::apply(),
3239         # (but $base does not,) so dup() it for reading in close_file
3240         open my $dup, '<&', $fh or croak $!;
3241         my $base = Git::temp_acquire('git_blob');
3242         if ($fb->{blob}) {
3243                 print $base 'link ' if ($fb->{mode_a} == 120000);
3244                 my $size = $::_repository->cat_blob($fb->{blob}, $base);
3245                 die "Failed to read object $fb->{blob}" if ($size < 0);
3246
3247                 if (defined $exp) {
3248                         seek $base, 0, 0 or croak $!;
3249                         my $got = ::md5sum($base);
3250                         die "Checksum mismatch: $fb->{path} $fb->{blob}\n",
3251                             "expected: $exp\n",
3252                             "     got: $got\n" if ($got ne $exp);
3253                 }
3254         }
3255         seek $base, 0, 0 or croak $!;
3256         $fb->{fh} = $fh;
3257         $fb->{base} = $base;
3258         [ SVN::TxDelta::apply($base, $dup, undef, $fb->{path}, $fb->{pool}) ];
3259 }
3260
3261 sub close_file {
3262         my ($self, $fb, $exp) = @_;
3263         my $hash;
3264         my $path = $self->git_path($fb->{path});
3265         if (my $fh = $fb->{fh}) {
3266                 if (defined $exp) {
3267                         seek($fh, 0, 0) or croak $!;
3268                         my $got = ::md5sum($fh);
3269                         if ($got ne $exp) {
3270                                 die "Checksum mismatch: $path\n",
3271                                     "expected: $exp\n    got: $got\n";
3272                         }
3273                 }
3274                 if ($fb->{mode_b} == 120000) {
3275                         sysseek($fh, 0, 0) or croak $!;
3276                         sysread($fh, my $buf, 5) == 5 or croak $!;
3277
3278                         unless ($buf eq 'link ') {
3279                                 warn "$path has mode 120000",
3280                                                 " but is not a link\n";
3281                         } else {
3282                                 my $tmp_fh = Git::temp_acquire('svn_hash');
3283                                 my $res;
3284                                 while ($res = sysread($fh, my $str, 1024)) {
3285                                         my $out = syswrite($tmp_fh, $str, $res);
3286                                         defined($out) && $out == $res
3287                                                 or croak("write ",
3288                                                         $tmp_fh->filename,
3289                                                         ": $!\n");
3290                                 }
3291                                 defined $res or croak $!;
3292
3293                                 ($fh, $tmp_fh) = ($tmp_fh, $fh);
3294                                 Git::temp_release($tmp_fh, 1);
3295                         }
3296                 }
3297
3298                 $hash = $::_repository->hash_and_insert_object(
3299                                 $fh->filename);
3300                 $hash =~ /^[a-f\d]{40}$/ or die "not a sha1: $hash\n";
3301
3302                 Git::temp_release($fb->{base}, 1);
3303                 Git::temp_release($fh, 1);
3304         } else {
3305                 $hash = $fb->{blob} or die "no blob information\n";
3306         }
3307         $fb->{pool}->clear;
3308         $self->{gii}->update($fb->{mode_b}, $hash, $path) or croak $!;
3309         print "\t$fb->{action}\t$path\n" if $fb->{action} && ! $::_q;
3310         undef;
3311 }
3312
3313 sub abort_edit {
3314         my $self = shift;
3315         $self->{nr} = $self->{gii}->{nr};
3316         delete $self->{gii};
3317         $self->SUPER::abort_edit(@_);
3318 }
3319
3320 sub close_edit {
3321         my $self = shift;
3322         $self->{git_commit_ok} = 1;
3323         $self->{nr} = $self->{gii}->{nr};
3324         delete $self->{gii};
3325         $self->SUPER::close_edit(@_);
3326 }
3327
3328 package SVN::Git::Editor;
3329 use vars qw/@ISA $_rmdir $_cp_similarity $_find_copies_harder $_rename_limit/;
3330 use strict;
3331 use warnings;
3332 use Carp qw/croak/;
3333 use IO::File;
3334
3335 sub new {
3336         my ($class, $opts) = @_;
3337         foreach (qw/svn_path r ra tree_a tree_b log editor_cb/) {
3338                 die "$_ required!\n" unless (defined $opts->{$_});
3339         }
3340
3341         my $pool = SVN::Pool->new;
3342         my $mods = generate_diff($opts->{tree_a}, $opts->{tree_b});
3343         my $types = check_diff_paths($opts->{ra}, $opts->{svn_path},
3344                                      $opts->{r}, $mods);
3345
3346         # $opts->{ra} functions should not be used after this:
3347         my @ce  = $opts->{ra}->get_commit_editor($opts->{log},
3348                                                 $opts->{editor_cb}, $pool);
3349         my $self = SVN::Delta::Editor->new(@ce, $pool);
3350         bless $self, $class;
3351         foreach (qw/svn_path r tree_a tree_b/) {
3352                 $self->{$_} = $opts->{$_};
3353         }
3354         $self->{url} = $opts->{ra}->{url};
3355         $self->{mods} = $mods;
3356         $self->{types} = $types;
3357         $self->{pool} = $pool;
3358         $self->{bat} = { '' => $self->open_root($self->{r}, $self->{pool}) };
3359         $self->{rm} = { };
3360         $self->{path_prefix} = length $self->{svn_path} ?
3361                                "$self->{svn_path}/" : '';
3362         $self->{config} = $opts->{config};
3363         return $self;
3364 }
3365
3366 sub generate_diff {
3367         my ($tree_a, $tree_b) = @_;
3368         my @diff_tree = qw(diff-tree -z -r);
3369         if ($_cp_similarity) {
3370                 push @diff_tree, "-C$_cp_similarity";
3371         } else {
3372                 push @diff_tree, '-C';
3373         }
3374         push @diff_tree, '--find-copies-harder' if $_find_copies_harder;
3375         push @diff_tree, "-l$_rename_limit" if defined $_rename_limit;
3376         push @diff_tree, $tree_a, $tree_b;
3377         my ($diff_fh, $ctx) = command_output_pipe(@diff_tree);
3378         local $/ = "\0";
3379         my $state = 'meta';
3380         my @mods;
3381         while (<$diff_fh>) {
3382                 chomp $_; # this gets rid of the trailing "\0"
3383                 if ($state eq 'meta' && /^:(\d{6})\s(\d{6})\s
3384                                         ($::sha1)\s($::sha1)\s
3385                                         ([MTCRAD])\d*$/xo) {
3386                         push @mods, {   mode_a => $1, mode_b => $2,
3387                                         sha1_a => $3, sha1_b => $4,
3388                                         chg => $5 };
3389                         if ($5 =~ /^(?:C|R)$/) {
3390                                 $state = 'file_a';
3391                         } else {
3392                                 $state = 'file_b';
3393                         }
3394                 } elsif ($state eq 'file_a') {
3395                         my $x = $mods[$#mods] or croak "Empty array\n";
3396                         if ($x->{chg} !~ /^(?:C|R)$/) {
3397                                 croak "Error parsing $_, $x->{chg}\n";
3398                         }
3399                         $x->{file_a} = $_;
3400                         $state = 'file_b';
3401                 } elsif ($state eq 'file_b') {
3402                         my $x = $mods[$#mods] or croak "Empty array\n";
3403                         if (exists $x->{file_a} && $x->{chg} !~ /^(?:C|R)$/) {
3404                                 croak "Error parsing $_, $x->{chg}\n";
3405                         }
3406                         if (!exists $x->{file_a} && $x->{chg} =~ /^(?:C|R)$/) {
3407                                 croak "Error parsing $_, $x->{chg}\n";
3408                         }
3409                         $x->{file_b} = $_;
3410                         $state = 'meta';
3411                 } else {
3412                         croak "Error parsing $_\n";
3413                 }
3414         }
3415         command_close_pipe($diff_fh, $ctx);
3416         \@mods;
3417 }
3418
3419 sub check_diff_paths {
3420         my ($ra, $pfx, $rev, $mods) = @_;
3421         my %types;
3422         $pfx .= '/' if length $pfx;
3423
3424         sub type_diff_paths {
3425                 my ($ra, $types, $path, $rev) = @_;
3426                 my @p = split m#/+#, $path;
3427                 my $c = shift @p;
3428                 unless (defined $types->{$c}) {
3429                         $types->{$c} = $ra->check_path($c, $rev);
3430                 }
3431                 while (@p) {
3432                         $c .= '/' . shift @p;
3433                         next if defined $types->{$c};
3434                         $types->{$c} = $ra->check_path($c, $rev);
3435                 }
3436         }
3437
3438         foreach my $m (@$mods) {
3439                 foreach my $f (qw/file_a file_b/) {
3440                         next unless defined $m->{$f};
3441                         my ($dir) = ($m->{$f} =~ m#^(.*?)/?(?:[^/]+)$#);
3442                         if (length $pfx.$dir && ! defined $types{$dir}) {
3443                                 type_diff_paths($ra, \%types, $pfx.$dir, $rev);
3444                         }
3445                 }
3446         }
3447         \%types;
3448 }
3449
3450 sub split_path {
3451         return ($_[0] =~ m#^(.*?)/?([^/]+)$#);
3452 }
3453
3454 sub repo_path {
3455         my ($self, $path) = @_;
3456         $self->{path_prefix}.(defined $path ? $path : '');
3457 }
3458
3459 sub url_path {
3460         my ($self, $path) = @_;
3461         if ($self->{url} =~ m#^https?://#) {
3462                 $path =~ s/([^a-zA-Z0-9_.-])/uc sprintf("%%%02x",ord($1))/eg;
3463         }
3464         $self->{url} . '/' . $self->repo_path($path);
3465 }
3466
3467 sub rmdirs {
3468         my ($self) = @_;
3469         my $rm = $self->{rm};
3470         delete $rm->{''}; # we never delete the url we're tracking
3471         return unless %$rm;
3472
3473         foreach (keys %$rm) {
3474                 my @d = split m#/#, $_;
3475                 my $c = shift @d;
3476                 $rm->{$c} = 1;
3477                 while (@d) {
3478                         $c .= '/' . shift @d;
3479                         $rm->{$c} = 1;
3480                 }
3481         }
3482         delete $rm->{$self->{svn_path}};
3483         delete $rm->{''}; # we never delete the url we're tracking
3484         return unless %$rm;
3485
3486         my ($fh, $ctx) = command_output_pipe(qw/ls-tree --name-only -r -z/,
3487                                              $self->{tree_b});
3488         local $/ = "\0";
3489         while (<$fh>) {
3490                 chomp;
3491                 my @dn = split m#/#, $_;
3492                 while (pop @dn) {
3493                         delete $rm->{join '/', @dn};
3494                 }
3495                 unless (%$rm) {
3496                         close $fh;
3497                         return;
3498                 }
3499         }
3500         command_close_pipe($fh, $ctx);
3501
3502         my ($r, $p, $bat) = ($self->{r}, $self->{pool}, $self->{bat});
3503         foreach my $d (sort { $b =~ tr#/#/# <=> $a =~ tr#/#/# } keys %$rm) {
3504                 $self->close_directory($bat->{$d}, $p);
3505                 my ($dn) = ($d =~ m#^(.*?)/?(?:[^/]+)$#);
3506                 print "\tD+\t$d/\n" unless $::_q;
3507                 $self->SUPER::delete_entry($d, $r, $bat->{$dn}, $p);
3508                 delete $bat->{$d};
3509         }
3510 }
3511
3512 sub open_or_add_dir {
3513         my ($self, $full_path, $baton) = @_;
3514         my $t = $self->{types}->{$full_path};
3515         if (!defined $t) {
3516                 die "$full_path not known in r$self->{r} or we have a bug!\n";
3517         }
3518         {
3519                 no warnings 'once';
3520                 # SVN::Node::none and SVN::Node::file are used only once,
3521                 # so we're shutting up Perl's warnings about them.
3522                 if ($t == $SVN::Node::none) {
3523                         return $self->add_directory($full_path, $baton,
3524                             undef, -1, $self->{pool});
3525                 } elsif ($t == $SVN::Node::dir) {
3526                         return $self->open_directory($full_path, $baton,
3527                             $self->{r}, $self->{pool});
3528                 } # no warnings 'once'
3529                 print STDERR "$full_path already exists in repository at ",
3530                     "r$self->{r} and it is not a directory (",
3531                     ($t == $SVN::Node::file ? 'file' : 'unknown'),"/$t)\n";
3532         } # no warnings 'once'
3533         exit 1;
3534 }
3535
3536 sub ensure_path {
3537         my ($self, $path) = @_;
3538         my $bat = $self->{bat};
3539         my $repo_path = $self->repo_path($path);
3540         return $bat->{''} unless (length $repo_path);
3541         my @p = split m#/+#, $repo_path;
3542         my $c = shift @p;
3543         $bat->{$c} ||= $self->open_or_add_dir($c, $bat->{''});
3544         while (@p) {
3545                 my $c0 = $c;
3546                 $c .= '/' . shift @p;
3547                 $bat->{$c} ||= $self->open_or_add_dir($c, $bat->{$c0});
3548         }
3549         return $bat->{$c};
3550 }
3551
3552 # Subroutine to convert a globbing pattern to a regular expression.
3553 # From perl cookbook.
3554 sub glob2pat {
3555         my $globstr = shift;
3556         my %patmap = ('*' => '.*', '?' => '.', '[' => '[', ']' => ']');
3557         $globstr =~ s{(.)} { $patmap{$1} || "\Q$1" }ge;
3558         return '^' . $globstr . '$';
3559 }
3560
3561 sub check_autoprop {
3562         my ($self, $pattern, $properties, $file, $fbat) = @_;
3563         # Convert the globbing pattern to a regular expression.
3564         my $regex = glob2pat($pattern);
3565         # Check if the pattern matches the file name.
3566         if($file =~ m/($regex)/) {
3567                 # Parse the list of properties to set.
3568                 my @props = split(/;/, $properties);
3569                 foreach my $prop (@props) {
3570                         # Parse 'name=value' syntax and set the property.
3571                         if ($prop =~ /([^=]+)=(.*)/) {
3572                                 my ($n,$v) = ($1,$2);
3573                                 for ($n, $v) {
3574                                         s/^\s+//; s/\s+$//;
3575                                 }
3576                                 $self->change_file_prop($fbat, $n, $v);
3577                         }
3578                 }
3579         }
3580 }
3581
3582 sub apply_autoprops {
3583         my ($self, $file, $fbat) = @_;
3584         my $conf_t = ${$self->{config}}{'config'};
3585         no warnings 'once';
3586         # Check [miscellany]/enable-auto-props in svn configuration.
3587         if (SVN::_Core::svn_config_get_bool(
3588                 $conf_t,
3589                 $SVN::_Core::SVN_CONFIG_SECTION_MISCELLANY,
3590                 $SVN::_Core::SVN_CONFIG_OPTION_ENABLE_AUTO_PROPS,
3591                 0)) {
3592                 # Auto-props are enabled.  Enumerate them to look for matches.
3593                 my $callback = sub {
3594                         $self->check_autoprop($_[0], $_[1], $file, $fbat);
3595                 };
3596                 SVN::_Core::svn_config_enumerate(
3597                         $conf_t,
3598                         $SVN::_Core::SVN_CONFIG_SECTION_AUTO_PROPS,
3599                         $callback);
3600         }
3601 }
3602
3603 sub A {
3604         my ($self, $m) = @_;
3605         my ($dir, $file) = split_path($m->{file_b});
3606         my $pbat = $self->ensure_path($dir);
3607         my $fbat = $self->add_file($self->repo_path($m->{file_b}), $pbat,
3608                                         undef, -1);
3609         print "\tA\t$m->{file_b}\n" unless $::_q;
3610         $self->apply_autoprops($file, $fbat);
3611         $self->chg_file($fbat, $m);
3612         $self->close_file($fbat,undef,$self->{pool});
3613 }
3614
3615 sub C {
3616         my ($self, $m) = @_;
3617         my ($dir, $file) = split_path($m->{file_b});
3618         my $pbat = $self->ensure_path($dir);
3619         my $fbat = $self->add_file($self->repo_path($m->{file_b}), $pbat,
3620                                 $self->url_path($m->{file_a}), $self->{r});
3621         print "\tC\t$m->{file_a} => $m->{file_b}\n" unless $::_q;
3622         $self->chg_file($fbat, $m);
3623         $self->close_file($fbat,undef,$self->{pool});
3624 }
3625
3626 sub delete_entry {
3627         my ($self, $path, $pbat) = @_;
3628         my $rpath = $self->repo_path($path);
3629         my ($dir, $file) = split_path($rpath);
3630         $self->{rm}->{$dir} = 1;
3631         $self->SUPER::delete_entry($rpath, $self->{r}, $pbat, $self->{pool});
3632 }
3633
3634 sub R {
3635         my ($self, $m) = @_;
3636         my ($dir, $file) = split_path($m->{file_b});
3637         my $pbat = $self->ensure_path($dir);
3638         my $fbat = $self->add_file($self->repo_path($m->{file_b}), $pbat,
3639                                 $self->url_path($m->{file_a}), $self->{r});
3640         print "\tR\t$m->{file_a} => $m->{file_b}\n" unless $::_q;
3641         $self->chg_file($fbat, $m);
3642         $self->close_file($fbat,undef,$self->{pool});
3643
3644         ($dir, $file) = split_path($m->{file_a});
3645         $pbat = $self->ensure_path($dir);
3646         $self->delete_entry($m->{file_a}, $pbat);
3647 }
3648
3649 sub M {
3650         my ($self, $m) = @_;
3651         my ($dir, $file) = split_path($m->{file_b});
3652         my $pbat = $self->ensure_path($dir);
3653         my $fbat = $self->open_file($self->repo_path($m->{file_b}),
3654                                 $pbat,$self->{r},$self->{pool});
3655         print "\t$m->{chg}\t$m->{file_b}\n" unless $::_q;
3656         $self->chg_file($fbat, $m);
3657         $self->close_file($fbat,undef,$self->{pool});
3658 }
3659
3660 sub T { shift->M(@_) }
3661
3662 sub change_file_prop {
3663         my ($self, $fbat, $pname, $pval) = @_;
3664         $self->SUPER::change_file_prop($fbat, $pname, $pval, $self->{pool});
3665 }
3666
3667 sub _chg_file_get_blob ($$$$) {
3668         my ($self, $fbat, $m, $which) = @_;
3669         my $fh = Git::temp_acquire("git_blob_$which");
3670         if ($m->{"mode_$which"} =~ /^120/) {
3671                 print $fh 'link ' or croak $!;
3672                 $self->change_file_prop($fbat,'svn:special','*');
3673         } elsif ($m->{mode_a} =~ /^120/ && $m->{"mode_$which"} !~ /^120/) {
3674                 $self->change_file_prop($fbat,'svn:special',undef);
3675         }
3676         my $blob = $m->{"sha1_$which"};
3677         return ($fh,) if ($blob =~ /^0{40}$/);
3678         my $size = $::_repository->cat_blob($blob, $fh);
3679         croak "Failed to read object $blob" if ($size < 0);
3680         $fh->flush == 0 or croak $!;
3681         seek $fh, 0, 0 or croak $!;
3682
3683         my $exp = ::md5sum($fh);
3684         seek $fh, 0, 0 or croak $!;
3685         return ($fh, $exp);
3686 }
3687
3688 sub chg_file {
3689         my ($self, $fbat, $m) = @_;
3690         if ($m->{mode_b} =~ /755$/ && $m->{mode_a} !~ /755$/) {
3691                 $self->change_file_prop($fbat,'svn:executable','*');
3692         } elsif ($m->{mode_b} !~ /755$/ && $m->{mode_a} =~ /755$/) {
3693                 $self->change_file_prop($fbat,'svn:executable',undef);
3694         }
3695         my ($fh_a, $exp_a) = _chg_file_get_blob $self, $fbat, $m, 'a';
3696         my ($fh_b, $exp_b) = _chg_file_get_blob $self, $fbat, $m, 'b';
3697         my $pool = SVN::Pool->new;
3698         my $atd = $self->apply_textdelta($fbat, $exp_a, $pool);
3699         if (-s $fh_a) {
3700                 my $txstream = SVN::TxDelta::new ($fh_a, $fh_b, $pool);
3701                 my $res = SVN::TxDelta::send_txstream($txstream, @$atd, $pool);
3702                 if (defined $res) {
3703                         die "Unexpected result from send_txstream: $res\n",
3704                             "(SVN::Core::VERSION: $SVN::Core::VERSION)\n";
3705                 }
3706         } else {
3707                 my $got = SVN::TxDelta::send_stream($fh_b, @$atd, $pool);
3708                 die "Checksum mismatch\nexpected: $exp_b\ngot: $got\n"
3709                     if ($got ne $exp_b);
3710         }
3711         Git::temp_release($fh_b, 1);
3712         Git::temp_release($fh_a, 1);
3713         $pool->clear;
3714 }
3715
3716 sub D {
3717         my ($self, $m) = @_;
3718         my ($dir, $file) = split_path($m->{file_b});
3719         my $pbat = $self->ensure_path($dir);
3720         print "\tD\t$m->{file_b}\n" unless $::_q;
3721         $self->delete_entry($m->{file_b}, $pbat);
3722 }
3723
3724 sub close_edit {
3725         my ($self) = @_;
3726         my ($p,$bat) = ($self->{pool}, $self->{bat});
3727         foreach (sort { $b =~ tr#/#/# <=> $a =~ tr#/#/# } keys %$bat) {
3728                 next if $_ eq '';
3729                 $self->close_directory($bat->{$_}, $p);
3730         }
3731         $self->close_directory($bat->{''}, $p);
3732         $self->SUPER::close_edit($p);
3733         $p->clear;
3734 }
3735
3736 sub abort_edit {
3737         my ($self) = @_;
3738         $self->SUPER::abort_edit($self->{pool});
3739 }
3740
3741 sub DESTROY {
3742         my $self = shift;
3743         $self->SUPER::DESTROY(@_);
3744         $self->{pool}->clear;
3745 }
3746
3747 # this drives the editor
3748 sub apply_diff {
3749         my ($self) = @_;
3750         my $mods = $self->{mods};
3751         my %o = ( D => 1, R => 0, C => -1, A => 3, M => 3, T => 3 );
3752         foreach my $m (sort { $o{$a->{chg}} <=> $o{$b->{chg}} } @$mods) {
3753                 my $f = $m->{chg};
3754                 if (defined $o{$f}) {
3755                         $self->$f($m);
3756                 } else {
3757                         fatal("Invalid change type: $f");
3758                 }
3759         }
3760         $self->rmdirs if $_rmdir;
3761         if (@$mods == 0) {
3762                 $self->abort_edit;
3763         } else {
3764                 $self->close_edit;
3765         }
3766         return scalar @$mods;
3767 }
3768
3769 package Git::SVN::Ra;
3770 use vars qw/@ISA $config_dir $_log_window_size/;
3771 use strict;
3772 use warnings;
3773 my ($ra_invalid, $can_do_switch, %ignored_err, $RA);
3774
3775 BEGIN {
3776         # enforce temporary pool usage for some simple functions
3777         no strict 'refs';
3778         for my $f (qw/rev_proplist get_latest_revnum get_uuid get_repos_root/) {
3779                 my $SUPER = "SUPER::$f";
3780                 *$f = sub {
3781                         my $self = shift;
3782                         my $pool = SVN::Pool->new;
3783                         my @ret = $self->$SUPER(@_,$pool);
3784                         $pool->clear;
3785                         wantarray ? @ret : $ret[0];
3786                 };
3787         }
3788 }
3789
3790 sub _auth_providers () {
3791         [
3792           SVN::Client::get_simple_provider(),
3793           SVN::Client::get_ssl_server_trust_file_provider(),
3794           SVN::Client::get_simple_prompt_provider(
3795             \&Git::SVN::Prompt::simple, 2),
3796           SVN::Client::get_ssl_client_cert_file_provider(),
3797           SVN::Client::get_ssl_client_cert_prompt_provider(
3798             \&Git::SVN::Prompt::ssl_client_cert, 2),
3799           SVN::Client::get_ssl_client_cert_pw_file_provider(),
3800           SVN::Client::get_ssl_client_cert_pw_prompt_provider(
3801             \&Git::SVN::Prompt::ssl_client_cert_pw, 2),
3802           SVN::Client::get_username_provider(),
3803           SVN::Client::get_ssl_server_trust_prompt_provider(
3804             \&Git::SVN::Prompt::ssl_server_trust),
3805           SVN::Client::get_username_prompt_provider(
3806             \&Git::SVN::Prompt::username, 2)
3807         ]
3808 }
3809
3810 sub escape_uri_only {
3811         my ($uri) = @_;
3812         my @tmp;
3813         foreach (split m{/}, $uri) {
3814                 s/([^\w.%+-]|%(?![a-fA-F0-9]{2}))/sprintf("%%%02X",ord($1))/eg;
3815                 push @tmp, $_;
3816         }
3817         join('/', @tmp);
3818 }
3819
3820 sub escape_url {
3821         my ($url) = @_;
3822         if ($url =~ m#^(https?)://([^/]+)(.*)$#) {
3823                 my ($scheme, $domain, $uri) = ($1, $2, escape_uri_only($3));
3824                 $url = "$scheme://$domain$uri";
3825         }
3826         $url;
3827 }
3828
3829 sub new {
3830         my ($class, $url) = @_;
3831         $url =~ s!/+$!!;
3832         return $RA if ($RA && $RA->{url} eq $url);
3833
3834         SVN::_Core::svn_config_ensure($config_dir, undef);
3835         my ($baton, $callbacks) = SVN::Core::auth_open_helper(_auth_providers);
3836         my $config = SVN::Core::config_get_config($config_dir);
3837         $RA = undef;
3838         my $dont_store_passwords = 1;
3839         my $conf_t = ${$config}{'config'};
3840         {
3841                 no warnings 'once';
3842                 # The usage of $SVN::_Core::SVN_CONFIG_* variables
3843                 # produces warnings that variables are used only once.
3844                 # I had not found the better way to shut them up, so
3845                 # the warnings of type 'once' are disabled in this block.
3846                 if (SVN::_Core::svn_config_get_bool($conf_t,
3847                     $SVN::_Core::SVN_CONFIG_SECTION_AUTH,
3848                     $SVN::_Core::SVN_CONFIG_OPTION_STORE_PASSWORDS,
3849                     1) == 0) {
3850                         SVN::_Core::svn_auth_set_parameter($baton,
3851                             $SVN::_Core::SVN_AUTH_PARAM_DONT_STORE_PASSWORDS,
3852                             bless (\$dont_store_passwords, "_p_void"));
3853                 }
3854                 if (SVN::_Core::svn_config_get_bool($conf_t,
3855                     $SVN::_Core::SVN_CONFIG_SECTION_AUTH,
3856                     $SVN::_Core::SVN_CONFIG_OPTION_STORE_AUTH_CREDS,
3857                     1) == 0) {
3858                         $Git::SVN::Prompt::_no_auth_cache = 1;
3859                 }
3860         } # no warnings 'once'
3861         my $self = SVN::Ra->new(url => escape_url($url), auth => $baton,
3862                               config => $config,
3863                               pool => SVN::Pool->new,
3864                               auth_provider_callbacks => $callbacks);
3865         $self->{url} = $url;
3866         $self->{svn_path} = $url;
3867         $self->{repos_root} = $self->get_repos_root;
3868         $self->{svn_path} =~ s#^\Q$self->{repos_root}\E(/|$)##;
3869         $self->{cache} = { check_path => { r => 0, data => {} },
3870                            get_dir => { r => 0, data => {} } };
3871         $RA = bless $self, $class;
3872 }
3873
3874 sub check_path {
3875         my ($self, $path, $r) = @_;
3876         my $cache = $self->{cache}->{check_path};
3877         if ($r == $cache->{r} && exists $cache->{data}->{$path}) {
3878                 return $cache->{data}->{$path};
3879         }
3880         my $pool = SVN::Pool->new;
3881         my $t = $self->SUPER::check_path($path, $r, $pool);
3882         $pool->clear;
3883         if ($r != $cache->{r}) {
3884                 %{$cache->{data}} = ();
3885                 $cache->{r} = $r;
3886         }
3887         $cache->{data}->{$path} = $t;
3888 }
3889
3890 sub get_dir {
3891         my ($self, $dir, $r) = @_;
3892         my $cache = $self->{cache}->{get_dir};
3893         if ($r == $cache->{r}) {
3894                 if (my $x = $cache->{data}->{$dir}) {
3895                         return wantarray ? @$x : $x->[0];
3896                 }
3897         }
3898         my $pool = SVN::Pool->new;
3899         my ($d, undef, $props) = $self->SUPER::get_dir($dir, $r, $pool);
3900         my %dirents = map { $_ => { kind => $d->{$_}->kind } } keys %$d;
3901         $pool->clear;
3902         if ($r != $cache->{r}) {
3903                 %{$cache->{data}} = ();
3904                 $cache->{r} = $r;
3905         }
3906         $cache->{data}->{$dir} = [ \%dirents, $r, $props ];
3907         wantarray ? (\%dirents, $r, $props) : \%dirents;
3908 }
3909
3910 sub DESTROY {
3911         # do not call the real DESTROY since we store ourselves in $RA
3912 }
3913
3914 sub get_log {
3915         my ($self, @args) = @_;
3916         my $pool = SVN::Pool->new;
3917         splice(@args, 3, 1) if ($SVN::Core::VERSION le '1.2.0');
3918         my $ret = $self->SUPER::get_log(@args, $pool);
3919         $pool->clear;
3920         $ret;
3921 }
3922
3923 sub trees_match {
3924         my ($self, $url1, $rev1, $url2, $rev2) = @_;
3925         my $ctx = SVN::Client->new(auth => _auth_providers);
3926         my $out = IO::File->new_tmpfile;
3927
3928         # older SVN (1.1.x) doesn't take $pool as the last parameter for
3929         # $ctx->diff(), so we'll create a default one
3930         my $pool = SVN::Pool->new_default_sub;
3931
3932         $ra_invalid = 1; # this will open a new SVN::Ra connection to $url1
3933         $ctx->diff([], $url1, $rev1, $url2, $rev2, 1, 1, 0, $out, $out);
3934         $out->flush;
3935         my $ret = (($out->stat)[7] == 0);
3936         close $out or croak $!;
3937
3938         $ret;
3939 }
3940
3941 sub get_commit_editor {
3942         my ($self, $log, $cb, $pool) = @_;
3943         my @lock = $SVN::Core::VERSION ge '1.2.0' ? (undef, 0) : ();
3944         $self->SUPER::get_commit_editor($log, $cb, @lock, $pool);
3945 }
3946
3947 sub gs_do_update {
3948         my ($self, $rev_a, $rev_b, $gs, $editor) = @_;
3949         my $new = ($rev_a == $rev_b);
3950         my $path = $gs->{path};
3951
3952         if ($new && -e $gs->{index}) {
3953                 unlink $gs->{index} or die
3954                   "Couldn't unlink index: $gs->{index}: $!\n";
3955         }
3956         my $pool = SVN::Pool->new;
3957         $editor->set_path_strip($path);
3958         my (@pc) = split m#/#, $path;
3959         my $reporter = $self->do_update($rev_b, (@pc ? shift @pc : ''),
3960                                         1, $editor, $pool);
3961         my @lock = $SVN::Core::VERSION ge '1.2.0' ? (undef) : ();
3962
3963         # Since we can't rely on svn_ra_reparent being available, we'll
3964         # just have to do some magic with set_path to make it so
3965         # we only want a partial path.
3966         my $sp = '';
3967         my $final = join('/', @pc);
3968         while (@pc) {
3969                 $reporter->set_path($sp, $rev_b, 0, @lock, $pool);
3970                 $sp .= '/' if length $sp;
3971                 $sp .= shift @pc;
3972         }
3973         die "BUG: '$sp' != '$final'\n" if ($sp ne $final);
3974
3975         $reporter->set_path($sp, $rev_a, $new, @lock, $pool);
3976
3977         $reporter->finish_report($pool);
3978         $pool->clear;
3979         $editor->{git_commit_ok};
3980 }
3981
3982 # this requires SVN 1.4.3 or later (do_switch didn't work before 1.4.3, and
3983 # svn_ra_reparent didn't work before 1.4)
3984 sub gs_do_switch {
3985         my ($self, $rev_a, $rev_b, $gs, $url_b, $editor) = @_;
3986         my $path = $gs->{path};
3987         my $pool = SVN::Pool->new;
3988
3989         my $full_url = $self->{url};
3990         my $old_url = $full_url;
3991         $full_url .= '/' . escape_uri_only($path) if length $path;
3992         my ($ra, $reparented);
3993         if ($old_url ne $full_url) {
3994                 if ($old_url !~ m#^svn(\+ssh)?://#) {
3995                         SVN::_Ra::svn_ra_reparent($self->{session}, $full_url,
3996                                                   $pool);
3997                         $self->{url} = $full_url;
3998                         $reparented = 1;
3999                 } else {
4000                         $_[0] = undef;
4001                         $self = undef;
4002                         $RA = undef;
4003                         $ra = Git::SVN::Ra->new($full_url);
4004                         $ra_invalid = 1;
4005                 }
4006         }
4007         $ra ||= $self;
4008         my $reporter = $ra->do_switch($rev_b, '', 1, $url_b, $editor, $pool);
4009         my @lock = $SVN::Core::VERSION ge '1.2.0' ? (undef) : ();
4010         $reporter->set_path('', $rev_a, 0, @lock, $pool);
4011         $reporter->finish_report($pool);
4012
4013         if ($reparented) {
4014                 SVN::_Ra::svn_ra_reparent($self->{session}, $old_url, $pool);
4015                 $self->{url} = $old_url;
4016         }
4017
4018         $pool->clear;
4019         $editor->{git_commit_ok};
4020 }
4021
4022 sub longest_common_path {
4023         my ($gsv, $globs) = @_;
4024         my %common;
4025         my $common_max = scalar @$gsv;
4026
4027         foreach my $gs (@$gsv) {
4028                 my @tmp = split m#/#, $gs->{path};
4029                 my $p = '';
4030                 foreach (@tmp) {
4031                         $p .= length($p) ? "/$_" : $_;
4032                         $common{$p} ||= 0;
4033                         $common{$p}++;
4034                 }
4035         }
4036         $globs ||= [];
4037         $common_max += scalar @$globs;
4038         foreach my $glob (@$globs) {
4039                 my @tmp = split m#/#, $glob->{path}->{left};
4040                 my $p = '';
4041                 foreach (@tmp) {
4042                         $p .= length($p) ? "/$_" : $_;
4043                         $common{$p} ||= 0;
4044                         $common{$p}++;
4045                 }
4046         }
4047
4048         my $longest_path = '';
4049         foreach (sort {length $b <=> length $a} keys %common) {
4050                 if ($common{$_} == $common_max) {
4051                         $longest_path = $_;
4052                         last;
4053                 }
4054         }
4055         $longest_path;
4056 }
4057
4058 sub gs_fetch_loop_common {
4059         my ($self, $base, $head, $gsv, $globs) = @_;
4060         return if ($base > $head);
4061         my $inc = $_log_window_size;
4062         my ($min, $max) = ($base, $head < $base + $inc ? $head : $base + $inc);
4063         my $longest_path = longest_common_path($gsv, $globs);
4064         my $ra_url = $self->{url};
4065         while (1) {
4066                 my %revs;
4067                 my $err;
4068                 my $err_handler = $SVN::Error::handler;
4069                 $SVN::Error::handler = sub {
4070                         ($err) = @_;
4071                         skip_unknown_revs($err);
4072                 };
4073                 sub _cb {
4074                         my ($paths, $r, $author, $date, $log) = @_;
4075                         [ dup_changed_paths($paths),
4076                           { author => $author, date => $date, log => $log } ];
4077                 }
4078                 $self->get_log([$longest_path], $min, $max, 0, 1, 1,
4079                                sub { $revs{$_[1]} = _cb(@_) });
4080                 if ($err && $max >= $head) {
4081                         print STDERR "Path '$longest_path' ",
4082                                      "was probably deleted:\n",
4083                                      $err->expanded_message,
4084                                      "\nWill attempt to follow ",
4085                                      "revisions r$min .. r$max ",
4086                                      "committed before the deletion\n";
4087                         my $hi = $max;
4088                         while (--$hi >= $min) {
4089                                 my $ok;
4090                                 $self->get_log([$longest_path], $min, $hi,
4091                                                0, 1, 1, sub {
4092                                                $ok ||= $_[1];
4093                                                $revs{$_[1]} = _cb(@_) });
4094                                 if ($ok) {
4095                                         print STDERR "r$min .. r$ok OK\n";
4096                                         last;
4097                                 }
4098                         }
4099                 }
4100                 $SVN::Error::handler = $err_handler;
4101
4102                 my %exists = map { $_->{path} => $_ } @$gsv;
4103                 foreach my $r (sort {$a <=> $b} keys %revs) {
4104                         my ($paths, $logged) = @{$revs{$r}};
4105
4106                         foreach my $gs ($self->match_globs(\%exists, $paths,
4107                                                            $globs, $r)) {
4108                                 if ($gs->rev_map_max >= $r) {
4109                                         next;
4110                                 }
4111                                 next unless $gs->match_paths($paths, $r);
4112                                 $gs->{logged_rev_props} = $logged;
4113                                 if (my $last_commit = $gs->last_commit) {
4114                                         $gs->assert_index_clean($last_commit);
4115                                 }
4116                                 my $log_entry = $gs->do_fetch($paths, $r);
4117                                 if ($log_entry) {
4118                                         $gs->do_git_commit($log_entry);
4119                                 }
4120                                 $INDEX_FILES{$gs->{index}} = 1;
4121                         }
4122                         foreach my $g (@$globs) {
4123                                 my $k = "svn-remote.$g->{remote}." .
4124                                         "$g->{t}-maxRev";
4125                                 Git::SVN::tmp_config($k, $r);
4126                         }
4127                         if ($ra_invalid) {
4128                                 $_[0] = undef;
4129                                 $self = undef;
4130                                 $RA = undef;
4131                                 $self = Git::SVN::Ra->new($ra_url);
4132                                 $ra_invalid = undef;
4133                         }
4134                 }
4135                 # pre-fill the .rev_db since it'll eventually get filled in
4136                 # with '0' x40 if something new gets committed
4137                 foreach my $gs (@$gsv) {
4138                         next if $gs->rev_map_max >= $max;
4139                         next if defined $gs->rev_map_get($max);
4140                         $gs->rev_map_set($max, 0 x40);
4141                 }
4142                 foreach my $g (@$globs) {
4143                         my $k = "svn-remote.$g->{remote}.$g->{t}-maxRev";
4144                         Git::SVN::tmp_config($k, $max);
4145                 }
4146                 last if $max >= $head;
4147                 $min = $max + 1;
4148                 $max += $inc;
4149                 $max = $head if ($max > $head);
4150         }
4151         Git::SVN::gc();
4152 }
4153
4154 sub get_dir_globbed {
4155         my ($self, $left, $depth, $r) = @_;
4156
4157         my @x = eval { $self->get_dir($left, $r) };
4158         return unless scalar @x == 3;
4159         my $dirents = $x[0];
4160         my @finalents;
4161         foreach my $de (keys %$dirents) {
4162                 next if $dirents->{$de}->{kind} != $SVN::Node::dir;
4163                 if ($depth > 1) {
4164                         my @args = ("$left/$de", $depth - 1, $r);
4165                         foreach my $dir ($self->get_dir_globbed(@args)) {
4166                                 push @finalents, "$de/$dir";
4167                         }
4168                 } else {
4169                         push @finalents, $de;
4170                 }
4171         }
4172         @finalents;
4173 }
4174
4175 sub match_globs {
4176         my ($self, $exists, $paths, $globs, $r) = @_;
4177
4178         sub get_dir_check {
4179                 my ($self, $exists, $g, $r) = @_;
4180
4181                 my @dirs = $self->get_dir_globbed($g->{path}->{left},
4182                                                   $g->{path}->{depth},
4183                                                   $r);
4184
4185                 foreach my $de (@dirs) {
4186                         my $p = $g->{path}->full_path($de);
4187                         next if $exists->{$p};
4188                         next if (length $g->{path}->{right} &&
4189                                  ($self->check_path($p, $r) !=
4190                                   $SVN::Node::dir));
4191                         $exists->{$p} = Git::SVN->init($self->{url}, $p, undef,
4192                                          $g->{ref}->full_path($de), 1);
4193                 }
4194         }
4195         foreach my $g (@$globs) {
4196                 if (my $path = $paths->{"/$g->{path}->{left}"}) {
4197                         if ($path->{action} =~ /^[AR]$/) {
4198                                 get_dir_check($self, $exists, $g, $r);
4199                         }
4200                 }
4201                 foreach (keys %$paths) {
4202                         if (/$g->{path}->{left_regex}/ &&
4203                             !/$g->{path}->{regex}/) {
4204                                 next if $paths->{$_}->{action} !~ /^[AR]$/;
4205                                 get_dir_check($self, $exists, $g, $r);
4206                         }
4207                         next unless /$g->{path}->{regex}/;
4208                         my $p = $1;
4209                         my $pathname = $g->{path}->full_path($p);
4210                         next if $exists->{$pathname};
4211                         next if ($self->check_path($pathname, $r) !=
4212                                  $SVN::Node::dir);
4213                         $exists->{$pathname} = Git::SVN->init(
4214                                               $self->{url}, $pathname, undef,
4215                                               $g->{ref}->full_path($p), 1);
4216                 }
4217                 my $c = '';
4218                 foreach (split m#/#, $g->{path}->{left}) {
4219                         $c .= "/$_";
4220                         next unless ($paths->{$c} &&
4221                                      ($paths->{$c}->{action} =~ /^[AR]$/));
4222                         get_dir_check($self, $exists, $g, $r);
4223                 }
4224         }
4225         values %$exists;
4226 }
4227
4228 sub minimize_url {
4229         my ($self) = @_;
4230         return $self->{url} if ($self->{url} eq $self->{repos_root});
4231         my $url = $self->{repos_root};
4232         my @components = split(m!/!, $self->{svn_path});
4233         my $c = '';
4234         do {
4235                 $url .= "/$c" if length $c;
4236                 eval { (ref $self)->new($url)->get_latest_revnum };
4237         } while ($@ && ($c = shift @components));
4238         $url;
4239 }
4240
4241 sub can_do_switch {
4242         my $self = shift;
4243         unless (defined $can_do_switch) {
4244                 my $pool = SVN::Pool->new;
4245                 my $rep = eval {
4246                         $self->do_switch(1, '', 0, $self->{url},
4247                                          SVN::Delta::Editor->new, $pool);
4248                 };
4249                 if ($@) {
4250                         $can_do_switch = 0;
4251                 } else {
4252                         $rep->abort_report($pool);
4253                         $can_do_switch = 1;
4254                 }
4255                 $pool->clear;
4256         }
4257         $can_do_switch;
4258 }
4259
4260 sub skip_unknown_revs {
4261         my ($err) = @_;
4262         my $errno = $err->apr_err();
4263         # Maybe the branch we're tracking didn't
4264         # exist when the repo started, so it's
4265         # not an error if it doesn't, just continue
4266         #
4267         # Wonderfully consistent library, eh?
4268         # 160013 - svn:// and file://
4269         # 175002 - http(s)://
4270         # 175007 - http(s):// (this repo required authorization, too...)
4271         #   More codes may be discovered later...
4272         if ($errno == 175007 || $errno == 175002 || $errno == 160013) {
4273                 my $err_key = $err->expanded_message;
4274                 # revision numbers change every time, filter them out
4275                 $err_key =~ s/\d+/\0/g;
4276                 $err_key = "$errno\0$err_key";
4277                 unless ($ignored_err{$err_key}) {
4278                         warn "W: Ignoring error from SVN, path probably ",
4279                              "does not exist: ($errno): ",
4280                              $err->expanded_message,"\n";
4281                         warn "W: Do not be alarmed at the above message ",
4282                              "git-svn is just searching aggressively for ",
4283                              "old history.\n",
4284                              "This may take a while on large repositories\n";
4285                         $ignored_err{$err_key} = 1;
4286                 }
4287                 return;
4288         }
4289         die "Error from SVN, ($errno): ", $err->expanded_message,"\n";
4290 }
4291
4292 # svn_log_changed_path_t objects passed to get_log are likely to be
4293 # overwritten even if only the refs are copied to an external variable,
4294 # so we should dup the structures in their entirety.  Using an externally
4295 # passed pool (instead of our temporary and quickly cleared pool in
4296 # Git::SVN::Ra) does not help matters at all...
4297 sub dup_changed_paths {
4298         my ($paths) = @_;
4299         return undef unless $paths;
4300         my %ret;
4301         foreach my $p (keys %$paths) {
4302                 my $i = $paths->{$p};
4303                 my %s = map { $_ => $i->$_ }
4304                               qw/copyfrom_path copyfrom_rev action/;
4305                 $ret{$p} = \%s;
4306         }
4307         \%ret;
4308 }
4309
4310 package Git::SVN::Log;
4311 use strict;
4312 use warnings;
4313 use POSIX qw/strftime/;
4314 use constant commit_log_separator => ('-' x 72) . "\n";
4315 use vars qw/$TZ $limit $color $pager $non_recursive $verbose $oneline
4316             %rusers $show_commit $incremental/;
4317 my $l_fmt;
4318
4319 sub cmt_showable {
4320         my ($c) = @_;
4321         return 1 if defined $c->{r};
4322
4323         # big commit message got truncated by the 16k pretty buffer in rev-list
4324         if ($c->{l} && $c->{l}->[-1] eq "...\n" &&
4325                                 $c->{a_raw} =~ /\@([a-f\d\-]+)>$/) {
4326                 @{$c->{l}} = ();
4327                 my @log = command(qw/cat-file commit/, $c->{c});
4328
4329                 # shift off the headers
4330                 shift @log while ($log[0] ne '');
4331                 shift @log;
4332
4333                 # TODO: make $c->{l} not have a trailing newline in the future
4334                 @{$c->{l}} = map { "$_\n" } grep !/^git-svn-id: /, @log;
4335
4336                 (undef, $c->{r}, undef) = ::extract_metadata(
4337                                 (grep(/^git-svn-id: /, @log))[-1]);
4338         }
4339         return defined $c->{r};
4340 }
4341
4342 sub log_use_color {
4343         return $color || Git->repository->get_colorbool('color.diff');
4344 }
4345
4346 sub git_svn_log_cmd {
4347         my ($r_min, $r_max, @args) = @_;
4348         my $head = 'HEAD';
4349         my (@files, @log_opts);
4350         foreach my $x (@args) {
4351                 if ($x eq '--' || @files) {
4352                         push @files, $x;
4353                 } else {
4354                         if (::verify_ref("$x^0")) {
4355                                 $head = $x;
4356                         } else {
4357                                 push @log_opts, $x;
4358                         }
4359                 }
4360         }
4361
4362         my ($url, $rev, $uuid, $gs) = ::working_head_info($head);
4363         $gs ||= Git::SVN->_new;
4364         my @cmd = (qw/log --abbrev-commit --pretty=raw --default/,
4365                    $gs->refname);
4366         push @cmd, '-r' unless $non_recursive;
4367         push @cmd, qw/--raw --name-status/ if $verbose;
4368         push @cmd, '--color' if log_use_color();
4369         push @cmd, @log_opts;
4370         if (defined $r_max && $r_max == $r_min) {
4371                 push @cmd, '--max-count=1';
4372                 if (my $c = $gs->rev_map_get($r_max)) {
4373                         push @cmd, $c;
4374                 }
4375         } elsif (defined $r_max) {
4376                 if ($r_max < $r_min) {
4377                         ($r_min, $r_max) = ($r_max, $r_min);
4378                 }
4379                 my (undef, $c_max) = $gs->find_rev_before($r_max, 1, $r_min);
4380                 my (undef, $c_min) = $gs->find_rev_after($r_min, 1, $r_max);
4381                 # If there are no commits in the range, both $c_max and $c_min
4382                 # will be undefined.  If there is at least 1 commit in the
4383                 # range, both will be defined.
4384                 return () if !defined $c_min || !defined $c_max;
4385                 if ($c_min eq $c_max) {
4386                         push @cmd, '--max-count=1', $c_min;
4387                 } else {
4388                         push @cmd, '--boundary', "$c_min..$c_max";
4389                 }
4390         }
4391         return (@cmd, @files);
4392 }
4393
4394 # adapted from pager.c
4395 sub config_pager {
4396         $pager ||= $ENV{GIT_PAGER} || $ENV{PAGER};
4397         if (!defined $pager) {
4398                 $pager = 'less';
4399         } elsif (length $pager == 0 || $pager eq 'cat') {
4400                 $pager = undef;
4401         }
4402         $ENV{GIT_PAGER_IN_USE} = defined($pager);
4403 }
4404
4405 sub run_pager {
4406         return unless -t *STDOUT && defined $pager;
4407         pipe my $rfd, my $wfd or return;
4408         defined(my $pid = fork) or ::fatal "Can't fork: $!";
4409         if (!$pid) {
4410                 open STDOUT, '>&', $wfd or
4411                                      ::fatal "Can't redirect to stdout: $!";
4412                 return;
4413         }
4414         open STDIN, '<&', $rfd or ::fatal "Can't redirect stdin: $!";
4415         $ENV{LESS} ||= 'FRSX';
4416         exec $pager or ::fatal "Can't run pager: $! ($pager)";
4417 }
4418
4419 sub format_svn_date {
4420         return strftime("%Y-%m-%d %H:%M:%S %z (%a, %d %b %Y)", localtime(shift));
4421 }
4422
4423 sub parse_git_date {
4424         my ($t, $tz) = @_;
4425         # Date::Parse isn't in the standard Perl distro :(
4426         if ($tz =~ s/^\+//) {
4427                 $t += tz_to_s_offset($tz);
4428         } elsif ($tz =~ s/^\-//) {
4429                 $t -= tz_to_s_offset($tz);
4430         }
4431         return $t;
4432 }
4433
4434 sub set_local_timezone {
4435         if (defined $TZ) {
4436                 $ENV{TZ} = $TZ;
4437         } else {
4438                 delete $ENV{TZ};
4439         }
4440 }
4441
4442 sub tz_to_s_offset {
4443         my ($tz) = @_;
4444         $tz =~ s/(\d\d)$//;
4445         return ($1 * 60) + ($tz * 3600);
4446 }
4447
4448 sub get_author_info {
4449         my ($dest, $author, $t, $tz) = @_;
4450         $author =~ s/(?:^\s*|\s*$)//g;
4451         $dest->{a_raw} = $author;
4452         my $au;
4453         if ($::_authors) {
4454                 $au = $rusers{$author} || undef;
4455         }
4456         if (!$au) {
4457                 ($au) = ($author =~ /<([^>]+)\@[^>]+>$/);
4458         }
4459         $dest->{t} = $t;
4460         $dest->{tz} = $tz;
4461         $dest->{a} = $au;
4462         $dest->{t_utc} = parse_git_date($t, $tz);
4463 }
4464
4465 sub process_commit {
4466         my ($c, $r_min, $r_max, $defer) = @_;
4467         if (defined $r_min && defined $r_max) {
4468                 if ($r_min == $c->{r} && $r_min == $r_max) {
4469                         show_commit($c);
4470                         return 0;
4471                 }
4472                 return 1 if $r_min == $r_max;
4473                 if ($r_min < $r_max) {
4474                         # we need to reverse the print order
4475                         return 0 if (defined $limit && --$limit < 0);
4476                         push @$defer, $c;
4477                         return 1;
4478                 }
4479                 if ($r_min != $r_max) {
4480                         return 1 if ($r_min < $c->{r});
4481                         return 1 if ($r_max > $c->{r});
4482                 }
4483         }
4484         return 0 if (defined $limit && --$limit < 0);
4485         show_commit($c);
4486         return 1;
4487 }
4488
4489 sub show_commit {
4490         my $c = shift;
4491         if ($oneline) {
4492                 my $x = "\n";
4493                 if (my $l = $c->{l}) {
4494                         while ($l->[0] =~ /^\s*$/) { shift @$l }
4495                         $x = $l->[0];
4496                 }
4497                 $l_fmt ||= 'A' . length($c->{r});
4498                 print 'r',pack($l_fmt, $c->{r}),' | ';
4499                 print "$c->{c} | " if $show_commit;
4500                 print $x;
4501         } else {
4502                 show_commit_normal($c);
4503         }
4504 }
4505
4506 sub show_commit_changed_paths {
4507         my ($c) = @_;
4508         return unless $c->{changed};
4509         print "Changed paths:\n", @{$c->{changed}};
4510 }
4511
4512 sub show_commit_normal {
4513         my ($c) = @_;
4514         print commit_log_separator, "r$c->{r} | ";
4515         print "$c->{c} | " if $show_commit;
4516         print "$c->{a} | ", format_svn_date($c->{t_utc}), ' | ';
4517         my $nr_line = 0;
4518
4519         if (my $l = $c->{l}) {
4520                 while ($l->[$#$l] eq "\n" && $#$l > 0
4521                                           && $l->[($#$l - 1)] eq "\n") {
4522                         pop @$l;
4523                 }
4524                 $nr_line = scalar @$l;
4525                 if (!$nr_line) {
4526                         print "1 line\n\n\n";
4527                 } else {
4528                         if ($nr_line == 1) {
4529                                 $nr_line = '1 line';
4530                         } else {
4531                                 $nr_line .= ' lines';
4532                         }
4533                         print $nr_line, "\n";
4534                         show_commit_changed_paths($c);
4535                         print "\n";
4536                         print $_ foreach @$l;
4537                 }
4538         } else {
4539                 print "1 line\n";
4540                 show_commit_changed_paths($c);
4541                 print "\n";
4542
4543         }
4544         foreach my $x (qw/raw stat diff/) {
4545                 if ($c->{$x}) {
4546                         print "\n";
4547                         print $_ foreach @{$c->{$x}}
4548                 }
4549         }
4550 }
4551
4552 sub cmd_show_log {
4553         my (@args) = @_;
4554         my ($r_min, $r_max);
4555         my $r_last = -1; # prevent dupes
4556         set_local_timezone();
4557         if (defined $::_revision) {
4558                 if ($::_revision =~ /^(\d+):(\d+)$/) {
4559                         ($r_min, $r_max) = ($1, $2);
4560                 } elsif ($::_revision =~ /^\d+$/) {
4561                         $r_min = $r_max = $::_revision;
4562                 } else {
4563                         ::fatal "-r$::_revision is not supported, use ",
4564                                 "standard 'git log' arguments instead";
4565                 }
4566         }
4567
4568         config_pager();
4569         @args = git_svn_log_cmd($r_min, $r_max, @args);
4570         if (!@args) {
4571                 print commit_log_separator unless $incremental || $oneline;
4572                 return;
4573         }
4574         my $log = command_output_pipe(@args);
4575         run_pager();
4576         my (@k, $c, $d, $stat);
4577         my $esc_color = qr/(?:\033\[(?:(?:\d+;)*\d*)?m)*/;
4578         while (<$log>) {
4579                 if (/^${esc_color}commit -?($::sha1_short)/o) {
4580                         my $cmt = $1;
4581                         if ($c && cmt_showable($c) && $c->{r} != $r_last) {
4582                                 $r_last = $c->{r};
4583                                 process_commit($c, $r_min, $r_max, \@k) or
4584                                                                 goto out;
4585                         }
4586                         $d = undef;
4587                         $c = { c => $cmt };
4588                 } elsif (/^${esc_color}author (.+) (\d+) ([\-\+]?\d+)$/o) {
4589                         get_author_info($c, $1, $2, $3);
4590                 } elsif (/^${esc_color}(?:tree|parent|committer) /o) {
4591                         # ignore
4592                 } elsif (/^${esc_color}:\d{6} \d{6} $::sha1_short/o) {
4593                         push @{$c->{raw}}, $_;
4594                 } elsif (/^${esc_color}[ACRMDT]\t/) {
4595                         # we could add $SVN->{svn_path} here, but that requires
4596                         # remote access at the moment (repo_path_split)...
4597                         s#^(${esc_color})([ACRMDT])\t#$1   $2 #o;
4598                         push @{$c->{changed}}, $_;
4599                 } elsif (/^${esc_color}diff /o) {
4600                         $d = 1;
4601                         push @{$c->{diff}}, $_;
4602                 } elsif ($d) {
4603                         push @{$c->{diff}}, $_;
4604                 } elsif (/^\ .+\ \|\s*\d+\ $esc_color[\+\-]*
4605                           $esc_color*[\+\-]*$esc_color$/x) {
4606                         $stat = 1;
4607                         push @{$c->{stat}}, $_;
4608                 } elsif ($stat && /^ \d+ files changed, \d+ insertions/) {
4609                         push @{$c->{stat}}, $_;
4610                         $stat = undef;
4611                 } elsif (/^${esc_color}    (git-svn-id:.+)$/o) {
4612                         ($c->{url}, $c->{r}, undef) = ::extract_metadata($1);
4613                 } elsif (s/^${esc_color}    //o) {
4614                         push @{$c->{l}}, $_;
4615                 }
4616         }
4617         if ($c && defined $c->{r} && $c->{r} != $r_last) {
4618                 $r_last = $c->{r};
4619                 process_commit($c, $r_min, $r_max, \@k);
4620         }
4621         if (@k) {
4622                 ($r_min, $r_max) = ($r_max, $r_min);
4623                 process_commit($_, $r_min, $r_max) foreach reverse @k;
4624         }
4625 out:
4626         close $log;
4627         print commit_log_separator unless $incremental || $oneline;
4628 }
4629
4630 sub cmd_blame {
4631         my $path = pop;
4632
4633         config_pager();
4634         run_pager();
4635
4636         my ($fh, $ctx, $rev);
4637
4638         if ($_git_format) {
4639                 ($fh, $ctx) = command_output_pipe('blame', @_, $path);
4640                 while (my $line = <$fh>) {
4641                         if ($line =~ /^\^?([[:xdigit:]]+)\s/) {
4642                                 # Uncommitted edits show up as a rev ID of
4643                                 # all zeros, which we can't look up with
4644                                 # cmt_metadata
4645                                 if ($1 !~ /^0+$/) {
4646                                         (undef, $rev, undef) =
4647                                                 ::cmt_metadata($1);
4648                                         $rev = '0' if (!$rev);
4649                                 } else {
4650                                         $rev = '0';
4651                                 }
4652                                 $rev = sprintf('%-10s', $rev);
4653                                 $line =~ s/^\^?[[:xdigit:]]+(\s)/$rev$1/;
4654                         }
4655                         print $line;
4656                 }
4657         } else {
4658                 ($fh, $ctx) = command_output_pipe('blame', '-p', @_, 'HEAD',
4659                                                   '--', $path);
4660                 my ($sha1);
4661                 my %authors;
4662                 while (my $line = <$fh>) {
4663                         if ($line =~ /^([[:xdigit:]]{40})\s\d+\s\d+/) {
4664                                 $sha1 = $1;
4665                                 (undef, $rev, undef) = ::cmt_metadata($1);
4666                                 $rev = '0' if (!$rev);
4667                         }
4668                         elsif ($line =~ /^author (.*)/) {
4669                                 $authors{$rev} = $1;
4670                                 $authors{$rev} =~ s/\s/_/g;
4671                         }
4672                         elsif ($line =~ /^\t(.*)$/) {
4673                                 printf("%6s %10s %s\n", $rev, $authors{$rev}, $1);
4674                         }
4675                 }
4676         }
4677         command_close_pipe($fh, $ctx);
4678 }
4679
4680 package Git::SVN::Migration;
4681 # these version numbers do NOT correspond to actual version numbers
4682 # of git nor git-svn.  They are just relative.
4683 #
4684 # v0 layout: .git/$id/info/url, refs/heads/$id-HEAD
4685 #
4686 # v1 layout: .git/$id/info/url, refs/remotes/$id
4687 #
4688 # v2 layout: .git/svn/$id/info/url, refs/remotes/$id
4689 #
4690 # v3 layout: .git/svn/$id, refs/remotes/$id
4691 #            - info/url may remain for backwards compatibility
4692 #            - this is what we migrate up to this layout automatically,
4693 #            - this will be used by git svn init on single branches
4694 # v3.1 layout (auto migrated):
4695 #            - .rev_db => .rev_db.$UUID, .rev_db will remain as a symlink
4696 #              for backwards compatibility
4697 #
4698 # v4 layout: .git/svn/$repo_id/$id, refs/remotes/$repo_id/$id
4699 #            - this is only created for newly multi-init-ed
4700 #              repositories.  Similar in spirit to the
4701 #              --use-separate-remotes option in git-clone (now default)
4702 #            - we do not automatically migrate to this (following
4703 #              the example set by core git)
4704 #
4705 # v5 layout: .rev_db.$UUID => .rev_map.$UUID
4706 #            - newer, more-efficient format that uses 24-bytes per record
4707 #              with no filler space.
4708 #            - use xxd -c24 < .rev_map.$UUID to view and debug
4709 #            - This is a one-way migration, repositories updated to the
4710 #              new format will not be able to use old git-svn without
4711 #              rebuilding the .rev_db.  Rebuilding the rev_db is not
4712 #              possible if noMetadata or useSvmProps are set; but should
4713 #              be no problem for users that use the (sensible) defaults.
4714 use strict;
4715 use warnings;
4716 use Carp qw/croak/;
4717 use File::Path qw/mkpath/;
4718 use File::Basename qw/dirname basename/;
4719 use vars qw/$_minimize/;
4720
4721 sub migrate_from_v0 {
4722         my $git_dir = $ENV{GIT_DIR};
4723         return undef unless -d $git_dir;
4724         my ($fh, $ctx) = command_output_pipe(qw/rev-parse --symbolic --all/);
4725         my $migrated = 0;
4726         while (<$fh>) {
4727                 chomp;
4728                 my ($id, $orig_ref) = ($_, $_);
4729                 next unless $id =~ s#^refs/heads/(.+)-HEAD$#$1#;
4730                 next unless -f "$git_dir/$id/info/url";
4731                 my $new_ref = "refs/remotes/$id";
4732                 if (::verify_ref("$new_ref^0")) {
4733                         print STDERR "W: $orig_ref is probably an old ",
4734                                      "branch used by an ancient version of ",
4735                                      "git-svn.\n",
4736                                      "However, $new_ref also exists.\n",
4737                                      "We will not be able ",
4738                                      "to use this branch until this ",
4739                                      "ambiguity is resolved.\n";
4740                         next;
4741                 }
4742                 print STDERR "Migrating from v0 layout...\n" if !$migrated;
4743                 print STDERR "Renaming ref: $orig_ref => $new_ref\n";
4744                 command_noisy('update-ref', $new_ref, $orig_ref);
4745                 command_noisy('update-ref', '-d', $orig_ref, $orig_ref);
4746                 $migrated++;
4747         }
4748         command_close_pipe($fh, $ctx);
4749         print STDERR "Done migrating from v0 layout...\n" if $migrated;
4750         $migrated;
4751 }
4752
4753 sub migrate_from_v1 {
4754         my $git_dir = $ENV{GIT_DIR};
4755         my $migrated = 0;
4756         return $migrated unless -d $git_dir;
4757         my $svn_dir = "$git_dir/svn";
4758
4759         # just in case somebody used 'svn' as their $id at some point...
4760         return $migrated if -d $svn_dir && ! -f "$svn_dir/info/url";
4761
4762         print STDERR "Migrating from a git-svn v1 layout...\n";
4763         mkpath([$svn_dir]);
4764         print STDERR "Data from a previous version of git-svn exists, but\n\t",
4765                      "$svn_dir\n\t(required for this version ",
4766                      "($::VERSION) of git-svn) does not exist.\n";
4767         my ($fh, $ctx) = command_output_pipe(qw/rev-parse --symbolic --all/);
4768         while (<$fh>) {
4769                 my $x = $_;
4770                 next unless $x =~ s#^refs/remotes/##;
4771                 chomp $x;
4772                 next unless -f "$git_dir/$x/info/url";
4773                 my $u = eval { ::file_to_s("$git_dir/$x/info/url") };
4774                 next unless $u;
4775                 my $dn = dirname("$git_dir/svn/$x");
4776                 mkpath([$dn]) unless -d $dn;
4777                 if ($x eq 'svn') { # they used 'svn' as GIT_SVN_ID:
4778                         mkpath(["$git_dir/svn/svn"]);
4779                         print STDERR " - $git_dir/$x/info => ",
4780                                         "$git_dir/svn/$x/info\n";
4781                         rename "$git_dir/$x/info", "$git_dir/svn/$x/info" or
4782                                croak "$!: $x";
4783                         # don't worry too much about these, they probably
4784                         # don't exist with repos this old (save for index,
4785                         # and we can easily regenerate that)
4786                         foreach my $f (qw/unhandled.log index .rev_db/) {
4787                                 rename "$git_dir/$x/$f", "$git_dir/svn/$x/$f";
4788                         }
4789                 } else {
4790                         print STDERR " - $git_dir/$x => $git_dir/svn/$x\n";
4791                         rename "$git_dir/$x", "$git_dir/svn/$x" or
4792                                croak "$!: $x";
4793                 }
4794                 $migrated++;
4795         }
4796         command_close_pipe($fh, $ctx);
4797         print STDERR "Done migrating from a git-svn v1 layout\n";
4798         $migrated;
4799 }
4800
4801 sub read_old_urls {
4802         my ($l_map, $pfx, $path) = @_;
4803         my @dir;
4804         foreach (<$path/*>) {
4805                 if (-r "$_/info/url") {
4806                         $pfx .= '/' if $pfx && $pfx !~ m!/$!;
4807                         my $ref_id = $pfx . basename $_;
4808                         my $url = ::file_to_s("$_/info/url");
4809                         $l_map->{$ref_id} = $url;
4810                 } elsif (-d $_) {
4811                         push @dir, $_;
4812                 }
4813         }
4814         foreach (@dir) {
4815                 my $x = $_;
4816                 $x =~ s!^\Q$ENV{GIT_DIR}\E/svn/!!o;
4817                 read_old_urls($l_map, $x, $_);
4818         }
4819 }
4820
4821 sub migrate_from_v2 {
4822         my @cfg = command(qw/config -l/);
4823         return if grep /^svn-remote\..+\.url=/, @cfg;
4824         my %l_map;
4825         read_old_urls(\%l_map, '', "$ENV{GIT_DIR}/svn");
4826         my $migrated = 0;
4827
4828         foreach my $ref_id (sort keys %l_map) {
4829                 eval { Git::SVN->init($l_map{$ref_id}, '', undef, $ref_id) };
4830                 if ($@) {
4831                         Git::SVN->init($l_map{$ref_id}, '', $ref_id, $ref_id);
4832                 }
4833                 $migrated++;
4834         }
4835         $migrated;
4836 }
4837
4838 sub minimize_connections {
4839         my $r = Git::SVN::read_all_remotes();
4840         my $new_urls = {};
4841         my $root_repos = {};
4842         foreach my $repo_id (keys %$r) {
4843                 my $url = $r->{$repo_id}->{url} or next;
4844                 my $fetch = $r->{$repo_id}->{fetch} or next;
4845                 my $ra = Git::SVN::Ra->new($url);
4846
4847                 # skip existing cases where we already connect to the root
4848                 if (($ra->{url} eq $ra->{repos_root}) ||
4849                     ($ra->{repos_root} eq $repo_id)) {
4850                         $root_repos->{$ra->{url}} = $repo_id;
4851                         next;
4852                 }
4853
4854                 my $root_ra = Git::SVN::Ra->new($ra->{repos_root});
4855                 my $root_path = $ra->{url};
4856                 $root_path =~ s#^\Q$ra->{repos_root}\E(/|$)##;
4857                 foreach my $path (keys %$fetch) {
4858                         my $ref_id = $fetch->{$path};
4859                         my $gs = Git::SVN->new($ref_id, $repo_id, $path);
4860
4861                         # make sure we can read when connecting to
4862                         # a higher level of a repository
4863                         my ($last_rev, undef) = $gs->last_rev_commit;
4864                         if (!defined $last_rev) {
4865                                 $last_rev = eval {
4866                                         $root_ra->get_latest_revnum;
4867                                 };
4868                                 next if $@;
4869                         }
4870                         my $new = $root_path;
4871                         $new .= length $path ? "/$path" : '';
4872                         eval {
4873                                 $root_ra->get_log([$new], $last_rev, $last_rev,
4874                                                   0, 0, 1, sub { });
4875                         };
4876                         next if $@;
4877                         $new_urls->{$ra->{repos_root}}->{$new} =
4878                                 { ref_id => $ref_id,
4879                                   old_repo_id => $repo_id,
4880                                   old_path => $path };
4881                 }
4882         }
4883
4884         my @emptied;
4885         foreach my $url (keys %$new_urls) {
4886                 # see if we can re-use an existing [svn-remote "repo_id"]
4887                 # instead of creating a(n ugly) new section:
4888                 my $repo_id = $root_repos->{$url} || $url;
4889
4890                 my $fetch = $new_urls->{$url};
4891                 foreach my $path (keys %$fetch) {
4892                         my $x = $fetch->{$path};
4893                         Git::SVN->init($url, $path, $repo_id, $x->{ref_id});
4894                         my $pfx = "svn-remote.$x->{old_repo_id}";
4895
4896                         my $old_fetch = quotemeta("$x->{old_path}:".
4897                                                   "refs/remotes/$x->{ref_id}");
4898                         command_noisy(qw/config --unset/,
4899                                       "$pfx.fetch", '^'. $old_fetch . '$');
4900                         delete $r->{$x->{old_repo_id}}->
4901                                {fetch}->{$x->{old_path}};
4902                         if (!keys %{$r->{$x->{old_repo_id}}->{fetch}}) {
4903                                 command_noisy(qw/config --unset/,
4904                                               "$pfx.url");
4905                                 push @emptied, $x->{old_repo_id}
4906                         }
4907                 }
4908         }
4909         if (@emptied) {
4910                 my $file = $ENV{GIT_CONFIG} || $ENV{GIT_CONFIG_LOCAL} ||
4911                            "$ENV{GIT_DIR}/config";
4912                 print STDERR <<EOF;
4913 The following [svn-remote] sections in your config file ($file) are empty
4914 and can be safely removed:
4915 EOF
4916                 print STDERR "[svn-remote \"$_\"]\n" foreach @emptied;
4917         }
4918 }
4919
4920 sub migration_check {
4921         migrate_from_v0();
4922         migrate_from_v1();
4923         migrate_from_v2();
4924         minimize_connections() if $_minimize;
4925 }
4926
4927 package Git::IndexInfo;
4928 use strict;
4929 use warnings;
4930 use Git qw/command_input_pipe command_close_pipe/;
4931
4932 sub new {
4933         my ($class) = @_;
4934         my ($gui, $ctx) = command_input_pipe(qw/update-index -z --index-info/);
4935         bless { gui => $gui, ctx => $ctx, nr => 0}, $class;
4936 }
4937
4938 sub remove {
4939         my ($self, $path) = @_;
4940         if (print { $self->{gui} } '0 ', 0 x 40, "\t", $path, "\0") {
4941                 return ++$self->{nr};
4942         }
4943         undef;
4944 }
4945
4946 sub update {
4947         my ($self, $mode, $hash, $path) = @_;
4948         if (print { $self->{gui} } $mode, ' ', $hash, "\t", $path, "\0") {
4949                 return ++$self->{nr};
4950         }
4951         undef;
4952 }
4953
4954 sub DESTROY {
4955         my ($self) = @_;
4956         command_close_pipe($self->{gui}, $self->{ctx});
4957 }
4958
4959 package Git::SVN::GlobSpec;
4960 use strict;
4961 use warnings;
4962
4963 sub new {
4964         my ($class, $glob) = @_;
4965         my $re = $glob;
4966         $re =~ s!/+$!!g; # no need for trailing slashes
4967         $re =~ m!^([^*]*)(\*(?:/\*)*)([^*]*)$!;
4968         my $temp = $re;
4969         my ($left, $right) = ($1, $3);
4970         $re = $2;
4971         my $depth = $re =~ tr/*/*/;
4972         if ($depth != $temp =~ tr/*/*/) {
4973                 die "Only one set of wildcard directories " .
4974                         "(e.g. '*' or '*/*/*') is supported: '$glob'\n";
4975         }
4976         if ($depth == 0) {
4977                 die "One '*' is needed for glob: '$glob'\n";
4978         }
4979         $re =~ s!\*!\[^/\]*!g;
4980         $re = quotemeta($left) . "($re)" . quotemeta($right);
4981         if (length $left && !($left =~ s!/+$!!g)) {
4982                 die "Missing trailing '/' on left side of: '$glob' ($left)\n";
4983         }
4984         if (length $right && !($right =~ s!^/+!!g)) {
4985                 die "Missing leading '/' on right side of: '$glob' ($right)\n";
4986         }
4987         my $left_re = qr/^\/\Q$left\E(\/|$)/;
4988         bless { left => $left, right => $right, left_regex => $left_re,
4989                 regex => qr/$re/, glob => $glob, depth => $depth }, $class;
4990 }
4991
4992 sub full_path {
4993         my ($self, $path) = @_;
4994         return (length $self->{left} ? "$self->{left}/" : '') .
4995                $path . (length $self->{right} ? "/$self->{right}" : '');
4996 }
4997
4998 __END__
4999
5000 Data structures:
5001
5002
5003 $remotes = { # returned by read_all_remotes()
5004         'svn' => {
5005                 # svn-remote.svn.url=https://svn.musicpd.org
5006                 url => 'https://svn.musicpd.org',
5007                 # svn-remote.svn.fetch=mpd/trunk:trunk
5008                 fetch => {
5009                         'mpd/trunk' => 'trunk',
5010                 },
5011                 # svn-remote.svn.tags=mpd/tags/*:tags/*
5012                 tags => {
5013                         path => {
5014                                 left => 'mpd/tags',
5015                                 right => '',
5016                                 regex => qr!mpd/tags/([^/]+)$!,
5017                                 glob => 'tags/*',
5018                         },
5019                         ref => {
5020                                 left => 'tags',
5021                                 right => '',
5022                                 regex => qr!tags/([^/]+)$!,
5023                                 glob => 'tags/*',
5024                         },
5025                 }
5026         }
5027 };
5028
5029 $log_entry hashref as returned by libsvn_log_entry()
5030 {
5031         log => 'whitespace-formatted log entry
5032 ',                                              # trailing newline is preserved
5033         revision => '8',                        # integer
5034         date => '2004-02-24T17:01:44.108345Z',  # commit date
5035         author => 'committer name'
5036 };
5037
5038
5039 # this is generated by generate_diff();
5040 @mods = array of diff-index line hashes, each element represents one line
5041         of diff-index output
5042
5043 diff-index line ($m hash)
5044 {
5045         mode_a => first column of diff-index output, no leading ':',
5046         mode_b => second column of diff-index output,
5047         sha1_b => sha1sum of the final blob,
5048         chg => change type [MCRADT],
5049         file_a => original file name of a file (iff chg is 'C' or 'R')
5050         file_b => new/current file name of a file (any chg)
5051 }
5052 ;
5053
5054 # retval of read_url_paths{,_all}();
5055 $l_map = {
5056         # repository root url
5057         'https://svn.musicpd.org' => {
5058                 # repository path               # GIT_SVN_ID
5059                 'mpd/trunk'             =>      'trunk',
5060                 'mpd/tags/0.11.5'       =>      'tags/0.11.5',
5061         },
5062 }
5063
5064 Notes:
5065         I don't trust the each() function on unless I created %hash myself
5066         because the internal iterator may not have started at base.