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