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