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