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