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