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