git-svn: moved the 'log' command into its own namespace
[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                 $SVN_URL
8                 $GIT_SVN_INDEX $GIT_SVN
9                 $GIT_DIR $GIT_SVN_DIR $REVDB
10                 $_follow_parent $sha1 $sha1_short/;
11 $AUTHOR = 'Eric Wong <normalperson@yhbt.net>';
12 $VERSION = '@@GIT_VERSION@@';
13
14 use Cwd qw/abs_path/;
15 $GIT_DIR = abs_path($ENV{GIT_DIR} || '.git');
16 $ENV{GIT_DIR} = $GIT_DIR;
17
18 my $LC_ALL = $ENV{LC_ALL};
19 $Git::SVN::Log::TZ = $ENV{TZ};
20 # make sure the svn binary gives consistent output between locales and TZs:
21 $ENV{TZ} = 'UTC';
22 $ENV{LC_ALL} = 'C';
23 $| = 1; # unbuffer STDOUT
24
25 # properties that we do not log:
26 my %SKIP = ( 'svn:wc:ra_dav:version-url' => 1,
27              'svn:special' => 1,
28              'svn:executable' => 1,
29              'svn:entry:committed-rev' => 1,
30              'svn:entry:last-author' => 1,
31              'svn:entry:uuid' => 1,
32              'svn:entry:committed-date' => 1,
33 );
34
35 sub fatal (@) { print STDERR @_; exit 1 }
36 require SVN::Core; # use()-ing this causes segfaults for me... *shrug*
37 require SVN::Ra;
38 require SVN::Delta;
39 if ($SVN::Core::VERSION lt '1.1.0') {
40         fatal "Need SVN::Core 1.1.0 or better (got $SVN::Core::VERSION)\n";
41 }
42 push @Git::SVN::Ra::ISA, 'SVN::Ra';
43 push @SVN::Git::Editor::ISA, 'SVN::Delta::Editor';
44 push @SVN::Git::Fetcher::ISA, 'SVN::Delta::Editor';
45 use Carp qw/croak/;
46 use IO::File qw//;
47 use File::Basename qw/dirname basename/;
48 use File::Path qw/mkpath/;
49 use Getopt::Long qw/:config gnu_getopt no_ignore_case auto_abbrev pass_through/;
50 use IPC::Open3;
51 use Memoize;
52 use Git;
53 memoize('revisions_eq');
54 memoize('cmt_metadata');
55 memoize('get_commit_time');
56
57 BEGIN {
58         my $s;
59         foreach (qw/command command_oneline command_noisy command_output_pipe
60                     command_input_pipe command_close_pipe/) {
61                 $s .= "*SVN::Git::Editor::$_ = *SVN::Git::Fetcher::$_ = ".
62                       "*Git::SVN::Log::$_ = *Git::SVN::$_ = *$_ = *Git::$_; ";
63         }
64         eval $s;
65 }
66
67 my ($SVN);
68
69 my $_optimize_commits = 1 unless $ENV{GIT_SVN_NO_OPTIMIZE_COMMITS};
70 $sha1 = qr/[a-f\d]{40}/;
71 $sha1_short = qr/[a-f\d]{4,40}/;
72 my ($_revision,$_stdin,$_help,$_rmdir,$_edit,
73         $_find_copies_harder, $_l, $_cp_similarity, $_cp_remote,
74         $_repack, $_repack_nr, $_repack_flags, $_q,
75         $_message, $_file, $_no_metadata,
76         $_template, $_shared, $_no_default_regex, $_no_graft_copy,
77         $_version, $_upgrade, $_authors, $_branch_all_refs, @_opt_m,
78         $_merge, $_strategy, $_dry_run,
79         $_prefix);
80 my (@_branch_from, %tree_map, %users);
81 my @repo_path_split_cache;
82
83 my %fc_opts = ( 'branch|b=s' => \@_branch_from,
84                 'follow-parent|follow' => \$_follow_parent,
85                 'branch-all-refs|B' => \$_branch_all_refs,
86                 'authors-file|A=s' => \$_authors,
87                 'repack:i' => \$_repack,
88                 'no-metadata' => \$_no_metadata,
89                 'quiet|q' => \$_q,
90                 'username=s' => \$Git::SVN::Prompt::_username,
91                 'config-dir=s' => \$Git::SVN::Ra::config_dir,
92                 'no-auth-cache' => \$Git::SVN::Prompt::_no_auth_cache,
93                 'repack-flags|repack-args|repack-opts=s' => \$_repack_flags);
94
95 my ($_trunk, $_tags, $_branches);
96 my %multi_opts = ( 'trunk|T=s' => \$_trunk,
97                 'tags|t=s' => \$_tags,
98                 'branches|b=s' => \$_branches );
99 my %init_opts = ( 'template=s' => \$_template, 'shared' => \$_shared );
100 my %cmt_opts = ( 'edit|e' => \$_edit,
101                 'rmdir' => \$_rmdir,
102                 'find-copies-harder' => \$_find_copies_harder,
103                 'l=i' => \$_l,
104                 'copy-similarity|C=i'=> \$_cp_similarity
105 );
106
107 my %cmd = (
108         fetch => [ \&cmd_fetch, "Download new revisions from SVN",
109                         { 'revision|r=s' => \$_revision, %fc_opts } ],
110         init => [ \&cmd_init, "Initialize a repo for tracking" .
111                           " (requires URL argument)",
112                           \%init_opts ],
113         dcommit => [ \&dcommit, 'Commit several diffs to merge with upstream',
114                         { 'merge|m|M' => \$_merge,
115                           'strategy|s=s' => \$_strategy,
116                           'dry-run|n' => \$_dry_run,
117                         %cmt_opts, %fc_opts } ],
118         'set-tree' => [ \&commit, "Set an SVN repository to a git tree-ish",
119                         {       'stdin|' => \$_stdin, %cmt_opts, %fc_opts, } ],
120         'show-ignore' => [ \&cmd_show_ignore, "Show svn:ignore listings",
121                         { 'revision|r=i' => \$_revision } ],
122         rebuild => [ \&rebuild, "Rebuild git-svn metadata (after git clone)",
123                         { 'copy-remote|remote=s' => \$_cp_remote,
124                           'upgrade' => \$_upgrade } ],
125         'graft-branches' => [ \&graft_branches,
126                         'Detect merges/branches from already imported history',
127                         { 'merge-rx|m' => \@_opt_m,
128                           'branch|b=s' => \@_branch_from,
129                           'branch-all-refs|B' => \$_branch_all_refs,
130                           'no-default-regex' => \$_no_default_regex,
131                           'no-graft-copy' => \$_no_graft_copy } ],
132         'multi-init' => [ \&cmd_multi_init,
133                         'Initialize multiple trees (like git-svnimport)',
134                         { %multi_opts, %init_opts,
135                          'revision|r=i' => \$_revision,
136                          'username=s' => \$Git::SVN::Prompt::_username,
137                          'config-dir=s' => \$Git::SVN::Ra::config_dir,
138                          'no-auth-cache' => \$Git::SVN::Prompt::_no_auth_cache,
139                          'prefix=s' => \$_prefix,
140                         } ],
141         'multi-fetch' => [ \&multi_fetch,
142                         'Fetch multiple trees (like git-svnimport)',
143                         \%fc_opts ],
144         'log' => [ \&Git::SVN::Log::cmd_show_log, 'Show commit logs',
145                         { 'limit=i' => \$Git::SVN::Log::limit,
146                           'revision|r=s' => \$_revision,
147                           'verbose|v' => \$Git::SVN::Log::verbose,
148                           'incremental' => \$Git::SVN::Log::incremental,
149                           'oneline' => \$Git::SVN::Log::oneline,
150                           'show-commit' => \$Git::SVN::Log::show_commit,
151                           'non-recursive' => \$Git::SVN::Log::non_recursive,
152                           'authors-file|A=s' => \$_authors,
153                           'color' => \$Git::SVN::Log::color,
154                           'pager=s' => \$Git::SVN::Log::pager,
155                         } ],
156         'commit-diff' => [ \&commit_diff, 'Commit a diff between two trees',
157                         { 'message|m=s' => \$_message,
158                           'file|F=s' => \$_file,
159                           'revision|r=s' => \$_revision,
160                         %cmt_opts } ],
161 );
162
163 my $cmd;
164 for (my $i = 0; $i < @ARGV; $i++) {
165         if (defined $cmd{$ARGV[$i]}) {
166                 $cmd = $ARGV[$i];
167                 splice @ARGV, $i, 1;
168                 last;
169         }
170 };
171
172 my %opts = %{$cmd{$cmd}->[2]} if (defined $cmd);
173
174 read_repo_config(\%opts);
175 my $rv = GetOptions(%opts, 'help|H|h' => \$_help,
176                                 'version|V' => \$_version,
177                                 'id|i=s' => \$GIT_SVN);
178 exit 1 if (!$rv && $cmd ne 'log');
179
180 set_default_vals();
181 usage(0) if $_help;
182 version() if $_version;
183 usage(1) unless defined $cmd;
184 init_vars();
185 load_authors() if $_authors;
186 load_all_refs() if $_branch_all_refs;
187 migration_check() unless $cmd =~ /^(?:init|rebuild|multi-init|commit-diff)$/;
188 $cmd{$cmd}->[0]->(@ARGV);
189 exit 0;
190
191 ####################### primary functions ######################
192 sub usage {
193         my $exit = shift || 0;
194         my $fd = $exit ? \*STDERR : \*STDOUT;
195         print $fd <<"";
196 git-svn - bidirectional operations between a single Subversion tree and git
197 Usage: $0 <command> [options] [arguments]\n
198
199         print $fd "Available commands:\n" unless $cmd;
200
201         foreach (sort keys %cmd) {
202                 next if $cmd && $cmd ne $_;
203                 print $fd '  ',pack('A17',$_),$cmd{$_}->[1],"\n";
204                 foreach (keys %{$cmd{$_}->[2]}) {
205                         # prints out arguments as they should be passed:
206                         my $x = s#[:=]s$## ? '<arg>' : s#[:=]i$## ? '<num>' : '';
207                         print $fd ' ' x 21, join(', ', map { length $_ > 1 ?
208                                                         "--$_" : "-$_" }
209                                                 split /\|/,$_)," $x\n";
210                 }
211         }
212         print $fd <<"";
213 \nGIT_SVN_ID may be set in the environment or via the --id/-i switch to an
214 arbitrary identifier if you're tracking multiple SVN branches/repositories in
215 one git repository and want to keep them separate.  See git-svn(1) for more
216 information.
217
218         exit $exit;
219 }
220
221 sub version {
222         print "git-svn version $VERSION (svn $SVN::Core::VERSION)\n";
223         exit 0;
224 }
225
226 sub rebuild {
227         if (!verify_ref("refs/remotes/$GIT_SVN^0")) {
228                 copy_remote_ref();
229         }
230         $SVN_URL = shift or undef;
231         my $newest_rev = 0;
232         if ($_upgrade) {
233                 command_noisy('update-ref',"refs/remotes/$GIT_SVN","
234                               $GIT_SVN-HEAD");
235         } else {
236                 check_upgrade_needed();
237         }
238
239         my ($rev_list, $ctx) = command_output_pipe("rev-list",
240                                                    "refs/remotes/$GIT_SVN");
241         my $latest;
242         my $svn_uuid;
243         while (<$rev_list>) {
244                 chomp;
245                 my $c = $_;
246                 croak "Non-SHA1: $c\n" unless $c =~ /^$sha1$/o;
247                 my @commit = grep(/^git-svn-id: /,
248                                   command(qw/cat-file commit/, $c));
249                 next if (!@commit); # skip merges
250                 my ($url, $rev, $uuid) = extract_metadata($commit[$#commit]);
251                 if (!defined $rev || !$uuid) {
252                         croak "Unable to extract revision or UUID from ",
253                                 "$c, $commit[$#commit]\n";
254                 }
255
256                 # if we merged or otherwise started elsewhere, this is
257                 # how we break out of it
258                 next if (defined $svn_uuid && ($uuid ne $svn_uuid));
259                 next if (defined $SVN_URL && defined $url && ($url ne $SVN_URL));
260
261                 unless (defined $latest) {
262                         if (!$SVN_URL && !$url) {
263                                 croak "SVN repository location required: $url\n";
264                         }
265                         $SVN_URL ||= $url;
266                         $svn_uuid ||= $uuid;
267                         setup_git_svn();
268                         $latest = $rev;
269                 }
270                 revdb_set($REVDB, $rev, $c);
271                 print "r$rev = $c\n";
272                 $newest_rev = $rev if ($rev > $newest_rev);
273         }
274         command_close_pipe($rev_list, $ctx);
275 }
276
277 sub do_git_init_db {
278         unless (-d $ENV{GIT_DIR}) {
279                 my @init_db = ('init');
280                 push @init_db, "--template=$_template" if defined $_template;
281                 push @init_db, "--shared" if defined $_shared;
282                 command_noisy(@init_db);
283         }
284 }
285
286 sub cmd_init {
287         my $url = shift or die "SVN repository location required " .
288                                 "as a command-line argument\n";
289         if (my $repo_path = shift) {
290                 unless (-d $repo_path) {
291                         mkpath([$repo_path]);
292                 }
293                 chdir $repo_path or croak $!;
294                 $ENV{GIT_DIR} = $repo_path . "/.git";
295         }
296         do_git_init_db();
297
298         Git::SVN->init(undef, $url);
299 }
300
301 sub cmd_fetch {
302         fetch_child_id($GIT_SVN, @_);
303 }
304
305 sub fetch {
306         check_upgrade_needed();
307         $SVN_URL ||= file_to_s("$GIT_SVN_DIR/info/url");
308         my $ret = fetch_lib(@_);
309         if ($ret->{commit} && !verify_ref('refs/heads/master^0')) {
310                 command_noisy(qw(update-ref refs/heads/master),$ret->{commit});
311         }
312         return $ret;
313 }
314
315 sub fetch_lib {
316         my (@parents) = @_;
317         $SVN_URL ||= file_to_s("$GIT_SVN_DIR/info/url");
318         $SVN ||= Git::SVN::Ra->new($SVN_URL);
319         my ($last_rev, $last_commit) = svn_grab_base_rev();
320         my ($base, $head) = libsvn_parse_revision($last_rev);
321         if ($base > $head) {
322                 return { revision => $last_rev, commit => $last_commit }
323         }
324         my $index = set_index($GIT_SVN_INDEX);
325
326         # limit ourselves and also fork() since get_log won't release memory
327         # after processing a revision and SVN stuff seems to leak
328         my $inc = 1000;
329         my ($min, $max) = ($base, $head < $base+$inc ? $head : $base+$inc);
330         if (defined $last_commit) {
331                 unless (-e $GIT_SVN_INDEX) {
332                         command_noisy('read-tree', $last_commit);
333                 }
334                 my $x = command_oneline('write-tree');
335                 my ($y) = (command(qw/cat-file commit/, $last_commit)
336                                                         =~ /^tree ($sha1)/m);
337                 if ($y ne $x) {
338                         unlink $GIT_SVN_INDEX or croak $!;
339                         command_noisy('read-tree', $last_commit);
340                 }
341                 $x = command_oneline('write-tree');
342                 if ($y ne $x) {
343                         print STDERR "trees ($last_commit) $y != $x\n",
344                                  "Something is seriously wrong...\n";
345                 }
346         }
347         while (1) {
348                 # fork, because using SVN::Pool with get_log() still doesn't
349                 # seem to help enough to keep memory usage down.
350                 defined(my $pid = fork) or croak $!;
351                 if (!$pid) {
352                         $SVN::Error::handler = \&libsvn_skip_unknown_revs;
353
354                         # Yes I'm perfectly aware that the fourth argument
355                         # below is the limit revisions number.  Unfortunately
356                         # performance sucks with it enabled, so it's much
357                         # faster to fetch revision ranges instead of relying
358                         # on the limiter.
359                         $SVN->dup->get_log([''], $min, $max, 0, 1, 1,
360                                 sub {
361                                         my $log_msg;
362                                         if ($last_commit) {
363                                                 $log_msg = libsvn_fetch(
364                                                         $last_commit, @_);
365                                                 $last_commit = git_commit(
366                                                         $log_msg,
367                                                         $last_commit,
368                                                         @parents);
369                                         } else {
370                                                 $log_msg = libsvn_new_tree(@_);
371                                                 $last_commit = git_commit(
372                                                         $log_msg, @parents);
373                                         }
374                                 });
375                         exit 0;
376                 }
377                 waitpid $pid, 0;
378                 croak $? if $?;
379                 ($last_rev, $last_commit) = svn_grab_base_rev();
380                 last if ($max >= $head);
381                 $min = $max + 1;
382                 $max += $inc;
383                 $max = $head if ($max > $head);
384                 $SVN = Git::SVN::Ra->new($SVN_URL);
385         }
386         restore_index($index);
387         return { revision => $last_rev, commit => $last_commit };
388 }
389
390 sub commit {
391         my (@commits) = @_;
392         check_upgrade_needed();
393         if ($_stdin || !@commits) {
394                 print "Reading from stdin...\n";
395                 @commits = ();
396                 while (<STDIN>) {
397                         if (/\b($sha1_short)\b/o) {
398                                 unshift @commits, $1;
399                         }
400                 }
401         }
402         my @revs;
403         foreach my $c (@commits) {
404                 my @tmp = command('rev-parse',$c);
405                 if (scalar @tmp == 1) {
406                         push @revs, $tmp[0];
407                 } elsif (scalar @tmp > 1) {
408                         push @revs, reverse(command('rev-list',@tmp));
409                 } else {
410                         die "Failed to rev-parse $c\n";
411                 }
412         }
413         commit_lib(@revs);
414         print "Done committing ",scalar @revs," revisions to SVN\n";
415 }
416
417 sub commit_lib {
418         my (@revs) = @_;
419         my ($r_last, $cmt_last) = svn_grab_base_rev();
420         defined $r_last or die "Must have an existing revision to commit\n";
421         my $fetched = fetch();
422         if ($r_last != $fetched->{revision}) {
423                 print STDERR "There are new revisions that were fetched ",
424                                 "and need to be merged (or acknowledged) ",
425                                 "before committing.\n",
426                                 "last rev: $r_last\n",
427                                 " current: $fetched->{revision}\n";
428                 exit 1;
429         }
430         my $commit_msg = "$GIT_SVN_DIR/.svn-commit.tmp.$$";
431
432         my $repo;
433         set_svn_commit_env();
434         foreach my $c (@revs) {
435                 my $log_msg = get_commit_message($c, $commit_msg);
436
437                 # fork for each commit because there's a memory leak I
438                 # can't track down... (it's probably in the SVN code)
439                 defined(my $pid = open my $fh, '-|') or croak $!;
440                 if (!$pid) {
441                         my $pool = SVN::Pool->new;
442                         my $ed = SVN::Git::Editor->new(
443                                         {       r => $r_last,
444                                                 ra => $SVN->dup,
445                                                 c => $c,
446                                                 svn_path => $SVN->{svn_path},
447                                         },
448                                         $SVN->get_commit_editor(
449                                                 $log_msg->{msg},
450                                                 sub {
451                                                         libsvn_commit_cb(
452                                                                 @_, $c,
453                                                                 $log_msg->{msg},
454                                                                 $r_last,
455                                                                 $cmt_last)
456                                                 }, $pool)
457                                         );
458                         my $mods = libsvn_checkout_tree($cmt_last, $c, $ed);
459                         if (@$mods == 0) {
460                                 print "No changes\nr$r_last = $cmt_last\n";
461                                 $ed->abort_edit;
462                         } else {
463                                 $ed->close_edit;
464                         }
465                         $pool->clear;
466                         exit 0;
467                 }
468                 my ($r_new, $cmt_new, $no);
469                 while (<$fh>) {
470                         print $_;
471                         chomp;
472                         if (/^r(\d+) = ($sha1)$/o) {
473                                 ($r_new, $cmt_new) = ($1, $2);
474                         } elsif ($_ eq 'No changes') {
475                                 $no = 1;
476                         }
477                 }
478                 close $fh or exit 1;
479                 if (! defined $r_new && ! defined $cmt_new) {
480                         unless ($no) {
481                                 die "Failed to parse revision information\n";
482                         }
483                 } else {
484                         ($r_last, $cmt_last) = ($r_new, $cmt_new);
485                 }
486         }
487         $ENV{LC_ALL} = 'C';
488         unlink $commit_msg;
489 }
490
491 sub dcommit {
492         my $head = shift || 'HEAD';
493         my $gs = "refs/remotes/$GIT_SVN";
494         my @refs = command(qw/rev-list --no-merges/, "$gs..$head");
495         my $last_rev;
496         foreach my $d (reverse @refs) {
497                 if (!verify_ref("$d~1")) {
498                         die "Commit $d\n",
499                             "has no parent commit, and therefore ",
500                             "nothing to diff against.\n",
501                             "You should be working from a repository ",
502                             "originally created by git-svn\n";
503                 }
504                 unless (defined $last_rev) {
505                         (undef, $last_rev, undef) = cmt_metadata("$d~1");
506                         unless (defined $last_rev) {
507                                 die "Unable to extract revision information ",
508                                     "from commit $d~1\n";
509                         }
510                 }
511                 if ($_dry_run) {
512                         print "diff-tree $d~1 $d\n";
513                 } else {
514                         if (my $r = commit_diff("$d~1", $d, undef, $last_rev)) {
515                                 $last_rev = $r;
516                         } # else: no changes, same $last_rev
517                 }
518         }
519         return if $_dry_run;
520         fetch();
521         my @diff = command('diff-tree', 'HEAD', $gs, '--');
522         my @finish;
523         if (@diff) {
524                 @finish = qw/rebase/;
525                 push @finish, qw/--merge/ if $_merge;
526                 push @finish, "--strategy=$_strategy" if $_strategy;
527                 print STDERR "W: HEAD and $gs differ, using @finish:\n", @diff;
528         } else {
529                 print "No changes between current HEAD and $gs\n",
530                       "Resetting to the latest $gs\n";
531                 @finish = qw/reset --mixed/;
532         }
533         command_noisy(@finish, $gs);
534 }
535
536 sub cmd_show_ignore {
537         my $gs = Git::SVN->new;
538         my $r = (defined $_revision ? $_revision : $gs->ra->get_latest_revnum);
539         $gs->traverse_ignore(\*STDOUT, '', $r);
540 }
541
542 sub graft_branches {
543         my $gr_file = "$GIT_DIR/info/grafts";
544         my ($grafts, $comments) = read_grafts($gr_file);
545         my $gr_sha1;
546
547         if (%$grafts) {
548                 # temporarily disable our grafts file to make this idempotent
549                 chomp($gr_sha1 = command(qw/hash-object -w/,$gr_file));
550                 rename $gr_file, "$gr_file~$gr_sha1" or croak $!;
551         }
552
553         my $l_map = read_url_paths();
554         my @re = map { qr/$_/is } @_opt_m if @_opt_m;
555         unless ($_no_default_regex) {
556                 push @re, (qr/\b(?:merge|merging|merged)\s+with\s+([\w\.\-]+)/i,
557                         qr/\b(?:merge|merging|merged)\s+([\w\.\-]+)/i,
558                         qr/\b(?:from|of)\s+([\w\.\-]+)/i );
559         }
560         foreach my $u (keys %$l_map) {
561                 if (@re) {
562                         foreach my $p (keys %{$l_map->{$u}}) {
563                                 graft_merge_msg($grafts,$l_map,$u,$p,@re);
564                         }
565                 }
566                 unless ($_no_graft_copy) {
567                         graft_file_copy_lib($grafts,$l_map,$u);
568                 }
569         }
570         graft_tree_joins($grafts);
571
572         write_grafts($grafts, $comments, $gr_file);
573         unlink "$gr_file~$gr_sha1" if $gr_sha1;
574 }
575
576 sub cmd_multi_init {
577         my $url = shift;
578         unless (defined $_trunk || defined $_branches || defined $_tags) {
579                 usage(1);
580         }
581         do_git_init_db();
582         $_prefix = '' unless defined $_prefix;
583         if (defined $_trunk) {
584                 my $gs_trunk = eval { Git::SVN->new($_prefix . 'trunk') };
585                 unless ($gs_trunk) {
586                         my $trunk_url = complete_svn_url($url, $_trunk);
587                         $gs_trunk = Git::SVN->init($_prefix . 'trunk',
588                                                    $trunk_url);
589                         command_noisy('config', 'svn.trunk', $trunk_url);
590                 }
591         }
592         my $ra = $url ? Git::SVN::Ra->new($url) : undef;
593         complete_url_ls_init($ra, $_branches, '--branches/-b', $_prefix);
594         complete_url_ls_init($ra, $_tags, '--tags/-t', $_prefix . 'tags/');
595 }
596
597 sub multi_fetch {
598         # try to do trunk first, since branches/tags
599         # may be descended from it.
600         if (-e "$GIT_DIR/svn/trunk/info/url") {
601                 fetch_child_id('trunk', @_);
602         }
603         rec_fetch('', "$GIT_DIR/svn", @_);
604 }
605
606 sub commit_diff_usage {
607         print STDERR "Usage: $0 commit-diff <tree-ish> <tree-ish> [<URL>]\n";
608         exit 1
609 }
610
611 sub commit_diff {
612         my $ta = shift or commit_diff_usage();
613         my $tb = shift or commit_diff_usage();
614         if (!eval { $SVN_URL = shift || file_to_s("$GIT_SVN_DIR/info/url") }) {
615                 print STDERR "Needed URL or usable git-svn id command-line\n";
616                 commit_diff_usage();
617         }
618         my $r = shift;
619         unless (defined $r) {
620                 if (defined $_revision) {
621                         $r = $_revision
622                 } else {
623                         die "-r|--revision is a required argument\n";
624                 }
625         }
626         if (defined $_message && defined $_file) {
627                 print STDERR "Both --message/-m and --file/-F specified ",
628                                 "for the commit message.\n",
629                                 "I have no idea what you mean\n";
630                 exit 1;
631         }
632         if (defined $_file) {
633                 $_message = file_to_s($_file);
634         } else {
635                 $_message ||= get_commit_message($tb,
636                                         "$GIT_DIR/.svn-commit.tmp.$$")->{msg};
637         }
638         $SVN ||= Git::SVN::Ra->new($SVN_URL);
639         if ($r eq 'HEAD') {
640                 $r = $SVN->get_latest_revnum;
641         } elsif ($r !~ /^\d+$/) {
642                 die "revision argument: $r not understood by git-svn\n";
643         }
644         my $rev_committed;
645         my $pool = SVN::Pool->new;
646         my $ed = SVN::Git::Editor->new({        r => $r,
647                                                 ra => $SVN->dup,
648                                                 c => $tb,
649                                                 svn_path => $SVN->{svn_path}
650                                         },
651                                 $SVN->get_commit_editor($_message,
652                                         sub {
653                                                 $rev_committed = $_[0];
654                                                 print "Committed $_[0]\n";
655                                         },
656                                         $pool)
657                                 );
658         eval {
659                 my $mods = libsvn_checkout_tree($ta, $tb, $ed);
660                 if (@$mods == 0) {
661                         print "No changes\n$ta == $tb\n";
662                         $ed->abort_edit;
663                 } else {
664                         $ed->close_edit;
665                 }
666         };
667         $pool->clear;
668         fatal "$@\n" if $@;
669         $_message = $_file = undef;
670         return $rev_committed;
671 }
672
673 ########################### utility functions #########################
674
675 sub fetch_child_id {
676         my $id = shift;
677         print "Fetching $id\n";
678         my $ref = "$GIT_DIR/refs/remotes/$id";
679         defined(my $pid = open my $fh, '-|') or croak $!;
680         if (!$pid) {
681                 $GIT_SVN = $ENV{GIT_SVN_ID} = $id;
682                 init_vars();
683                 fetch(@_);
684                 exit 0;
685         }
686         while (<$fh>) {
687                 print $_;
688                 check_repack() if (/^r\d+ = $sha1/o);
689         }
690         close $fh or croak $?;
691 }
692
693 sub rec_fetch {
694         my ($pfx, $p, @args) = @_;
695         my @dir;
696         foreach (sort <$p/*>) {
697                 if (-r "$_/info/url") {
698                         $pfx .= '/' if $pfx && $pfx !~ m!/$!;
699                         my $id = $pfx . basename $_;
700                         next if $id eq 'trunk';
701                         fetch_child_id($id, @args);
702                 } elsif (-d $_) {
703                         push @dir, $_;
704                 }
705         }
706         foreach (@dir) {
707                 my $x = $_;
708                 $x =~ s!^\Q$GIT_DIR\E/svn/!!;
709                 rec_fetch($x, $_);
710         }
711 }
712
713 sub complete_svn_url {
714         my ($url, $path) = @_;
715         $path =~ s#/+$##;
716         $url =~ s#/+$## if $url;
717         if ($path !~ m#^[a-z\+]+://#) {
718                 $path = '/' . $path if ($path !~ m#^/#);
719                 if (!defined $url || $url !~ m#^[a-z\+]+://#) {
720                         fatal("E: '$path' is not a complete URL ",
721                               "and a separate URL is not specified\n");
722                 }
723                 $path = $url . $path;
724         }
725         return $path;
726 }
727
728 sub complete_url_ls_init {
729         my ($ra, $path, $switch, $pfx) = @_;
730         unless ($path) {
731                 print STDERR "W: $switch not specified\n";
732                 return;
733         }
734         $path =~ s#/+$##;
735         if ($path =~ m#^[a-z\+]+://#) {
736                 $ra = Git::SVN::Ra->new($path);
737                 $path = '';
738         } else {
739                 $path =~ s#^/+##;
740                 unless ($ra) {
741                         fatal("E: '$path' is not a complete URL ",
742                               "and a separate URL is not specified\n");
743                 }
744         }
745         my $r = defined $_revision ? $_revision : $ra->get_latest_revnum;
746         my ($dirent, undef, undef) = $ra->get_dir($path, $r);
747         my $url = $ra->{url} . (length $path ? "/$path" : '');
748         foreach my $d (sort keys %$dirent) {
749                 next if ($dirent->{$d}->kind != $SVN::Node::dir);
750                 my $u =  "$url/$d";
751                 my $id = "$pfx$d";
752                 my $gs = eval { Git::SVN->new($id) };
753                 # don't try to init already existing refs
754                 unless ($gs) {
755                         print "init $u => $id\n";
756                         Git::SVN->init($id, $u);
757                 }
758         }
759         my ($n) = ($switch =~ /^--(\w+)/);
760         command_noisy('config', "svn.$n", $url);
761 }
762
763 sub common_prefix {
764         my $paths = shift;
765         my %common;
766         foreach (@$paths) {
767                 my @tmp = split m#/#, $_;
768                 my $p = '';
769                 while (my $x = shift @tmp) {
770                         $p .= "/$x";
771                         $common{$p} ||= 0;
772                         $common{$p}++;
773                 }
774         }
775         foreach (sort {length $b <=> length $a} keys %common) {
776                 if ($common{$_} == @$paths) {
777                         return $_;
778                 }
779         }
780         return '';
781 }
782
783 # grafts set here are 'stronger' in that they're based on actual tree
784 # matches, and won't be deleted from merge-base checking in write_grafts()
785 sub graft_tree_joins {
786         my $grafts = shift;
787         map_tree_joins() if (@_branch_from && !%tree_map);
788         return unless %tree_map;
789
790         git_svn_each(sub {
791                 my $i = shift;
792                 my @args = (qw/rev-list --pretty=raw/, "refs/remotes/$i");
793                 my ($fh, $ctx) = command_output_pipe(@args);
794                 while (<$fh>) {
795                         next unless /^commit ($sha1)$/o;
796                         my $c = $1;
797                         my ($t) = (<$fh> =~ /^tree ($sha1)$/o);
798                         next unless $tree_map{$t};
799
800                         my $l;
801                         do {
802                                 $l = readline $fh;
803                         } until ($l =~ /^committer (?:.+) (\d+) ([\-\+]?\d+)$/);
804
805                         my ($s, $tz) = ($1, $2);
806                         if ($tz =~ s/^\+//) {
807                                 $s += tz_to_s_offset($tz);
808                         } elsif ($tz =~ s/^\-//) {
809                                 $s -= tz_to_s_offset($tz);
810                         }
811
812                         my ($url_a, $r_a, $uuid_a) = cmt_metadata($c);
813
814                         foreach my $p (@{$tree_map{$t}}) {
815                                 next if $p eq $c;
816                                 my $mb = eval { command('merge-base', $c, $p) };
817                                 next unless ($@ || $?);
818                                 if (defined $r_a) {
819                                         # see if SVN says it's a relative
820                                         my ($url_b, $r_b, $uuid_b) =
821                                                         cmt_metadata($p);
822                                         next if (defined $url_b &&
823                                                         defined $url_a &&
824                                                         ($url_a eq $url_b) &&
825                                                         ($uuid_a eq $uuid_b));
826                                         if ($uuid_a eq $uuid_b) {
827                                                 if ($r_b < $r_a) {
828                                                         $grafts->{$c}->{$p} = 2;
829                                                         next;
830                                                 } elsif ($r_b > $r_a) {
831                                                         $grafts->{$p}->{$c} = 2;
832                                                         next;
833                                                 }
834                                         }
835                                 }
836                                 my $ct = get_commit_time($p);
837                                 if ($ct < $s) {
838                                         $grafts->{$c}->{$p} = 2;
839                                 } elsif ($ct > $s) {
840                                         $grafts->{$p}->{$c} = 2;
841                                 }
842                                 # what should we do when $ct == $s ?
843                         }
844                 }
845                 command_close_pipe($fh, $ctx);
846         });
847 }
848
849 sub graft_file_copy_lib {
850         my ($grafts, $l_map, $u) = @_;
851         my $tree_paths = $l_map->{$u};
852         my $pfx = common_prefix([keys %$tree_paths]);
853         my ($repo, $path) = repo_path_split($u.$pfx);
854         $SVN = Git::SVN::Ra->new($repo);
855
856         my ($base, $head) = libsvn_parse_revision();
857         my $inc = 1000;
858         my ($min, $max) = ($base, $head < $base+$inc ? $head : $base+$inc);
859         my $eh = $SVN::Error::handler;
860         $SVN::Error::handler = \&libsvn_skip_unknown_revs;
861         while (1) {
862                 $SVN->dup->get_log([$path], $min, $max, 0, 2, 1,
863                         sub {
864                                 libsvn_graft_file_copies($grafts, $tree_paths,
865                                                         $path, @_);
866                         });
867                 last if ($max >= $head);
868                 $min = $max + 1;
869                 $max += $inc;
870                 $max = $head if ($max > $head);
871         }
872         $SVN::Error::handler = $eh;
873 }
874
875 sub process_merge_msg_matches {
876         my ($grafts, $l_map, $u, $p, $c, @matches) = @_;
877         my (@strong, @weak);
878         foreach (@matches) {
879                 # merging with ourselves is not interesting
880                 next if $_ eq $p;
881                 if ($l_map->{$u}->{$_}) {
882                         push @strong, $_;
883                 } else {
884                         push @weak, $_;
885                 }
886         }
887         foreach my $w (@weak) {
888                 last if @strong;
889                 # no exact match, use branch name as regexp.
890                 my $re = qr/\Q$w\E/i;
891                 foreach (keys %{$l_map->{$u}}) {
892                         if (/$re/) {
893                                 push @strong, $l_map->{$u}->{$_};
894                                 last;
895                         }
896                 }
897                 last if @strong;
898                 $w = basename($w);
899                 $re = qr/\Q$w\E/i;
900                 foreach (keys %{$l_map->{$u}}) {
901                         if (/$re/) {
902                                 push @strong, $l_map->{$u}->{$_};
903                                 last;
904                         }
905                 }
906         }
907         my ($rev) = ($c->{m} =~ /^git-svn-id:\s(?:\S+?)\@(\d+)
908                                         \s(?:[a-f\d\-]+)$/xsm);
909         unless (defined $rev) {
910                 ($rev) = ($c->{m} =~/^git-svn-id:\s(\d+)
911                                         \@(?:[a-f\d\-]+)/xsm);
912                 return unless defined $rev;
913         }
914         foreach my $m (@strong) {
915                 my ($r0, $s0) = find_rev_before($rev, $m, 1);
916                 $grafts->{$c->{c}}->{$s0} = 1 if defined $s0;
917         }
918 }
919
920 sub graft_merge_msg {
921         my ($grafts, $l_map, $u, $p, @re) = @_;
922
923         my $x = $l_map->{$u}->{$p};
924         my $rl = rev_list_raw("refs/remotes/$x");
925         while (my $c = next_rev_list_entry($rl)) {
926                 foreach my $re (@re) {
927                         my (@br) = ($c->{m} =~ /$re/g);
928                         next unless @br;
929                         process_merge_msg_matches($grafts,$l_map,$u,$p,$c,@br);
930                 }
931         }
932 }
933
934 sub verify_ref {
935         my ($ref) = @_;
936         eval { command_oneline([ 'rev-parse', '--verify', $ref ],
937                                { STDERR => 0 }); };
938 }
939
940 sub repo_path_split {
941         my $full_url = shift;
942         $full_url =~ s#/+$##;
943
944         foreach (@repo_path_split_cache) {
945                 if ($full_url =~ s#$_##) {
946                         my $u = $1;
947                         $full_url =~ s#^/+##;
948                         return ($u, $full_url);
949                 }
950         }
951         my $tmp = Git::SVN::Ra->new($full_url);
952         return ($tmp->{repos_root}, $tmp->{svn_path});
953 }
954
955 sub setup_git_svn {
956         defined $SVN_URL or croak "SVN repository location required\n";
957         unless (-d $GIT_DIR) {
958                 croak "GIT_DIR=$GIT_DIR does not exist!\n";
959         }
960         mkpath([$GIT_SVN_DIR]);
961         mkpath(["$GIT_SVN_DIR/info"]);
962         open my $fh, '>>',$REVDB or croak $!;
963         close $fh;
964         s_to_file($SVN_URL,"$GIT_SVN_DIR/info/url");
965
966 }
967
968 sub get_tree_from_treeish {
969         my ($treeish) = @_;
970         croak "Not a sha1: $treeish\n" unless $treeish =~ /^$sha1$/o;
971         my $type = command_oneline(qw/cat-file -t/, $treeish);
972         my $expected;
973         while ($type eq 'tag') {
974                 ($treeish, $type) = command(qw/cat-file tag/, $treeish);
975         }
976         if ($type eq 'commit') {
977                 $expected = (grep /^tree /, command(qw/cat-file commit/,
978                                                     $treeish))[0];
979                 ($expected) = ($expected =~ /^tree ($sha1)$/);
980                 die "Unable to get tree from $treeish\n" unless $expected;
981         } elsif ($type eq 'tree') {
982                 $expected = $treeish;
983         } else {
984                 die "$treeish is a $type, expected tree, tag or commit\n";
985         }
986         return $expected;
987 }
988
989 sub get_diff {
990         my ($from, $treeish) = @_;
991         print "diff-tree $from $treeish\n";
992         my @diff_tree = qw(diff-tree -z -r);
993         if ($_cp_similarity) {
994                 push @diff_tree, "-C$_cp_similarity";
995         } else {
996                 push @diff_tree, '-C';
997         }
998         push @diff_tree, '--find-copies-harder' if $_find_copies_harder;
999         push @diff_tree, "-l$_l" if defined $_l;
1000         push @diff_tree, $from, $treeish;
1001         my ($diff_fh, $ctx) = command_output_pipe(@diff_tree);
1002         local $/ = "\0";
1003         my $state = 'meta';
1004         my @mods;
1005         while (<$diff_fh>) {
1006                 chomp $_; # this gets rid of the trailing "\0"
1007                 if ($state eq 'meta' && /^:(\d{6})\s(\d{6})\s
1008                                         $sha1\s($sha1)\s([MTCRAD])\d*$/xo) {
1009                         push @mods, {   mode_a => $1, mode_b => $2,
1010                                         sha1_b => $3, chg => $4 };
1011                         if ($4 =~ /^(?:C|R)$/) {
1012                                 $state = 'file_a';
1013                         } else {
1014                                 $state = 'file_b';
1015                         }
1016                 } elsif ($state eq 'file_a') {
1017                         my $x = $mods[$#mods] or croak "Empty array\n";
1018                         if ($x->{chg} !~ /^(?:C|R)$/) {
1019                                 croak "Error parsing $_, $x->{chg}\n";
1020                         }
1021                         $x->{file_a} = $_;
1022                         $state = 'file_b';
1023                 } elsif ($state eq 'file_b') {
1024                         my $x = $mods[$#mods] or croak "Empty array\n";
1025                         if (exists $x->{file_a} && $x->{chg} !~ /^(?:C|R)$/) {
1026                                 croak "Error parsing $_, $x->{chg}\n";
1027                         }
1028                         if (!exists $x->{file_a} && $x->{chg} =~ /^(?:C|R)$/) {
1029                                 croak "Error parsing $_, $x->{chg}\n";
1030                         }
1031                         $x->{file_b} = $_;
1032                         $state = 'meta';
1033                 } else {
1034                         croak "Error parsing $_\n";
1035                 }
1036         }
1037         command_close_pipe($diff_fh, $ctx);
1038         return \@mods;
1039 }
1040
1041 sub libsvn_checkout_tree {
1042         my ($from, $treeish, $ed) = @_;
1043         my $mods = get_diff($from, $treeish);
1044         return $mods unless (scalar @$mods);
1045         my %o = ( D => 1, R => 0, C => -1, A => 3, M => 3, T => 3 );
1046         foreach my $m (sort { $o{$a->{chg}} <=> $o{$b->{chg}} } @$mods) {
1047                 my $f = $m->{chg};
1048                 if (defined $o{$f}) {
1049                         $ed->$f($m, $_q);
1050                 } else {
1051                         croak "Invalid change type: $f\n";
1052                 }
1053         }
1054         $ed->rmdirs($_q) if $_rmdir;
1055         return $mods;
1056 }
1057
1058 sub get_commit_message {
1059         my ($commit, $commit_msg) = (@_);
1060         my %log_msg = ( msg => '' );
1061         open my $msg, '>', $commit_msg or croak $!;
1062
1063         my $type = command_oneline(qw/cat-file -t/, $commit);
1064         if ($type eq 'commit' || $type eq 'tag') {
1065                 my ($msg_fh, $ctx) = command_output_pipe('cat-file',
1066                                                          $type, $commit);
1067                 my $in_msg = 0;
1068                 while (<$msg_fh>) {
1069                         if (!$in_msg) {
1070                                 $in_msg = 1 if (/^\s*$/);
1071                         } elsif (/^git-svn-id: /) {
1072                                 # skip this, we regenerate the correct one
1073                                 # on re-fetch anyways
1074                         } else {
1075                                 print $msg $_ or croak $!;
1076                         }
1077                 }
1078                 command_close_pipe($msg_fh, $ctx);
1079         }
1080         close $msg or croak $!;
1081
1082         if ($_edit || ($type eq 'tree')) {
1083                 my $editor = $ENV{VISUAL} || $ENV{EDITOR} || 'vi';
1084                 system($editor, $commit_msg);
1085         }
1086
1087         # file_to_s removes all trailing newlines, so just use chomp() here:
1088         open $msg, '<', $commit_msg or croak $!;
1089         { local $/; chomp($log_msg{msg} = <$msg>); }
1090         close $msg or croak $!;
1091
1092         return \%log_msg;
1093 }
1094
1095 sub set_svn_commit_env {
1096         if (defined $LC_ALL) {
1097                 $ENV{LC_ALL} = $LC_ALL;
1098         } else {
1099                 delete $ENV{LC_ALL};
1100         }
1101 }
1102
1103 sub rev_list_raw {
1104         my ($fh, $c) = command_output_pipe(qw/rev-list --pretty=raw/, @_);
1105         return { fh => $fh, ctx => $c, t => { } };
1106 }
1107
1108 sub next_rev_list_entry {
1109         my $rl = shift;
1110         my $fh = $rl->{fh};
1111         my $x = $rl->{t};
1112         while (<$fh>) {
1113                 if (/^commit ($sha1)$/o) {
1114                         if ($x->{c}) {
1115                                 $rl->{t} = { c => $1 };
1116                                 return $x;
1117                         } else {
1118                                 $x->{c} = $1;
1119                         }
1120                 } elsif (/^parent ($sha1)$/o) {
1121                         $x->{p}->{$1} = 1;
1122                 } elsif (s/^    //) {
1123                         $x->{m} ||= '';
1124                         $x->{m} .= $_;
1125                 }
1126         }
1127         command_close_pipe($fh, $rl->{ctx});
1128         return ($x != $rl->{t}) ? $x : undef;
1129 }
1130
1131 sub s_to_file {
1132         my ($str, $file, $mode) = @_;
1133         open my $fd,'>',$file or croak $!;
1134         print $fd $str,"\n" or croak $!;
1135         close $fd or croak $!;
1136         chmod ($mode &~ umask, $file) if (defined $mode);
1137 }
1138
1139 sub file_to_s {
1140         my $file = shift;
1141         open my $fd,'<',$file or croak "$!: file: $file\n";
1142         local $/;
1143         my $ret = <$fd>;
1144         close $fd or croak $!;
1145         $ret =~ s/\s*$//s;
1146         return $ret;
1147 }
1148
1149 sub assert_revision_unknown {
1150         my $r = shift;
1151         if (my $c = revdb_get($REVDB, $r)) {
1152                 croak "$r = $c already exists! Why are we refetching it?";
1153         }
1154 }
1155
1156 sub git_commit {
1157         my ($log_msg, @parents) = @_;
1158         assert_revision_unknown($log_msg->{revision});
1159         map_tree_joins() if (@_branch_from && !%tree_map);
1160
1161         my (@tmp_parents, @exec_parents, %seen_parent);
1162         if (my $lparents = $log_msg->{parents}) {
1163                 @tmp_parents = @$lparents
1164         }
1165         # commit parents can be conditionally bound to a particular
1166         # svn revision via: "svn_revno=commit_sha1", filter them out here:
1167         foreach my $p (@parents) {
1168                 next unless defined $p;
1169                 if ($p =~ /^(\d+)=($sha1_short)$/o) {
1170                         if ($1 == $log_msg->{revision}) {
1171                                 push @tmp_parents, $2;
1172                         }
1173                 } else {
1174                         push @tmp_parents, $p if $p =~ /$sha1_short/o;
1175                 }
1176         }
1177         my $tree = $log_msg->{tree};
1178         if (!defined $tree) {
1179                 my $index = set_index($GIT_SVN_INDEX);
1180                 $tree = command_oneline('write-tree');
1181                 croak $? if $?;
1182                 restore_index($index);
1183         }
1184         # just in case we clobber the existing ref, we still want that ref
1185         # as our parent:
1186         if (my $cur = verify_ref("refs/remotes/$GIT_SVN^0")) {
1187                 chomp $cur;
1188                 push @tmp_parents, $cur;
1189         }
1190
1191         if (exists $tree_map{$tree}) {
1192                 foreach my $p (@{$tree_map{$tree}}) {
1193                         my $skip;
1194                         foreach (@tmp_parents) {
1195                                 # see if a common parent is found
1196                                 my $mb = eval { command('merge-base', $_, $p) };
1197                                 next if ($@ || $?);
1198                                 $skip = 1;
1199                                 last;
1200                         }
1201                         next if $skip;
1202                         my ($url_p, $r_p, $uuid_p) = cmt_metadata($p);
1203                         next if (($SVN->uuid eq $uuid_p) &&
1204                                                 ($log_msg->{revision} > $r_p));
1205                         next if (defined $url_p && defined $SVN_URL &&
1206                                                 ($SVN->uuid eq $uuid_p) &&
1207                                                 ($url_p eq $SVN_URL));
1208                         push @tmp_parents, $p;
1209                 }
1210         }
1211         foreach (@tmp_parents) {
1212                 next if $seen_parent{$_};
1213                 $seen_parent{$_} = 1;
1214                 push @exec_parents, $_;
1215                 # MAXPARENT is defined to 16 in commit-tree.c:
1216                 last if @exec_parents > 16;
1217         }
1218
1219         set_commit_env($log_msg);
1220         my @exec = ('git-commit-tree', $tree);
1221         push @exec, '-p', $_  foreach @exec_parents;
1222         defined(my $pid = open3(my $msg_fh, my $out_fh, '>&STDERR', @exec))
1223                                                                 or croak $!;
1224         print $msg_fh $log_msg->{msg} or croak $!;
1225         unless ($_no_metadata) {
1226                 print $msg_fh "\ngit-svn-id: $SVN_URL\@$log_msg->{revision} ",
1227                                         $SVN->uuid,"\n" or croak $!;
1228         }
1229         $msg_fh->flush == 0 or croak $!;
1230         close $msg_fh or croak $!;
1231         chomp(my $commit = do { local $/; <$out_fh> });
1232         close $out_fh or croak $!;
1233         waitpid $pid, 0;
1234         croak $? if $?;
1235         if ($commit !~ /^$sha1$/o) {
1236                 die "Failed to commit, invalid sha1: $commit\n";
1237         }
1238         command_noisy('update-ref',"refs/remotes/$GIT_SVN",$commit);
1239         revdb_set($REVDB, $log_msg->{revision}, $commit);
1240
1241         # this output is read via pipe, do not change:
1242         print "r$log_msg->{revision} = $commit\n";
1243         return $commit;
1244 }
1245
1246 sub check_repack {
1247         if ($_repack && (--$_repack_nr == 0)) {
1248                 $_repack_nr = $_repack;
1249                 # repack doesn't use any arguments with spaces in them, does it?
1250                 command_noisy('repack', split(/\s+/, $_repack_flags));
1251         }
1252 }
1253
1254 sub set_commit_env {
1255         my ($log_msg) = @_;
1256         my $author = $log_msg->{author};
1257         if (!defined $author || length $author == 0) {
1258                 $author = '(no author)';
1259         }
1260         my ($name,$email) = defined $users{$author} ?  @{$users{$author}}
1261                                 : ($author,$author . '@' . $SVN->uuid);
1262         $ENV{GIT_AUTHOR_NAME} = $ENV{GIT_COMMITTER_NAME} = $name;
1263         $ENV{GIT_AUTHOR_EMAIL} = $ENV{GIT_COMMITTER_EMAIL} = $email;
1264         $ENV{GIT_AUTHOR_DATE} = $ENV{GIT_COMMITTER_DATE} = $log_msg->{date};
1265 }
1266
1267 sub check_upgrade_needed {
1268         if (!-r $REVDB) {
1269                 -d $GIT_SVN_DIR or mkpath([$GIT_SVN_DIR]);
1270                 open my $fh, '>>',$REVDB or croak $!;
1271                 close $fh;
1272         }
1273         return unless eval {
1274                 command([qw/rev-parse --verify/,"$GIT_SVN-HEAD^0"],
1275                         {STDERR => 0});
1276         };
1277         my $head = eval { command('rev-parse',"refs/remotes/$GIT_SVN") };
1278         if ($@ || !$head) {
1279                 print STDERR "Please run: $0 rebuild --upgrade\n";
1280                 exit 1;
1281         }
1282 }
1283
1284 # fills %tree_map with a reverse mapping of trees to commits.  Useful
1285 # for finding parents to commit on.
1286 sub map_tree_joins {
1287         my %seen;
1288         foreach my $br (@_branch_from) {
1289                 my $pipe = command_output_pipe(qw/rev-list
1290                                             --topo-order --pretty=raw/, $br);
1291                 while (<$pipe>) {
1292                         if (/^commit ($sha1)$/o) {
1293                                 my $commit = $1;
1294
1295                                 # if we've seen a commit,
1296                                 # we've seen its parents
1297                                 last if $seen{$commit};
1298                                 my ($tree) = (<$pipe> =~ /^tree ($sha1)$/o);
1299                                 unless (defined $tree) {
1300                                         die "Failed to parse commit $commit\n";
1301                                 }
1302                                 push @{$tree_map{$tree}}, $commit;
1303                                 $seen{$commit} = 1;
1304                         }
1305                 }
1306                 close $pipe;
1307         }
1308 }
1309
1310 sub load_all_refs {
1311         if (@_branch_from) {
1312                 print STDERR '--branch|-b parameters are ignored when ',
1313                         "--branch-all-refs|-B is passed\n";
1314         }
1315
1316         # don't worry about rev-list on non-commit objects/tags,
1317         # it shouldn't blow up if a ref is a blob or tree...
1318         @_branch_from = command(qw/rev-parse --symbolic --all/);
1319 }
1320
1321 # '<svn username> = real-name <email address>' mapping based on git-svnimport:
1322 sub load_authors {
1323         open my $authors, '<', $_authors or die "Can't open $_authors $!\n";
1324         my $log = $cmd eq 'log';
1325         while (<$authors>) {
1326                 chomp;
1327                 next unless /^(\S+?|\(no author\))\s*=\s*(.+?)\s*<(.+)>\s*$/;
1328                 my ($user, $name, $email) = ($1, $2, $3);
1329                 if ($log) {
1330                         $Git::SVN::Log::rusers{"$name <$email>"} = $user;
1331                 } else {
1332                         $users{$user} = [$name, $email];
1333                 }
1334         }
1335         close $authors or croak $!;
1336 }
1337
1338 sub git_svn_each {
1339         my $sub = shift;
1340         foreach (command(qw/rev-parse --symbolic --all/)) {
1341                 next unless s#^refs/remotes/##;
1342                 chomp $_;
1343                 next unless -f "$GIT_DIR/svn/$_/info/url";
1344                 &$sub($_);
1345         }
1346 }
1347
1348 sub migrate_revdb {
1349         git_svn_each(sub {
1350                 my $id = shift;
1351                 defined(my $pid = fork) or croak $!;
1352                 if (!$pid) {
1353                         $GIT_SVN = $ENV{GIT_SVN_ID} = $id;
1354                         init_vars();
1355                         exit 0 if -r $REVDB;
1356                         print "Upgrading svn => git mapping...\n";
1357                         -d $GIT_SVN_DIR or mkpath([$GIT_SVN_DIR]);
1358                         open my $fh, '>>',$REVDB or croak $!;
1359                         close $fh;
1360                         rebuild();
1361                         print "Done upgrading. You may now delete the ",
1362                                 "deprecated $GIT_SVN_DIR/revs directory\n";
1363                         exit 0;
1364                 }
1365                 waitpid $pid, 0;
1366                 croak $? if $?;
1367         });
1368 }
1369
1370 sub migration_check {
1371         migrate_revdb() unless (-e $REVDB);
1372         return if (-d "$GIT_DIR/svn" || !-d $GIT_DIR);
1373         print "Upgrading repository...\n";
1374         unless (-d "$GIT_DIR/svn") {
1375                 mkdir "$GIT_DIR/svn" or croak $!;
1376         }
1377         print "Data from a previous version of git-svn exists, but\n\t",
1378                                 "$GIT_SVN_DIR\n\t(required for this version ",
1379                                 "($VERSION) of git-svn) does not.\n";
1380
1381         foreach my $x (command(qw/rev-parse --symbolic --all/)) {
1382                 next unless $x =~ s#^refs/remotes/##;
1383                 chomp $x;
1384                 next unless -f "$GIT_DIR/$x/info/url";
1385                 my $u = eval { file_to_s("$GIT_DIR/$x/info/url") };
1386                 next unless $u;
1387                 my $dn = dirname("$GIT_DIR/svn/$x");
1388                 mkpath([$dn]) unless -d $dn;
1389                 rename "$GIT_DIR/$x", "$GIT_DIR/svn/$x" or croak "$!: $x";
1390         }
1391         migrate_revdb() if (-d $GIT_SVN_DIR && !-w $REVDB);
1392         print "Done upgrading.\n";
1393 }
1394
1395 sub find_rev_before {
1396         my ($r, $id, $eq_ok) = @_;
1397         my $f = "$GIT_DIR/svn/$id/.rev_db";
1398         return (undef,undef) unless -r $f;
1399         --$r unless $eq_ok;
1400         while ($r > 0) {
1401                 if (my $c = revdb_get($f, $r)) {
1402                         return ($r, $c);
1403                 }
1404                 --$r;
1405         }
1406         return (undef, undef);
1407 }
1408
1409 sub init_vars {
1410         $GIT_SVN ||= $ENV{GIT_SVN_ID} || 'git-svn';
1411         $Git::SVN::default = $GIT_SVN;
1412         $GIT_SVN_DIR = "$GIT_DIR/svn/$GIT_SVN";
1413         $REVDB = "$GIT_SVN_DIR/.rev_db";
1414         $GIT_SVN_INDEX = "$GIT_SVN_DIR/index";
1415         $SVN_URL = undef;
1416         %tree_map = ();
1417 }
1418
1419 # convert GetOpt::Long specs for use by git-config
1420 sub read_repo_config {
1421         return unless -d $GIT_DIR;
1422         my $opts = shift;
1423         foreach my $o (keys %$opts) {
1424                 my $v = $opts->{$o};
1425                 my ($key) = ($o =~ /^([a-z\-]+)/);
1426                 $key =~ s/-//g;
1427                 my $arg = 'git-config';
1428                 $arg .= ' --int' if ($o =~ /[:=]i$/);
1429                 $arg .= ' --bool' if ($o !~ /[:=][sfi]$/);
1430                 if (ref $v eq 'ARRAY') {
1431                         chomp(my @tmp = `$arg --get-all svn.$key`);
1432                         @$v = @tmp if @tmp;
1433                 } else {
1434                         chomp(my $tmp = `$arg --get svn.$key`);
1435                         if ($tmp && !($arg =~ / --bool/ && $tmp eq 'false')) {
1436                                 $$v = $tmp;
1437                         }
1438                 }
1439         }
1440 }
1441
1442 sub set_default_vals {
1443         if (defined $_repack) {
1444                 $_repack = 1000 if ($_repack <= 0);
1445                 $_repack_nr = $_repack;
1446                 $_repack_flags ||= '-d';
1447         }
1448 }
1449
1450 sub read_grafts {
1451         my $gr_file = shift;
1452         my ($grafts, $comments) = ({}, {});
1453         if (open my $fh, '<', $gr_file) {
1454                 my @tmp;
1455                 while (<$fh>) {
1456                         if (/^($sha1)\s+/) {
1457                                 my $c = $1;
1458                                 if (@tmp) {
1459                                         @{$comments->{$c}} = @tmp;
1460                                         @tmp = ();
1461                                 }
1462                                 foreach my $p (split /\s+/, $_) {
1463                                         $grafts->{$c}->{$p} = 1;
1464                                 }
1465                         } else {
1466                                 push @tmp, $_;
1467                         }
1468                 }
1469                 close $fh or croak $!;
1470                 @{$comments->{'END'}} = @tmp if @tmp;
1471         }
1472         return ($grafts, $comments);
1473 }
1474
1475 sub write_grafts {
1476         my ($grafts, $comments, $gr_file) = @_;
1477
1478         open my $fh, '>', $gr_file or croak $!;
1479         foreach my $c (sort keys %$grafts) {
1480                 if ($comments->{$c}) {
1481                         print $fh $_ foreach @{$comments->{$c}};
1482                 }
1483                 my $p = $grafts->{$c};
1484                 my %x; # real parents
1485                 delete $p->{$c}; # commits are not self-reproducing...
1486                 my $ch = command_output_pipe(qw/cat-file commit/, $c);
1487                 while (<$ch>) {
1488                         if (/^parent ($sha1)/) {
1489                                 $x{$1} = $p->{$1} = 1;
1490                         } else {
1491                                 last unless /^\S/;
1492                         }
1493                 }
1494                 close $ch; # breaking the pipe
1495
1496                 # if real parents are the only ones in the grafts, drop it
1497                 next if join(' ',sort keys %$p) eq join(' ',sort keys %x);
1498
1499                 my (@ip, @jp, $mb);
1500                 my %del = %x;
1501                 @ip = @jp = keys %$p;
1502                 foreach my $i (@ip) {
1503                         next if $del{$i} || $p->{$i} == 2;
1504                         foreach my $j (@jp) {
1505                                 next if $i eq $j || $del{$j} || $p->{$j} == 2;
1506                                 $mb = eval { command('merge-base', $i, $j) };
1507                                 next unless $mb;
1508                                 chomp $mb;
1509                                 next if $x{$mb};
1510                                 if ($mb eq $j) {
1511                                         delete $p->{$i};
1512                                         $del{$i} = 1;
1513                                 } elsif ($mb eq $i) {
1514                                         delete $p->{$j};
1515                                         $del{$j} = 1;
1516                                 }
1517                         }
1518                 }
1519
1520                 # if real parents are the only ones in the grafts, drop it
1521                 next if join(' ',sort keys %$p) eq join(' ',sort keys %x);
1522
1523                 print $fh $c, ' ', join(' ', sort keys %$p),"\n";
1524         }
1525         if ($comments->{'END'}) {
1526                 print $fh $_ foreach @{$comments->{'END'}};
1527         }
1528         close $fh or croak $!;
1529 }
1530
1531 sub read_url_paths_all {
1532         my ($l_map, $pfx, $p) = @_;
1533         my @dir;
1534         foreach (<$p/*>) {
1535                 if (-r "$_/info/url") {
1536                         $pfx .= '/' if $pfx && $pfx !~ m!/$!;
1537                         my $id = $pfx . basename $_;
1538                         my $url = file_to_s("$_/info/url");
1539                         my ($u, $p) = repo_path_split($url);
1540                         $l_map->{$u}->{$p} = $id;
1541                 } elsif (-d $_) {
1542                         push @dir, $_;
1543                 }
1544         }
1545         foreach (@dir) {
1546                 my $x = $_;
1547                 $x =~ s!^\Q$GIT_DIR\E/svn/!!o;
1548                 read_url_paths_all($l_map, $x, $_);
1549         }
1550 }
1551
1552 # this one only gets ids that have been imported, not new ones
1553 sub read_url_paths {
1554         my $l_map = {};
1555         git_svn_each(sub { my $x = shift;
1556                         my $url = file_to_s("$GIT_DIR/svn/$x/info/url");
1557                         my ($u, $p) = repo_path_split($url);
1558                         $l_map->{$u}->{$p} = $x;
1559                         });
1560         return $l_map;
1561 }
1562
1563 sub extract_metadata {
1564         my $id = shift or return (undef, undef, undef);
1565         my ($url, $rev, $uuid) = ($id =~ /^git-svn-id:\s(\S+?)\@(\d+)
1566                                                         \s([a-f\d\-]+)$/x);
1567         if (!defined $rev || !$uuid || !$url) {
1568                 # some of the original repositories I made had
1569                 # identifiers like this:
1570                 ($rev, $uuid) = ($id =~/^git-svn-id:\s(\d+)\@([a-f\d\-]+)/);
1571         }
1572         return ($url, $rev, $uuid);
1573 }
1574
1575 sub cmt_metadata {
1576         return extract_metadata((grep(/^git-svn-id: /,
1577                 command(qw/cat-file commit/, shift)))[-1]);
1578 }
1579
1580 sub get_commit_time {
1581         my $cmt = shift;
1582         my $fh = command_output_pipe(qw/rev-list --pretty=raw -n1/, $cmt);
1583         while (<$fh>) {
1584                 /^committer\s(?:.+) (\d+) ([\-\+]?\d+)$/ or next;
1585                 my ($s, $tz) = ($1, $2);
1586                 if ($tz =~ s/^\+//) {
1587                         $s += tz_to_s_offset($tz);
1588                 } elsif ($tz =~ s/^\-//) {
1589                         $s -= tz_to_s_offset($tz);
1590                 }
1591                 close $fh;
1592                 return $s;
1593         }
1594         die "Can't get commit time for commit: $cmt\n";
1595 }
1596
1597 sub tz_to_s_offset {
1598         my ($tz) = @_;
1599         $tz =~ s/(\d\d)$//;
1600         return ($1 * 60) + ($tz * 3600);
1601 }
1602
1603 package Git::SVN;
1604 use strict;
1605 use warnings;
1606 use vars qw/$default/;
1607 use Carp qw/croak/;
1608 use File::Path qw/mkpath/;
1609 use IPC::Open3;
1610
1611 # properties that we do not log:
1612 my %SKIP_PROP;
1613 BEGIN {
1614         %SKIP_PROP = map { $_ => 1 } qw/svn:wc:ra_dav:version-url
1615                                         svn:special svn:executable
1616                                         svn:entry:committed-rev
1617                                         svn:entry:last-author
1618                                         svn:entry:uuid
1619                                         svn:entry:committed-date/;
1620 }
1621
1622 sub init {
1623         my ($class, $id, $url) = @_;
1624         my $self = _new($class, $id);
1625         mkpath(["$self->{dir}/info"]);
1626         if (defined $url) {
1627                 $url =~ s!/+$!!; # strip trailing slash
1628                 ::s_to_file($url, "$self->{dir}/info/url");
1629         }
1630         $self->{url} = $url;
1631         open my $fh, '>>', $self->{db_path} or croak $!;
1632         close $fh or croak $!;
1633         $self;
1634 }
1635
1636 sub new {
1637         my ($class, $id) = @_;
1638         my $self = _new($class, $id);
1639         $self->{url} = ::file_to_s("$self->{dir}/info/url");
1640         $self;
1641 }
1642
1643 sub refname { "refs/remotes/$_[0]->{id}" }
1644
1645 sub ra {
1646         my ($self) = shift;
1647         $self->{ra} ||= Git::SVN::Ra->new($self->{url});
1648 }
1649
1650 sub copy_remote_ref {
1651         my ($self) = @_;
1652         my $origin = $::_cp_remote ? $::_cp_remote : 'origin';
1653         my $ref = $self->refname;
1654         if (command('ls-remote', $origin, $ref)) {
1655                 command_noisy('fetch', $origin, "$ref:$ref");
1656         } elsif ($::_cp_remote && !$::_upgrade) {
1657                 die "Unable to find remote reference: $ref on $origin\n";
1658         }
1659 }
1660
1661 sub traverse_ignore {
1662         my ($self, $fh, $path, $r) = @_;
1663         $path =~ s#^/+##g;
1664         my ($dirent, undef, $props) = $self->ra->get_dir($path, $r);
1665         my $p = $path;
1666         $p =~ s#^\Q$self->{ra}->{svn_path}\E/##;
1667         print $fh length $p ? "\n# $p\n" : "\n# /\n";
1668         if (my $s = $props->{'svn:ignore'}) {
1669                 $s =~ s/[\r\n]+/\n/g;
1670                 chomp $s;
1671                 if (length $p == 0) {
1672                         $s =~ s#\n#\n/$p#g;
1673                         print $fh "/$s\n";
1674                 } else {
1675                         $s =~ s#\n#\n/$p/#g;
1676                         print $fh "/$p/$s\n";
1677                 }
1678         }
1679         foreach (sort keys %$dirent) {
1680                 next if $dirent->{$_}->kind != $SVN::Node::dir;
1681                 $self->traverse_ignore($fh, "$path/$_", $r);
1682         }
1683 }
1684
1685 # returns the newest SVN revision number and newest commit SHA1
1686 sub last_rev_commit {
1687         my ($self) = @_;
1688         if (defined $self->{last_rev} && defined $self->{last_commit}) {
1689                 return ($self->{last_rev}, $self->{last_commit});
1690         }
1691         my $c = ::verify_ref($self->refname.'^0');
1692         if (defined $c && length $c) {
1693                 my $rev = (::cmt_metadata($c))[1];
1694                 if (defined $rev) {
1695                         ($self->{last_rev}, $self->{last_commit}) = ($rev, $c);
1696                         return ($rev, $c);
1697                 }
1698         }
1699         my $offset = -41; # from tail
1700         my $rl;
1701         open my $fh, '<', $self->{db_path} or
1702                                  croak "$self->{db_path} not readable: $!\n";
1703         seek $fh, $offset, 2;
1704         $rl = readline $fh;
1705         defined $rl or return (undef, undef);
1706         chomp $rl;
1707         while ($c ne $rl && tell $fh != 0) {
1708                 $offset -= 41;
1709                 seek $fh, $offset, 2;
1710                 $rl = readline $fh;
1711                 defined $rl or return (undef, undef);
1712                 chomp $rl;
1713         }
1714         my $rev = tell $fh;
1715         croak $! if ($rev < 0);
1716         $rev =  ($rev - 41) / 41;
1717         close $fh or croak $!;
1718         ($self->{last_rev}, $self->{last_commit}) = ($rev, $c);
1719         return ($rev, $c);
1720 }
1721
1722 sub parse_revision {
1723         my ($self, $base) = @_;
1724         my $head = $self->ra->get_latest_revnum;
1725         if (!defined $::_revision || $::_revision eq 'BASE:HEAD') {
1726                 return ($base + 1, $head) if (defined $base);
1727                 return (0, $head);
1728         }
1729         return ($1, $2) if ($::_revision =~ /^(\d+):(\d+)$/);
1730         return ($::_revision, $::_revision) if ($::_revision =~ /^\d+$/);
1731         if ($::_revision =~ /^BASE:(\d+)$/) {
1732                 return ($base + 1, $1) if (defined $base);
1733                 return (0, $head);
1734         }
1735         return ($1, $head) if ($::_revision =~ /^(\d+):HEAD$/);
1736         die "revision argument: $::_revision not understood by git-svn\n",
1737                 "Try using the command-line svn client instead\n";
1738 }
1739
1740 sub tmp_index_do {
1741         my ($self, $sub) = @_;
1742         my $old_index = $ENV{GIT_INDEX_FILE};
1743         $ENV{GIT_INDEX_FILE} = $self->{index};
1744         my @ret = &$sub;
1745         if ($old_index) {
1746                 $ENV{GIT_INDEX_FILE} = $old_index;
1747         } else {
1748                 delete $ENV{GIT_INDEX_FILE};
1749         }
1750         wantarray ? @ret : $ret[0];
1751 }
1752
1753 sub assert_index_clean {
1754         my ($self, $treeish) = @_;
1755
1756         $self->tmp_index_do(sub {
1757                 command_noisy('read-tree', $treeish) unless -e $self->{index};
1758                 my $x = command_oneline('write-tree');
1759                 my ($y) = (command(qw/cat-file commit/, $treeish) =~
1760                            /^tree ($::sha1)/mo);
1761                 if ($y ne $x) {
1762                         unlink $self->{index} or croak $!;
1763                         command_noisy('read-tree', $treeish);
1764                 }
1765                 $x = command_oneline('write-tree');
1766                 if ($y ne $x) {
1767                         ::fatal "trees ($treeish) $y != $x\n",
1768                                 "Something is seriously wrong...\n";
1769                 }
1770         });
1771 }
1772
1773 sub get_commit_parents {
1774         my ($self, $log_msg, @parents) = @_;
1775         my (%seen, @ret, @tmp);
1776         # commit parents can be conditionally bound to a particular
1777         # svn revision via: "svn_revno=commit_sha1", filter them out here:
1778         foreach my $p (@parents) {
1779                 next unless defined $p;
1780                 if ($p =~ /^(\d+)=($::sha1_short)$/o) {
1781                         push @tmp, $2 if $1 == $log_msg->{revision};
1782                 } else {
1783                         push @tmp, $p if $p =~ /^$::sha1_short$/o;
1784                 }
1785         }
1786         if (my $cur = ::verify_ref($self->refname.'^0')) {
1787                 push @tmp, $cur;
1788         }
1789         push @tmp, $_ foreach (@{$log_msg->{parents}}, @tmp);
1790         while (my $p = shift @tmp) {
1791                 next if $seen{$p};
1792                 $seen{$p} = 1;
1793                 push @ret, $p;
1794                 # MAXPARENT is defined to 16 in commit-tree.c:
1795                 last if @ret >= 16;
1796         }
1797         if (@tmp) {
1798                 die "r$log_msg->{revision}: No room for parents:\n\t",
1799                     join("\n\t", @tmp), "\n";
1800         }
1801         @ret;
1802 }
1803
1804 sub check_upgrade_needed {
1805         my ($self) = @_;
1806         if (!-r $self->{db_path}) {
1807                 -d $self->{dir} or mkpath([$self->{dir}]);
1808                 open my $fh, '>>', $self->{db_path} or croak $!;
1809                 close $fh;
1810         }
1811         return unless ::verify_ref($self->{id}.'-HEAD^0');
1812         my $head = ::verify_ref($self->refname.'^0');
1813         if ($@ || !$head) {
1814                 ::fatal("Please run: $0 rebuild --upgrade\n");
1815         }
1816 }
1817
1818 sub do_git_commit {
1819         my ($self, $log_msg, @parents) = @_;
1820         if (my $c = $self->rev_db_get($log_msg->{revision})) {
1821                 croak "$log_msg->{revision} = $c already exists! ",
1822                       "Why are we refetching it?\n";
1823         }
1824         my ($name, $email) = ::author_name_email($log_msg->{author}, $self->ra);
1825         $ENV{GIT_AUTHOR_NAME} = $ENV{GIT_COMMITTER_NAME} = $name;
1826         $ENV{GIT_AUTHOR_EMAIL} = $ENV{GIT_COMMITTER_EMAIL} = $email;
1827         $ENV{GIT_AUTHOR_DATE} = $ENV{GIT_COMMITTER_DATE} = $log_msg->{date};
1828
1829         my $tree = $log_msg->{tree};
1830         if (!defined $tree) {
1831                 $tree = $self->tmp_index_do(sub {
1832                                             command_oneline('write-tree') });
1833         }
1834         die "Tree is not a valid sha1: $tree\n" if $tree !~ /^$::sha1$/o;
1835
1836         my @exec = ('git-commit-tree', $tree);
1837         foreach ($self->get_commit_parents($log_msg, @parents)) {
1838                 push @exec, '-p', $_;
1839         }
1840         defined(my $pid = open3(my $msg_fh, my $out_fh, '>&STDERR', @exec))
1841                                                                    or croak $!;
1842         print $msg_fh $log_msg->{log} or croak $!;
1843         print $msg_fh "\ngit-svn-id: $self->{ra}->{url}\@$log_msg->{revision}",
1844                       " ", $self->ra->uuid,"\n" or croak $!;
1845         $msg_fh->flush == 0 or croak $!;
1846         close $msg_fh or croak $!;
1847         chomp(my $commit = do { local $/; <$out_fh> });
1848         close $out_fh or croak $!;
1849         waitpid $pid, 0;
1850         croak $? if $?;
1851         if ($commit !~ /^$::sha1$/o) {
1852                 die "Failed to commit, invalid sha1: $commit\n";
1853         }
1854
1855         command_noisy('update-ref',$self->refname, $commit);
1856         $self->rev_db_set($log_msg->{revision}, $commit);
1857
1858         $self->{last_rev} = $log_msg->{revision};
1859         $self->{last_commit} = $commit;
1860         print "r$log_msg->{revision} = $commit\n";
1861         return $commit;
1862 }
1863
1864 sub do_fetch {
1865         my ($self, $paths, $rev) = @_; #, $author, $date, $msg) = @_;
1866         my $ed = SVN::Git::Fetcher->new($self);
1867         my ($last_rev, @parents);
1868         if ($self->{last_commit}) {
1869                 $last_rev = $self->{last_rev};
1870                 $ed->{c} = $self->{last_commit};
1871                 @parents = ($self->{last_commit});
1872         } else {
1873                 $last_rev = $rev;
1874         }
1875         unless ($self->ra->do_update($last_rev, $rev, '', 1, $ed)) {
1876                 die "SVN connection failed somewhere...\n";
1877         }
1878         $self->make_log_entry($rev, \@parents, $ed);
1879 }
1880
1881 sub write_untracked {
1882         my ($self, $rev, $fh, $untracked) = @_;
1883         my $h;
1884         print $fh "r$rev\n" or croak $!;
1885         $h = $untracked->{empty};
1886         foreach (sort keys %$h) {
1887                 my $act = $h->{$_} ? '+empty_dir' : '-empty_dir';
1888                 print $fh "  $act: ", uri_encode($_), "\n" or croak $!;
1889                 warn "W: $act: $_\n";
1890         }
1891         foreach my $t (qw/dir_prop file_prop/) {
1892                 $h = $untracked->{$t} or next;
1893                 foreach my $path (sort keys %$h) {
1894                         my $ppath = $path eq '' ? '.' : $path;
1895                         foreach my $prop (sort keys %{$h->{$path}}) {
1896                                 next if $SKIP{$prop};
1897                                 my $v = $h->{$path}->{$prop};
1898                                 if (defined $v) {
1899                                         print $fh "  +$t: ",
1900                                                   uri_encode($ppath), ' ',
1901                                                   uri_encode($prop), ' ',
1902                                                   uri_encode($v), "\n"
1903                                                   or croak $!;
1904                                 } else {
1905                                         print $fh "  -$t: ",
1906                                                   uri_encode($ppath), ' ',
1907                                                   uri_encode($prop), "\n"
1908                                                   or croak $!;
1909                                 }
1910                         }
1911                 }
1912         }
1913         foreach my $t (qw/absent_file absent_directory/) {
1914                 $h = $untracked->{$t} or next;
1915                 foreach my $parent (sort keys %$h) {
1916                         foreach my $path (sort @{$h->{$parent}}) {
1917                                 print $fh "  $t: ",
1918                                       uri_encode("$parent/$path"), "\n"
1919                                       or croak $!;
1920                                 warn "W: $t: $parent/$path ",
1921                                      "Insufficient permissions?\n";
1922                         }
1923                 }
1924         }
1925 }
1926
1927 sub make_log_entry {
1928         my ($self, $rev, $parents, $untracked) = @_;
1929         my $rp = $self->ra->rev_proplist($rev);
1930         my %log_entry = ( parents => $parents || [], revision => $rev,
1931                           revprops => $rp, log => '');
1932         open my $un, '>>', "$self->{dir}/unhandled.log" or croak $!;
1933         $self->write_untracked($rev, $un, $untracked);
1934         foreach (sort keys %$rp) {
1935                 my $v = $rp->{$_};
1936                 if (/^svn:(author|date|log)$/) {
1937                         $log_entry{$1} = $v;
1938                 } else {
1939                         print $un "  rev_prop: ", uri_encode($_), ' ',
1940                                   uri_encode($v), "\n";
1941                 }
1942         }
1943         close $un or croak $!;
1944         $log_entry{date} = parse_svn_date($log_entry{date});
1945         $log_entry{author} = check_author($log_entry{author});
1946         $log_entry{log} .= "\n";
1947         \%log_entry;
1948 }
1949
1950 sub fetch {
1951         my ($self, @parents) = @_;
1952         my ($last_rev, $last_commit) = $self->last_rev_commit;
1953         my ($base, $head) = $self->parse_revision($last_rev);
1954         return if ($base > $head);
1955         if (defined $last_commit) {
1956                 $self->assert_index_clean($last_commit);
1957         }
1958         my $inc = 1000;
1959         my ($min, $max) = ($base, $head < $base + $inc ? $head : $base + $inc);
1960         my $err_handler = $SVN::Error::handler;
1961         $SVN::Error::handler = \&skip_unknown_revs;
1962         while (1) {
1963                 my @revs;
1964                 $self->ra->get_log([''], $min, $max, 0, 1, 1, sub {
1965                         my ($paths, $rev, $author, $date, $msg) = @_;
1966                         push @revs, $rev });
1967                 foreach (@revs) {
1968                         my $log_entry = $self->do_fetch(undef, $_);
1969                         $self->do_git_commit($log_entry, @parents);
1970                 }
1971                 last if $max >= $head;
1972                 $min = $max + 1;
1973                 $max += $inc;
1974                 $max = $head if ($max > $head);
1975         }
1976         $SVN::Error::handler = $err_handler;
1977 }
1978
1979 sub set_tree_cb {
1980         my ($self, $log_entry, $tree, $rev, $date, $author) = @_;
1981         # TODO: enable and test optimized commits:
1982         if (0 && $rev == ($self->{last_rev} + 1)) {
1983                 $log_entry->{revision} = $rev;
1984                 $log_entry->{author} = $author;
1985                 $self->do_git_commit($log_entry, "$rev=$tree");
1986         } else {
1987                 $self->fetch("$rev=$tree");
1988         }
1989 }
1990
1991 sub set_tree {
1992         my ($self, $tree) = (shift, shift);
1993         my $log_entry = get_commit_entry($tree);
1994         unless ($self->{last_rev}) {
1995                 fatal("Must have an existing revision to commit\n");
1996         }
1997         my $pool = SVN::Pool->new;
1998         my $ed = SVN::Git::Editor->new({ r => $self->{last_rev},
1999                                          ra => $self->ra->dup,
2000                                          c => $tree,
2001                                          svn_path => $self->ra->{svn_path}
2002                                        },
2003                                        $self->ra->get_commit_editor(
2004                                          $log_entry->{log}, sub {
2005                                            $self->set_tree_cb($log_entry,
2006                                                               $tree, @_);
2007                                        }),
2008                                        $pool);
2009         my $mods = $ed->apply_diff($self->{last_commit}, $tree);
2010         if (@$mods == 0) {
2011                 print "No changes\nr$self->{last_rev} = $tree\n";
2012         }
2013         $pool->clear;
2014 }
2015
2016 sub skip_unknown_revs {
2017         my ($err) = @_;
2018         my $errno = $err->apr_err();
2019         # Maybe the branch we're tracking didn't
2020         # exist when the repo started, so it's
2021         # not an error if it doesn't, just continue
2022         #
2023         # Wonderfully consistent library, eh?
2024         # 160013 - svn:// and file://
2025         # 175002 - http(s)://
2026         # 175007 - http(s):// (this repo required authorization, too...)
2027         #   More codes may be discovered later...
2028         if ($errno == 175007 || $errno == 175002 || $errno == 160013) {
2029                 return;
2030         }
2031         croak "Error from SVN, ($errno): ", $err->expanded_message,"\n";
2032 }
2033
2034 # rev_db:
2035 # Tie::File seems to be prone to offset errors if revisions get sparse,
2036 # it's not that fast, either.  Tie::File is also not in Perl 5.6.  So
2037 # one of my favorite modules is out :<  Next up would be one of the DBM
2038 # modules, but I'm not sure which is most portable...  So I'll just
2039 # go with something that's plain-text, but still capable of
2040 # being randomly accessed.  So here's my ultra-simple fixed-width
2041 # database.  All records are 40 characters + "\n", so it's easy to seek
2042 # to a revision: (41 * rev) is the byte offset.
2043 # A record of 40 0s denotes an empty revision.
2044 # And yes, it's still pretty fast (faster than Tie::File).
2045
2046 sub rev_db_set {
2047         my ($self, $rev, $commit) = @_;
2048         length $commit == 40 or croak "arg3 must be a full SHA1 hexsum\n";
2049         open my $fh, '+<', $self->{db_path} or croak $!;
2050         my $offset = $rev * 41;
2051         # assume that append is the common case:
2052         seek $fh, 0, 2 or croak $!;
2053         my $pos = tell $fh;
2054         if ($pos < $offset) {
2055                 print $fh (('0' x 40),"\n") x (($offset - $pos) / 41)
2056                   or croak $!;
2057         }
2058         seek $fh, $offset, 0 or croak $!;
2059         print $fh $commit,"\n" or croak $!;
2060         close $fh or croak $!;
2061 }
2062
2063 sub rev_db_get {
2064         my ($self, $rev) = @_;
2065         my $ret;
2066         my $offset = $rev * 41;
2067         open my $fh, '<', $self->{db_path} or croak $!;
2068         if (seek $fh, $offset, 0) {
2069                 $ret = readline $fh;
2070                 if (defined $ret) {
2071                         chomp $ret;
2072                         $ret = undef if ($ret =~ /^0{40}$/);
2073                 }
2074         }
2075         close $fh or croak $!;
2076         $ret;
2077 }
2078
2079 sub _new {
2080         my ($class, $id) = @_;
2081         $id ||= $Git::SVN::default;
2082         my $dir = "$ENV{GIT_DIR}/svn/$id";
2083         bless { id => $id, dir => $dir, index => "$dir/index",
2084                 db_path => "$dir/.rev_db" }, $class;
2085 }
2086
2087
2088 package Git::SVN::Prompt;
2089 use strict;
2090 use warnings;
2091 require SVN::Core;
2092 use vars qw/$_no_auth_cache $_username/;
2093
2094 sub simple {
2095         my ($cred, $realm, $default_username, $may_save, $pool) = @_;
2096         $may_save = undef if $_no_auth_cache;
2097         $default_username = $_username if defined $_username;
2098         if (defined $default_username && length $default_username) {
2099                 if (defined $realm && length $realm) {
2100                         print STDERR "Authentication realm: $realm\n";
2101                         STDERR->flush;
2102                 }
2103                 $cred->username($default_username);
2104         } else {
2105                 username($cred, $realm, $may_save, $pool);
2106         }
2107         $cred->password(_read_password("Password for '" .
2108                                        $cred->username . "': ", $realm));
2109         $cred->may_save($may_save);
2110         $SVN::_Core::SVN_NO_ERROR;
2111 }
2112
2113 sub ssl_server_trust {
2114         my ($cred, $realm, $failures, $cert_info, $may_save, $pool) = @_;
2115         $may_save = undef if $_no_auth_cache;
2116         print STDERR "Error validating server certificate for '$realm':\n";
2117         if ($failures & $SVN::Auth::SSL::UNKNOWNCA) {
2118                 print STDERR " - The certificate is not issued by a trusted ",
2119                       "authority. Use the\n",
2120                       "   fingerprint to validate the certificate manually!\n";
2121         }
2122         if ($failures & $SVN::Auth::SSL::CNMISMATCH) {
2123                 print STDERR " - The certificate hostname does not match.\n";
2124         }
2125         if ($failures & $SVN::Auth::SSL::NOTYETVALID) {
2126                 print STDERR " - The certificate is not yet valid.\n";
2127         }
2128         if ($failures & $SVN::Auth::SSL::EXPIRED) {
2129                 print STDERR " - The certificate has expired.\n";
2130         }
2131         if ($failures & $SVN::Auth::SSL::OTHER) {
2132                 print STDERR " - The certificate has an unknown error.\n";
2133         }
2134         printf STDERR
2135                 "Certificate information:\n".
2136                 " - Hostname: %s\n".
2137                 " - Valid: from %s until %s\n".
2138                 " - Issuer: %s\n".
2139                 " - Fingerprint: %s\n",
2140                 map $cert_info->$_, qw(hostname valid_from valid_until
2141                                        issuer_dname fingerprint);
2142         my $choice;
2143 prompt:
2144         print STDERR $may_save ?
2145               "(R)eject, accept (t)emporarily or accept (p)ermanently? " :
2146               "(R)eject or accept (t)emporarily? ";
2147         STDERR->flush;
2148         $choice = lc(substr(<STDIN> || 'R', 0, 1));
2149         if ($choice =~ /^t$/i) {
2150                 $cred->may_save(undef);
2151         } elsif ($choice =~ /^r$/i) {
2152                 return -1;
2153         } elsif ($may_save && $choice =~ /^p$/i) {
2154                 $cred->may_save($may_save);
2155         } else {
2156                 goto prompt;
2157         }
2158         $cred->accepted_failures($failures);
2159         $SVN::_Core::SVN_NO_ERROR;
2160 }
2161
2162 sub ssl_client_cert {
2163         my ($cred, $realm, $may_save, $pool) = @_;
2164         $may_save = undef if $_no_auth_cache;
2165         print STDERR "Client certificate filename: ";
2166         STDERR->flush;
2167         chomp(my $filename = <STDIN>);
2168         $cred->cert_file($filename);
2169         $cred->may_save($may_save);
2170         $SVN::_Core::SVN_NO_ERROR;
2171 }
2172
2173 sub ssl_client_cert_pw {
2174         my ($cred, $realm, $may_save, $pool) = @_;
2175         $may_save = undef if $_no_auth_cache;
2176         $cred->password(_read_password("Password: ", $realm));
2177         $cred->may_save($may_save);
2178         $SVN::_Core::SVN_NO_ERROR;
2179 }
2180
2181 sub username {
2182         my ($cred, $realm, $may_save, $pool) = @_;
2183         $may_save = undef if $_no_auth_cache;
2184         if (defined $realm && length $realm) {
2185                 print STDERR "Authentication realm: $realm\n";
2186         }
2187         my $username;
2188         if (defined $_username) {
2189                 $username = $_username;
2190         } else {
2191                 print STDERR "Username: ";
2192                 STDERR->flush;
2193                 chomp($username = <STDIN>);
2194         }
2195         $cred->username($username);
2196         $cred->may_save($may_save);
2197         $SVN::_Core::SVN_NO_ERROR;
2198 }
2199
2200 sub _read_password {
2201         my ($prompt, $realm) = @_;
2202         print STDERR $prompt;
2203         STDERR->flush;
2204         require Term::ReadKey;
2205         Term::ReadKey::ReadMode('noecho');
2206         my $password = '';
2207         while (defined(my $key = Term::ReadKey::ReadKey(0))) {
2208                 last if $key =~ /[\012\015]/; # \n\r
2209                 $password .= $key;
2210         }
2211         Term::ReadKey::ReadMode('restore');
2212         print STDERR "\n";
2213         STDERR->flush;
2214         $password;
2215 }
2216
2217 package main;
2218
2219 sub uri_encode {
2220         my ($f) = @_;
2221         $f =~ s#([^a-zA-Z0-9\*!\:_\./\-])#uc sprintf("%%%02x",ord($1))#eg;
2222         $f
2223 }
2224
2225 sub uri_decode {
2226         my ($f) = @_;
2227         $f =~ tr/+/ /;
2228         $f =~ s/%([A-F0-9]{2})/chr hex($1)/ge;
2229         $f
2230 }
2231
2232 sub libsvn_log_entry {
2233         my ($rev, $author, $date, $msg, $parents, $untracked) = @_;
2234         my ($Y,$m,$d,$H,$M,$S) = ($date =~ /^(\d{4})\-(\d\d)\-(\d\d)T
2235                                          (\d\d)\:(\d\d)\:(\d\d).\d+Z$/x)
2236                                 or die "Unable to parse date: $date\n";
2237         if (defined $author && length $author > 0 &&
2238             defined $_authors && ! defined $users{$author}) {
2239                 die "Author: $author not defined in $_authors file\n";
2240         }
2241         $msg = '' if ($rev == 0 && !defined $msg);
2242
2243         open my $un, '>>', "$GIT_SVN_DIR/unhandled.log" or croak $!;
2244         my $h;
2245         print $un "r$rev\n" or croak $!;
2246         $h = $untracked->{empty};
2247         foreach (sort keys %$h) {
2248                 my $act = $h->{$_} ? '+empty_dir' : '-empty_dir';
2249                 print $un "  $act: ", uri_encode($_), "\n" or croak $!;
2250                 warn "W: $act: $_\n";
2251         }
2252         foreach my $t (qw/dir_prop file_prop/) {
2253                 $h = $untracked->{$t} or next;
2254                 foreach my $path (sort keys %$h) {
2255                         my $ppath = $path eq '' ? '.' : $path;
2256                         foreach my $prop (sort keys %{$h->{$path}}) {
2257                                 next if $SKIP{$prop};
2258                                 my $v = $h->{$path}->{$prop};
2259                                 if (defined $v) {
2260                                         print $un "  +$t: ",
2261                                                   uri_encode($ppath), ' ',
2262                                                   uri_encode($prop), ' ',
2263                                                   uri_encode($v), "\n"
2264                                                   or croak $!;
2265                                 } else {
2266                                         print $un "  -$t: ",
2267                                                   uri_encode($ppath), ' ',
2268                                                   uri_encode($prop), "\n"
2269                                                   or croak $!;
2270                                 }
2271                         }
2272                 }
2273         }
2274         foreach my $t (qw/absent_file absent_directory/) {
2275                 $h = $untracked->{$t} or next;
2276                 foreach my $parent (sort keys %$h) {
2277                         foreach my $path (sort @{$h->{$parent}}) {
2278                                 print $un "  $t: ",
2279                                       uri_encode("$parent/$path"), "\n"
2280                                       or croak $!;
2281                                 warn "W: $t: $parent/$path ",
2282                                      "Insufficient permissions?\n";
2283                         }
2284                 }
2285         }
2286
2287         # revprops (make this optional? it's an extra network trip...)
2288         my $rp = $SVN->rev_proplist($rev);
2289         foreach (sort keys %$rp) {
2290                 next if /^svn:(?:author|date|log)$/;
2291                 print $un "  rev_prop: ", uri_encode($_), ' ',
2292                           uri_encode($rp->{$_}), "\n";
2293         }
2294         close $un or croak $!;
2295
2296         { revision => $rev, date => "+0000 $Y-$m-$d $H:$M:$S",
2297           author => $author, msg => $msg."\n", parents => $parents || [],
2298           revprops => $rp }
2299 }
2300
2301 sub libsvn_fetch {
2302         my ($last_commit, $paths, $rev, $author, $date, $msg) = @_;
2303         my $ed = SVN::Git::Fetcher->new({ c => $last_commit, q => $_q });
2304         my (undef, $last_rev, undef) = cmt_metadata($last_commit);
2305         unless ($SVN->gs_do_update($last_rev, $rev, '', 1, $ed)) {
2306                 die "SVN connection failed somewhere...\n";
2307         }
2308         libsvn_log_entry($rev, $author, $date, $msg, [$last_commit], $ed);
2309 }
2310
2311 sub svn_grab_base_rev {
2312         my $c = eval { command_oneline([qw/rev-parse --verify/,
2313                                         "refs/remotes/$GIT_SVN^0"],
2314                                         { STDERR => 0 }) };
2315         if (defined $c && length $c) {
2316                 my ($url, $rev, $uuid) = cmt_metadata($c);
2317                 return ($rev, $c) if defined $rev;
2318         }
2319         if ($_no_metadata) {
2320                 my $offset = -41; # from tail
2321                 my $rl;
2322                 open my $fh, '<', $REVDB or
2323                         die "--no-metadata specified and $REVDB not readable\n";
2324                 seek $fh, $offset, 2;
2325                 $rl = readline $fh;
2326                 defined $rl or return (undef, undef);
2327                 chomp $rl;
2328                 while ($c ne $rl && tell $fh != 0) {
2329                         $offset -= 41;
2330                         seek $fh, $offset, 2;
2331                         $rl = readline $fh;
2332                         defined $rl or return (undef, undef);
2333                         chomp $rl;
2334                 }
2335                 my $rev = tell $fh;
2336                 croak $! if ($rev < -1);
2337                 $rev =  ($rev - 41) / 41;
2338                 close $fh or croak $!;
2339                 return ($rev, $c);
2340         }
2341         return (undef, undef);
2342 }
2343
2344 sub libsvn_parse_revision {
2345         my $base = shift;
2346         my $head = $SVN->get_latest_revnum();
2347         if (!defined $_revision || $_revision eq 'BASE:HEAD') {
2348                 return ($base + 1, $head) if (defined $base);
2349                 return (0, $head);
2350         }
2351         return ($1, $2) if ($_revision =~ /^(\d+):(\d+)$/);
2352         return ($_revision, $_revision) if ($_revision =~ /^\d+$/);
2353         if ($_revision =~ /^BASE:(\d+)$/) {
2354                 return ($base + 1, $1) if (defined $base);
2355                 return (0, $head);
2356         }
2357         return ($1, $head) if ($_revision =~ /^(\d+):HEAD$/);
2358         die "revision argument: $_revision not understood by git-svn\n",
2359                 "Try using the command-line svn client instead\n";
2360 }
2361
2362 sub libsvn_traverse_ignore {
2363         my ($fh, $path, $r) = @_;
2364         $path =~ s#^/+##g;
2365         my ($dirent, undef, $props) = $SVN->get_dir($path, $r);
2366         my $p = $path;
2367         $p =~ s#^\Q$SVN->{svn_path}\E/##;
2368         print $fh length $p ? "\n# $p\n" : "\n# /\n";
2369         if (my $s = $props->{'svn:ignore'}) {
2370                 $s =~ s/[\r\n]+/\n/g;
2371                 chomp $s;
2372                 if (length $p == 0) {
2373                         $s =~ s#\n#\n/$p#g;
2374                         print $fh "/$s\n";
2375                 } else {
2376                         $s =~ s#\n#\n/$p/#g;
2377                         print $fh "/$p/$s\n";
2378                 }
2379         }
2380         foreach (sort keys %$dirent) {
2381                 next if $dirent->{$_}->kind != $SVN::Node::dir;
2382                 libsvn_traverse_ignore($fh, "$path/$_", $r);
2383         }
2384 }
2385
2386 sub revisions_eq {
2387         my ($path, $r0, $r1) = @_;
2388         return 1 if $r0 == $r1;
2389         my $nr = 0;
2390         # should be OK to use Pool here (r1 - r0) should be small
2391         $SVN->get_log([$path], $r0, $r1, 0, 0, 1, sub {$nr++});
2392         return 0 if ($nr > 1);
2393         return 1;
2394 }
2395
2396 sub libsvn_find_parent_branch {
2397         my ($paths, $rev, $author, $date, $msg) = @_;
2398         my $svn_path = '/'.$SVN->{svn_path};
2399
2400         # look for a parent from another branch:
2401         my $i = $paths->{$svn_path} or return;
2402         my $branch_from = $i->copyfrom_path or return;
2403         my $r = $i->copyfrom_rev;
2404         print STDERR  "Found possible branch point: ",
2405                                 "$branch_from => $svn_path, $r\n";
2406         $branch_from =~ s#^/##;
2407         my $l_map = {};
2408         read_url_paths_all($l_map, '', "$GIT_DIR/svn");
2409         my $url = $SVN->{repos_root};
2410         defined $l_map->{$url} or return;
2411         my $id = $l_map->{$url}->{$branch_from};
2412         if (!defined $id && $_follow_parent) {
2413                 print STDERR "Following parent: $branch_from\@$r\n";
2414                 # auto create a new branch and follow it
2415                 $id = basename($branch_from);
2416                 $id .= '@'.$r if -r "$GIT_DIR/svn/$id";
2417                 while (-r "$GIT_DIR/svn/$id") {
2418                         # just grow a tail if we're not unique enough :x
2419                         $id .= '-';
2420                 }
2421         }
2422         return unless defined $id;
2423
2424         my ($r0, $parent) = find_rev_before($r,$id,1);
2425         if ($_follow_parent && (!defined $r0 || !defined $parent)) {
2426                 defined(my $pid = fork) or croak $!;
2427                 if (!$pid) {
2428                         $GIT_SVN = $ENV{GIT_SVN_ID} = $id;
2429                         init_vars();
2430                         $SVN_URL = "$url/$branch_from";
2431                         $SVN = undef;
2432                         setup_git_svn();
2433                         # we can't assume SVN_URL exists at r+1:
2434                         $_revision = "0:$r";
2435                         fetch_lib();
2436                         exit 0;
2437                 }
2438                 waitpid $pid, 0;
2439                 croak $? if $?;
2440                 ($r0, $parent) = find_rev_before($r,$id,1);
2441         }
2442         return unless (defined $r0 && defined $parent);
2443         if (revisions_eq($branch_from, $r0, $r)) {
2444                 unlink $GIT_SVN_INDEX;
2445                 print STDERR "Found branch parent: ($GIT_SVN) $parent\n";
2446                 command_noisy('read-tree', $parent);
2447                 unless ($SVN->can_do_switch) {
2448                         return _libsvn_new_tree($paths, $rev, $author, $date,
2449                                                 $msg, [$parent]);
2450                 }
2451                 # do_switch works with svn/trunk >= r22312, but that is not
2452                 # included with SVN 1.4.2 (the latest version at the moment),
2453                 # so we can't rely on it.
2454                 my $ra = Git::SVN::Ra->new("$url/$branch_from");
2455                 my $ed = SVN::Git::Fetcher->new({c => $parent, q => $_q });
2456                 $ra->gs_do_switch($r0, $rev, '', 1, $SVN->{url}, $ed) or
2457                                    die "SVN connection failed somewhere...\n";
2458                 return libsvn_log_entry($rev, $author, $date, $msg, [$parent]);
2459         }
2460         print STDERR "Nope, branch point not imported or unknown\n";
2461         return undef;
2462 }
2463
2464 sub libsvn_new_tree {
2465         if (my $log_entry = libsvn_find_parent_branch(@_)) {
2466                 return $log_entry;
2467         }
2468         my ($paths, $rev, $author, $date, $msg) = @_; # $pool is last
2469         _libsvn_new_tree($paths, $rev, $author, $date, $msg, []);
2470 }
2471
2472 sub _libsvn_new_tree {
2473         my ($paths, $rev, $author, $date, $msg, $parents) = @_;
2474         my $ed = SVN::Git::Fetcher->new({q => $_q});
2475         unless ($SVN->gs_do_update($rev, $rev, '', 1, $ed)) {
2476                 die "SVN connection failed somewhere...\n";
2477         }
2478         libsvn_log_entry($rev, $author, $date, $msg, $parents, $ed);
2479 }
2480
2481 sub find_graft_path_commit {
2482         my ($tree_paths, $p1, $r1) = @_;
2483         foreach my $x (keys %$tree_paths) {
2484                 next unless ($p1 =~ /^\Q$x\E/);
2485                 my $i = $tree_paths->{$x};
2486                 my ($r0, $parent) = find_rev_before($r1,$i,1);
2487                 return $parent if (defined $r0 && $r0 == $r1);
2488                 print STDERR "r$r1 of $i not imported\n";
2489                 next;
2490         }
2491         return undef;
2492 }
2493
2494 sub find_graft_path_parents {
2495         my ($grafts, $tree_paths, $c, $p0, $r0) = @_;
2496         foreach my $x (keys %$tree_paths) {
2497                 next unless ($p0 =~ /^\Q$x\E/);
2498                 my $i = $tree_paths->{$x};
2499                 my ($r, $parent) = find_rev_before($r0, $i, 1);
2500                 if (defined $r && defined $parent && revisions_eq($x,$r,$r0)) {
2501                         my ($url_b, undef, $uuid_b) = cmt_metadata($c);
2502                         my ($url_a, undef, $uuid_a) = cmt_metadata($parent);
2503                         next if ($url_a && $url_b && $url_a eq $url_b &&
2504                                                         $uuid_b eq $uuid_a);
2505                         $grafts->{$c}->{$parent} = 1;
2506                 }
2507         }
2508 }
2509
2510 sub libsvn_graft_file_copies {
2511         my ($grafts, $tree_paths, $path, $paths, $rev) = @_;
2512         foreach (keys %$paths) {
2513                 my $i = $paths->{$_};
2514                 my ($m, $p0, $r0) = ($i->action, $i->copyfrom_path,
2515                                         $i->copyfrom_rev);
2516                 next unless (defined $p0 && defined $r0);
2517
2518                 my $p1 = $_;
2519                 $p1 =~ s#^/##;
2520                 $p0 =~ s#^/##;
2521                 my $c = find_graft_path_commit($tree_paths, $p1, $rev);
2522                 next unless $c;
2523                 find_graft_path_parents($grafts, $tree_paths, $c, $p0, $r0);
2524         }
2525 }
2526
2527 sub set_index {
2528         my $old = $ENV{GIT_INDEX_FILE};
2529         $ENV{GIT_INDEX_FILE} = shift;
2530         return $old;
2531 }
2532
2533 sub restore_index {
2534         my ($old) = @_;
2535         if (defined $old) {
2536                 $ENV{GIT_INDEX_FILE} = $old;
2537         } else {
2538                 delete $ENV{GIT_INDEX_FILE};
2539         }
2540 }
2541
2542 sub libsvn_commit_cb {
2543         my ($rev, $date, $committer, $c, $msg, $r_last, $cmt_last) = @_;
2544         if ($_optimize_commits && $rev == ($r_last + 1)) {
2545                 my $log = libsvn_log_entry($rev,$committer,$date,$msg);
2546                 $log->{tree} = get_tree_from_treeish($c);
2547                 my $cmt = git_commit($log, $cmt_last, $c);
2548                 my @diff = command('diff-tree', $cmt, $c);
2549                 if (@diff) {
2550                         print STDERR "Trees differ: $cmt $c\n",
2551                                         join('',@diff),"\n";
2552                         exit 1;
2553                 }
2554         } else {
2555                 fetch("$rev=$c");
2556         }
2557 }
2558
2559 sub libsvn_skip_unknown_revs {
2560         my $err = shift;
2561         my $errno = $err->apr_err();
2562         # Maybe the branch we're tracking didn't
2563         # exist when the repo started, so it's
2564         # not an error if it doesn't, just continue
2565         #
2566         # Wonderfully consistent library, eh?
2567         # 160013 - svn:// and file://
2568         # 175002 - http(s)://
2569         # 175007 - http(s):// (this repo required authorization, too...)
2570         #   More codes may be discovered later...
2571         if ($errno == 175007 || $errno == 175002 || $errno == 160013) {
2572                 return;
2573         }
2574         croak "Error from SVN, ($errno): ", $err->expanded_message,"\n";
2575 };
2576
2577 # Tie::File seems to be prone to offset errors if revisions get sparse,
2578 # it's not that fast, either.  Tie::File is also not in Perl 5.6.  So
2579 # one of my favorite modules is out :<  Next up would be one of the DBM
2580 # modules, but I'm not sure which is most portable...  So I'll just
2581 # go with something that's plain-text, but still capable of
2582 # being randomly accessed.  So here's my ultra-simple fixed-width
2583 # database.  All records are 40 characters + "\n", so it's easy to seek
2584 # to a revision: (41 * rev) is the byte offset.
2585 # A record of 40 0s denotes an empty revision.
2586 # And yes, it's still pretty fast (faster than Tie::File).
2587 sub revdb_set {
2588         my ($file, $rev, $commit) = @_;
2589         length $commit == 40 or croak "arg3 must be a full SHA1 hexsum\n";
2590         open my $fh, '+<', $file or croak $!;
2591         my $offset = $rev * 41;
2592         # assume that append is the common case:
2593         seek $fh, 0, 2 or croak $!;
2594         my $pos = tell $fh;
2595         if ($pos < $offset) {
2596                 print $fh (('0' x 40),"\n") x (($offset - $pos) / 41);
2597         }
2598         seek $fh, $offset, 0 or croak $!;
2599         print $fh $commit,"\n";
2600         close $fh or croak $!;
2601 }
2602
2603 sub revdb_get {
2604         my ($file, $rev) = @_;
2605         my $ret;
2606         my $offset = $rev * 41;
2607         open my $fh, '<', $file or croak $!;
2608         seek $fh, $offset, 0;
2609         if (tell $fh == $offset) {
2610                 $ret = readline $fh;
2611                 if (defined $ret) {
2612                         chomp $ret;
2613                         $ret = undef if ($ret =~ /^0{40}$/);
2614                 }
2615         }
2616         close $fh or croak $!;
2617         return $ret;
2618 }
2619
2620 sub copy_remote_ref {
2621         my $origin = $_cp_remote ? $_cp_remote : 'origin';
2622         my $ref = "refs/remotes/$GIT_SVN";
2623         if (command('ls-remote', $origin, $ref)) {
2624                 command_noisy('fetch', $origin, "$ref:$ref");
2625         } elsif ($_cp_remote && !$_upgrade) {
2626                 die "Unable to find remote reference: ",
2627                                 "refs/remotes/$GIT_SVN on $origin\n";
2628         }
2629 }
2630
2631 {
2632         my $kill_stupid_warnings = $SVN::Node::none.$SVN::Node::file.
2633                                 $SVN::Node::dir.$SVN::Node::unknown.
2634                                 $SVN::Node::none.$SVN::Node::file.
2635                                 $SVN::Node::dir.$SVN::Node::unknown.
2636                                 $SVN::Auth::SSL::CNMISMATCH.
2637                                 $SVN::Auth::SSL::NOTYETVALID.
2638                                 $SVN::Auth::SSL::EXPIRED.
2639                                 $SVN::Auth::SSL::UNKNOWNCA.
2640                                 $SVN::Auth::SSL::OTHER;
2641 }
2642
2643 package SVN::Git::Fetcher;
2644 use vars qw/@ISA/;
2645 use strict;
2646 use warnings;
2647 use Carp qw/croak/;
2648 use IO::File qw//;
2649
2650 # file baton members: path, mode_a, mode_b, pool, fh, blob, base
2651 sub new {
2652         my ($class, $git_svn) = @_;
2653         my $self = SVN::Delta::Editor->new;
2654         bless $self, $class;
2655         $self->{c} = $git_svn->{c} if exists $git_svn->{c};
2656         $self->{q} = $git_svn->{q};
2657         $self->{empty} = {};
2658         $self->{dir_prop} = {};
2659         $self->{file_prop} = {};
2660         $self->{absent_dir} = {};
2661         $self->{absent_file} = {};
2662         ($self->{gui}, $self->{ctx}) = command_input_pipe(
2663                                              qw/update-index -z --index-info/);
2664         require Digest::MD5;
2665         $self;
2666 }
2667
2668 sub open_root {
2669         { path => '' };
2670 }
2671
2672 sub open_directory {
2673         my ($self, $path, $pb, $rev) = @_;
2674         { path => $path };
2675 }
2676
2677 sub delete_entry {
2678         my ($self, $path, $rev, $pb) = @_;
2679         my $gui = $self->{gui};
2680
2681         # remove entire directories.
2682         if (command('ls-tree', $self->{c}, '--', $path) =~ /^040000 tree/) {
2683                 my ($ls, $ctx) = command_output_pipe(qw/ls-tree
2684                                                      -r --name-only -z/,
2685                                                      $self->{c}, '--', $path);
2686                 local $/ = "\0";
2687                 while (<$ls>) {
2688                         print $gui '0 ',0 x 40,"\t",$_ or croak $!;
2689                         print "\tD\t$_\n" unless $self->{q};
2690                 }
2691                 print "\tD\t$path/\n" unless $self->{q};
2692                 command_close_pipe($ls, $ctx);
2693                 $self->{empty}->{$path} = 0
2694         } else {
2695                 print $gui '0 ',0 x 40,"\t",$path,"\0" or croak $!;
2696                 print "\tD\t$path\n" unless $self->{q};
2697         }
2698         undef;
2699 }
2700
2701 sub open_file {
2702         my ($self, $path, $pb, $rev) = @_;
2703         my ($mode, $blob) = (command('ls-tree', $self->{c}, '--',$path)
2704                              =~ /^(\d{6}) blob ([a-f\d]{40})\t/);
2705         unless (defined $mode && defined $blob) {
2706                 die "$path was not found in commit $self->{c} (r$rev)\n";
2707         }
2708         { path => $path, mode_a => $mode, mode_b => $mode, blob => $blob,
2709           pool => SVN::Pool->new, action => 'M' };
2710 }
2711
2712 sub add_file {
2713         my ($self, $path, $pb, $cp_path, $cp_rev) = @_;
2714         my ($dir, $file) = ($path =~ m#^(.*?)/?([^/]+)$#);
2715         delete $self->{empty}->{$dir};
2716         { path => $path, mode_a => 100644, mode_b => 100644,
2717           pool => SVN::Pool->new, action => 'A' };
2718 }
2719
2720 sub add_directory {
2721         my ($self, $path, $cp_path, $cp_rev) = @_;
2722         my ($dir, $file) = ($path =~ m#^(.*?)/?([^/]+)$#);
2723         delete $self->{empty}->{$dir};
2724         $self->{empty}->{$path} = 1;
2725         { path => $path };
2726 }
2727
2728 sub change_dir_prop {
2729         my ($self, $db, $prop, $value) = @_;
2730         $self->{dir_prop}->{$db->{path}} ||= {};
2731         $self->{dir_prop}->{$db->{path}}->{$prop} = $value;
2732         undef;
2733 }
2734
2735 sub absent_directory {
2736         my ($self, $path, $pb) = @_;
2737         $self->{absent_dir}->{$pb->{path}} ||= [];
2738         push @{$self->{absent_dir}->{$pb->{path}}}, $path;
2739         undef;
2740 }
2741
2742 sub absent_file {
2743         my ($self, $path, $pb) = @_;
2744         $self->{absent_file}->{$pb->{path}} ||= [];
2745         push @{$self->{absent_file}->{$pb->{path}}}, $path;
2746         undef;
2747 }
2748
2749 sub change_file_prop {
2750         my ($self, $fb, $prop, $value) = @_;
2751         if ($prop eq 'svn:executable') {
2752                 if ($fb->{mode_b} != 120000) {
2753                         $fb->{mode_b} = defined $value ? 100755 : 100644;
2754                 }
2755         } elsif ($prop eq 'svn:special') {
2756                 $fb->{mode_b} = defined $value ? 120000 : 100644;
2757         } else {
2758                 $self->{file_prop}->{$fb->{path}} ||= {};
2759                 $self->{file_prop}->{$fb->{path}}->{$prop} = $value;
2760         }
2761         undef;
2762 }
2763
2764 sub apply_textdelta {
2765         my ($self, $fb, $exp) = @_;
2766         my $fh = IO::File->new_tmpfile;
2767         $fh->autoflush(1);
2768         # $fh gets auto-closed() by SVN::TxDelta::apply(),
2769         # (but $base does not,) so dup() it for reading in close_file
2770         open my $dup, '<&', $fh or croak $!;
2771         my $base = IO::File->new_tmpfile;
2772         $base->autoflush(1);
2773         if ($fb->{blob}) {
2774                 defined (my $pid = fork) or croak $!;
2775                 if (!$pid) {
2776                         open STDOUT, '>&', $base or croak $!;
2777                         print STDOUT 'link ' if ($fb->{mode_a} == 120000);
2778                         exec qw/git-cat-file blob/, $fb->{blob} or croak $!;
2779                 }
2780                 waitpid $pid, 0;
2781                 croak $? if $?;
2782
2783                 if (defined $exp) {
2784                         seek $base, 0, 0 or croak $!;
2785                         my $md5 = Digest::MD5->new;
2786                         $md5->addfile($base);
2787                         my $got = $md5->hexdigest;
2788                         die "Checksum mismatch: $fb->{path} $fb->{blob}\n",
2789                             "expected: $exp\n",
2790                             "     got: $got\n" if ($got ne $exp);
2791                 }
2792         }
2793         seek $base, 0, 0 or croak $!;
2794         $fb->{fh} = $dup;
2795         $fb->{base} = $base;
2796         [ SVN::TxDelta::apply($base, $fh, undef, $fb->{path}, $fb->{pool}) ];
2797 }
2798
2799 sub close_file {
2800         my ($self, $fb, $exp) = @_;
2801         my $hash;
2802         my $path = $fb->{path};
2803         if (my $fh = $fb->{fh}) {
2804                 seek($fh, 0, 0) or croak $!;
2805                 my $md5 = Digest::MD5->new;
2806                 $md5->addfile($fh);
2807                 my $got = $md5->hexdigest;
2808                 die "Checksum mismatch: $path\n",
2809                     "expected: $exp\n    got: $got\n" if ($got ne $exp);
2810                 seek($fh, 0, 0) or croak $!;
2811                 if ($fb->{mode_b} == 120000) {
2812                         read($fh, my $buf, 5) == 5 or croak $!;
2813                         $buf eq 'link ' or die "$path has mode 120000",
2814                                                "but is not a link\n";
2815                 }
2816                 defined(my $pid = open my $out,'-|') or die "Can't fork: $!\n";
2817                 if (!$pid) {
2818                         open STDIN, '<&', $fh or croak $!;
2819                         exec qw/git-hash-object -w --stdin/ or croak $!;
2820                 }
2821                 chomp($hash = do { local $/; <$out> });
2822                 close $out or croak $!;
2823                 close $fh or croak $!;
2824                 $hash =~ /^[a-f\d]{40}$/ or die "not a sha1: $hash\n";
2825                 close $fb->{base} or croak $!;
2826         } else {
2827                 $hash = $fb->{blob} or die "no blob information\n";
2828         }
2829         $fb->{pool}->clear;
2830         my $gui = $self->{gui};
2831         print $gui "$fb->{mode_b} $hash\t$path\0" or croak $!;
2832         print "\t$fb->{action}\t$path\n" if $fb->{action} && ! $self->{q};
2833         undef;
2834 }
2835
2836 sub abort_edit {
2837         my $self = shift;
2838         eval { command_close_pipe($self->{gui}, $self->{ctx}) };
2839         $self->SUPER::abort_edit(@_);
2840 }
2841
2842 sub close_edit {
2843         my $self = shift;
2844         command_close_pipe($self->{gui}, $self->{ctx});
2845         $self->{git_commit_ok} = 1;
2846         $self->SUPER::close_edit(@_);
2847 }
2848
2849 package SVN::Git::Editor;
2850 use vars qw/@ISA/;
2851 use strict;
2852 use warnings;
2853 use Carp qw/croak/;
2854 use IO::File;
2855
2856 sub new {
2857         my $class = shift;
2858         my $git_svn = shift;
2859         my $self = SVN::Delta::Editor->new(@_);
2860         bless $self, $class;
2861         foreach (qw/svn_path c r ra /) {
2862                 die "$_ required!\n" unless (defined $git_svn->{$_});
2863                 $self->{$_} = $git_svn->{$_};
2864         }
2865         $self->{pool} = SVN::Pool->new;
2866         $self->{bat} = { '' => $self->open_root($self->{r}, $self->{pool}) };
2867         $self->{rm} = { };
2868         require Digest::MD5;
2869         return $self;
2870 }
2871
2872 sub split_path {
2873         return ($_[0] =~ m#^(.*?)/?([^/]+)$#);
2874 }
2875
2876 sub repo_path {
2877         (defined $_[1] && length $_[1]) ? $_[1] : ''
2878 }
2879
2880 sub url_path {
2881         my ($self, $path) = @_;
2882         $self->{ra}->{url} . '/' . $self->repo_path($path);
2883 }
2884
2885 sub rmdirs {
2886         my ($self, $q) = @_;
2887         my $rm = $self->{rm};
2888         delete $rm->{''}; # we never delete the url we're tracking
2889         return unless %$rm;
2890
2891         foreach (keys %$rm) {
2892                 my @d = split m#/#, $_;
2893                 my $c = shift @d;
2894                 $rm->{$c} = 1;
2895                 while (@d) {
2896                         $c .= '/' . shift @d;
2897                         $rm->{$c} = 1;
2898                 }
2899         }
2900         delete $rm->{$self->{svn_path}};
2901         delete $rm->{''}; # we never delete the url we're tracking
2902         return unless %$rm;
2903
2904         my ($fh, $ctx) = command_output_pipe(
2905                                    qw/ls-tree --name-only -r -z/, $self->{c});
2906         local $/ = "\0";
2907         while (<$fh>) {
2908                 chomp;
2909                 my @dn = split m#/#, $_;
2910                 while (pop @dn) {
2911                         delete $rm->{join '/', @dn};
2912                 }
2913                 unless (%$rm) {
2914                         close $fh;
2915                         return;
2916                 }
2917         }
2918         command_close_pipe($fh, $ctx);
2919
2920         my ($r, $p, $bat) = ($self->{r}, $self->{pool}, $self->{bat});
2921         foreach my $d (sort { $b =~ tr#/#/# <=> $a =~ tr#/#/# } keys %$rm) {
2922                 $self->close_directory($bat->{$d}, $p);
2923                 my ($dn) = ($d =~ m#^(.*?)/?(?:[^/]+)$#);
2924                 print "\tD+\t$d/\n" unless $q;
2925                 $self->SUPER::delete_entry($d, $r, $bat->{$dn}, $p);
2926                 delete $bat->{$d};
2927         }
2928 }
2929
2930 sub open_or_add_dir {
2931         my ($self, $full_path, $baton) = @_;
2932         my $t = $self->{ra}->check_path($full_path, $self->{r});
2933         if ($t == $SVN::Node::none) {
2934                 return $self->add_directory($full_path, $baton,
2935                                                 undef, -1, $self->{pool});
2936         } elsif ($t == $SVN::Node::dir) {
2937                 return $self->open_directory($full_path, $baton,
2938                                                 $self->{r}, $self->{pool});
2939         }
2940         print STDERR "$full_path already exists in repository at ",
2941                 "r$self->{r} and it is not a directory (",
2942                 ($t == $SVN::Node::file ? 'file' : 'unknown'),"/$t)\n";
2943         exit 1;
2944 }
2945
2946 sub ensure_path {
2947         my ($self, $path) = @_;
2948         my $bat = $self->{bat};
2949         $path = $self->repo_path($path);
2950         return $bat->{''} unless (length $path);
2951         my @p = split m#/+#, $path;
2952         my $c = shift @p;
2953         $bat->{$c} ||= $self->open_or_add_dir($c, $bat->{''});
2954         while (@p) {
2955                 my $c0 = $c;
2956                 $c .= '/' . shift @p;
2957                 $bat->{$c} ||= $self->open_or_add_dir($c, $bat->{$c0});
2958         }
2959         return $bat->{$c};
2960 }
2961
2962 sub A {
2963         my ($self, $m, $q) = @_;
2964         my ($dir, $file) = split_path($m->{file_b});
2965         my $pbat = $self->ensure_path($dir);
2966         my $fbat = $self->add_file($self->repo_path($m->{file_b}), $pbat,
2967                                         undef, -1);
2968         print "\tA\t$m->{file_b}\n" unless $q;
2969         $self->chg_file($fbat, $m);
2970         $self->close_file($fbat,undef,$self->{pool});
2971 }
2972
2973 sub C {
2974         my ($self, $m, $q) = @_;
2975         my ($dir, $file) = split_path($m->{file_b});
2976         my $pbat = $self->ensure_path($dir);
2977         my $fbat = $self->add_file($self->repo_path($m->{file_b}), $pbat,
2978                                 $self->url_path($m->{file_a}), $self->{r});
2979         print "\tC\t$m->{file_a} => $m->{file_b}\n" unless $q;
2980         $self->chg_file($fbat, $m);
2981         $self->close_file($fbat,undef,$self->{pool});
2982 }
2983
2984 sub delete_entry {
2985         my ($self, $path, $pbat) = @_;
2986         my $rpath = $self->repo_path($path);
2987         my ($dir, $file) = split_path($rpath);
2988         $self->{rm}->{$dir} = 1;
2989         $self->SUPER::delete_entry($rpath, $self->{r}, $pbat, $self->{pool});
2990 }
2991
2992 sub R {
2993         my ($self, $m, $q) = @_;
2994         my ($dir, $file) = split_path($m->{file_b});
2995         my $pbat = $self->ensure_path($dir);
2996         my $fbat = $self->add_file($self->repo_path($m->{file_b}), $pbat,
2997                                 $self->url_path($m->{file_a}), $self->{r});
2998         print "\tR\t$m->{file_a} => $m->{file_b}\n" unless $q;
2999         $self->chg_file($fbat, $m);
3000         $self->close_file($fbat,undef,$self->{pool});
3001
3002         ($dir, $file) = split_path($m->{file_a});
3003         $pbat = $self->ensure_path($dir);
3004         $self->delete_entry($m->{file_a}, $pbat);
3005 }
3006
3007 sub M {
3008         my ($self, $m, $q) = @_;
3009         my ($dir, $file) = split_path($m->{file_b});
3010         my $pbat = $self->ensure_path($dir);
3011         my $fbat = $self->open_file($self->repo_path($m->{file_b}),
3012                                 $pbat,$self->{r},$self->{pool});
3013         print "\t$m->{chg}\t$m->{file_b}\n" unless $q;
3014         $self->chg_file($fbat, $m);
3015         $self->close_file($fbat,undef,$self->{pool});
3016 }
3017
3018 sub T { shift->M(@_) }
3019
3020 sub change_file_prop {
3021         my ($self, $fbat, $pname, $pval) = @_;
3022         $self->SUPER::change_file_prop($fbat, $pname, $pval, $self->{pool});
3023 }
3024
3025 sub chg_file {
3026         my ($self, $fbat, $m) = @_;
3027         if ($m->{mode_b} =~ /755$/ && $m->{mode_a} !~ /755$/) {
3028                 $self->change_file_prop($fbat,'svn:executable','*');
3029         } elsif ($m->{mode_b} !~ /755$/ && $m->{mode_a} =~ /755$/) {
3030                 $self->change_file_prop($fbat,'svn:executable',undef);
3031         }
3032         my $fh = IO::File->new_tmpfile or croak $!;
3033         if ($m->{mode_b} =~ /^120/) {
3034                 print $fh 'link ' or croak $!;
3035                 $self->change_file_prop($fbat,'svn:special','*');
3036         } elsif ($m->{mode_a} =~ /^120/ && $m->{mode_b} !~ /^120/) {
3037                 $self->change_file_prop($fbat,'svn:special',undef);
3038         }
3039         defined(my $pid = fork) or croak $!;
3040         if (!$pid) {
3041                 open STDOUT, '>&', $fh or croak $!;
3042                 exec qw/git-cat-file blob/, $m->{sha1_b} or croak $!;
3043         }
3044         waitpid $pid, 0;
3045         croak $? if $?;
3046         $fh->flush == 0 or croak $!;
3047         seek $fh, 0, 0 or croak $!;
3048
3049         my $md5 = Digest::MD5->new;
3050         $md5->addfile($fh) or croak $!;
3051         seek $fh, 0, 0 or croak $!;
3052
3053         my $exp = $md5->hexdigest;
3054         my $pool = SVN::Pool->new;
3055         my $atd = $self->apply_textdelta($fbat, undef, $pool);
3056         my $got = SVN::TxDelta::send_stream($fh, @$atd, $pool);
3057         die "Checksum mismatch\nexpected: $exp\ngot: $got\n" if ($got ne $exp);
3058         $pool->clear;
3059
3060         close $fh or croak $!;
3061 }
3062
3063 sub D {
3064         my ($self, $m, $q) = @_;
3065         my ($dir, $file) = split_path($m->{file_b});
3066         my $pbat = $self->ensure_path($dir);
3067         print "\tD\t$m->{file_b}\n" unless $q;
3068         $self->delete_entry($m->{file_b}, $pbat);
3069 }
3070
3071 sub close_edit {
3072         my ($self) = @_;
3073         my ($p,$bat) = ($self->{pool}, $self->{bat});
3074         foreach (sort { $b =~ tr#/#/# <=> $a =~ tr#/#/# } keys %$bat) {
3075                 $self->close_directory($bat->{$_}, $p);
3076         }
3077         $self->SUPER::close_edit($p);
3078         $p->clear;
3079 }
3080
3081 sub abort_edit {
3082         my ($self) = @_;
3083         $self->SUPER::abort_edit($self->{pool});
3084         $self->{pool}->clear;
3085 }
3086
3087 package Git::SVN::Ra;
3088 use vars qw/@ISA $config_dir/;
3089 use strict;
3090 use warnings;
3091 my ($can_do_switch);
3092
3093 BEGIN {
3094         # enforce temporary pool usage for some simple functions
3095         my $e;
3096         foreach (qw/get_latest_revnum rev_proplist get_file
3097                     check_path get_dir get_uuid get_repos_root/) {
3098                 $e .= "sub $_ {
3099                         my \$self = shift;
3100                         my \$pool = SVN::Pool->new;
3101                         my \@ret = \$self->SUPER::$_(\@_,\$pool);
3102                         \$pool->clear;
3103                         wantarray ? \@ret : \$ret[0]; }\n";
3104         }
3105         eval $e;
3106 }
3107
3108 sub new {
3109         my ($class, $url) = @_;
3110         SVN::_Core::svn_config_ensure($config_dir, undef);
3111         my ($baton, $callbacks) = SVN::Core::auth_open_helper([
3112             SVN::Client::get_simple_provider(),
3113             SVN::Client::get_ssl_server_trust_file_provider(),
3114             SVN::Client::get_simple_prompt_provider(
3115               \&Git::SVN::Prompt::simple, 2),
3116             SVN::Client::get_ssl_client_cert_prompt_provider(
3117               \&Git::SVN::Prompt::ssl_client_cert, 2),
3118             SVN::Client::get_ssl_client_cert_pw_prompt_provider(
3119               \&Git::SVN::Prompt::ssl_client_cert_pw, 2),
3120             SVN::Client::get_username_provider(),
3121             SVN::Client::get_ssl_server_trust_prompt_provider(
3122               \&Git::SVN::Prompt::ssl_server_trust),
3123             SVN::Client::get_username_prompt_provider(
3124               \&Git::SVN::Prompt::username, 2),
3125           ]);
3126         my $config = SVN::Core::config_get_config($config_dir);
3127         my $self = SVN::Ra->new(url => $url, auth => $baton,
3128                               config => $config,
3129                               pool => SVN::Pool->new,
3130                               auth_provider_callbacks => $callbacks);
3131         $self->{svn_path} = $url;
3132         $self->{repos_root} = $self->get_repos_root;
3133         $self->{svn_path} =~ s#^\Q$self->{repos_root}\E/*##;
3134         bless $self, $class;
3135 }
3136
3137 sub DESTROY {
3138         my $self = shift;
3139         $self->{pool}->clear if $self->{pool};
3140         $self->SUPER::DESTROY(@_);
3141 }
3142
3143 sub dup {
3144         my ($self) = @_;
3145         my $dup = SVN::Ra->new(pool => SVN::Pool->new,
3146                                 map { $_ => $self->{$_} } qw/config url
3147                      auth auth_provider_callbacks repos_root svn_path/);
3148         bless $dup, ref $self;
3149 }
3150
3151 sub get_log {
3152         my ($self, @args) = @_;
3153         my $pool = SVN::Pool->new;
3154         $args[4]-- if $args[4] && ! $::_follow_parent;
3155         splice(@args, 3, 1) if ($SVN::Core::VERSION le '1.2.0');
3156         my $ret = $self->SUPER::get_log(@args, $pool);
3157         $pool->clear;
3158         $ret;
3159 }
3160
3161 sub get_commit_editor {
3162         my ($self, $msg, $cb, $pool) = @_;
3163         my @lock = $SVN::Core::VERSION ge '1.2.0' ? (undef, 0) : ();
3164         $self->SUPER::get_commit_editor($msg, $cb, @lock, $pool);
3165 }
3166
3167 sub uuid {
3168         my ($self) = @_;
3169         $self->{uuid} ||= $self->get_uuid;
3170 }
3171
3172 sub gs_do_update {
3173         my ($self, $rev_a, $rev_b, $path, $recurse, $editor) = @_;
3174         my $pool = SVN::Pool->new;
3175         my $reporter = $self->do_update($rev_b, $path, $recurse,
3176                                         $editor, $pool);
3177         my @lock = $SVN::Core::VERSION ge '1.2.0' ? (undef) : ();
3178         my $new = ($rev_a == $rev_b);
3179         $reporter->set_path($path, $rev_a, $new, @lock, $pool);
3180         $reporter->finish_report($pool);
3181         $pool->clear;
3182         $editor->{git_commit_ok};
3183 }
3184
3185 sub gs_do_switch {
3186         my ($self, $rev_a, $rev_b, $path, $recurse, $url_b, $editor) = @_;
3187         my $pool = SVN::Pool->new;
3188         my $reporter = $self->do_switch($rev_b, $path, $recurse,
3189                                         $url_b, $editor, $pool);
3190         my @lock = $SVN::Core::VERSION ge '1.2.0' ? (undef) : ();
3191         $reporter->set_path($path, $rev_a, 0, @lock, $pool);
3192         $reporter->finish_report($pool);
3193         $pool->clear;
3194         $editor->{git_commit_ok};
3195 }
3196
3197 sub can_do_switch {
3198         my $self = shift;
3199         unless (defined $can_do_switch) {
3200                 my $pool = SVN::Pool->new;
3201                 my $rep = eval {
3202                         $self->do_switch(1, '', 0, $self->{url},
3203                                          SVN::Delta::Editor->new, $pool);
3204                 };
3205                 if ($@) {
3206                         $can_do_switch = 0;
3207                 } else {
3208                         $rep->abort_report($pool);
3209                         $can_do_switch = 1;
3210                 }
3211                 $pool->clear;
3212         }
3213         $can_do_switch;
3214 }
3215
3216 package Git::SVN::Log;
3217 use strict;
3218 use warnings;
3219 use POSIX qw/strftime/;
3220 use vars qw/$TZ $limit $color $pager $non_recursive $verbose $oneline
3221             %rusers $show_commit $incremental/;
3222 my $l_fmt;
3223
3224 sub cmt_showable {
3225         my ($c) = @_;
3226         return 1 if defined $c->{r};
3227         if ($c->{l} && $c->{l}->[-1] eq "...\n" &&
3228                                 $c->{a_raw} =~ /\@([a-f\d\-]+)>$/) {
3229                 my @msg = command(qw/cat-file commit/, $c->{c});
3230                 shift @msg while ($msg[0] ne "\n");
3231                 shift @msg;
3232                 @{$c->{l}} = grep !/^git-svn-id: /, @msg;
3233
3234                 (undef, $c->{r}, undef) = ::extract_metadata(
3235                                 (grep(/^git-svn-id: /, @msg))[-1]);
3236         }
3237         return defined $c->{r};
3238 }
3239
3240 sub log_use_color {
3241         return 1 if $color;
3242         my ($dc, $dcvar);
3243         $dcvar = 'color.diff';
3244         $dc = `git-config --get $dcvar`;
3245         if ($dc eq '') {
3246                 # nothing at all; fallback to "diff.color"
3247                 $dcvar = 'diff.color';
3248                 $dc = `git-config --get $dcvar`;
3249         }
3250         chomp($dc);
3251         if ($dc eq 'auto') {
3252                 my $pc;
3253                 $pc = `git-config --get color.pager`;
3254                 if ($pc eq '') {
3255                         # does not have it -- fallback to pager.color
3256                         $pc = `git-config --bool --get pager.color`;
3257                 }
3258                 else {
3259                         $pc = `git-config --bool --get color.pager`;
3260                         if ($?) {
3261                                 $pc = 'false';
3262                         }
3263                 }
3264                 chomp($pc);
3265                 if (-t *STDOUT || (defined $pager && $pc eq 'true')) {
3266                         return ($ENV{TERM} && $ENV{TERM} ne 'dumb');
3267                 }
3268                 return 0;
3269         }
3270         return 0 if $dc eq 'never';
3271         return 1 if $dc eq 'always';
3272         chomp($dc = `git-config --bool --get $dcvar`);
3273         return ($dc eq 'true');
3274 }
3275
3276 sub git_svn_log_cmd {
3277         my ($r_min, $r_max) = @_;
3278         my $gs = Git::SVN->_new;
3279         my @cmd = (qw/log --abbrev-commit --pretty=raw --default/,
3280                    $gs->refname);
3281         push @cmd, '-r' unless $non_recursive;
3282         push @cmd, qw/--raw --name-status/ if $verbose;
3283         push @cmd, '--color' if log_use_color();
3284         return @cmd unless defined $r_max;
3285         if ($r_max == $r_min) {
3286                 push @cmd, '--max-count=1';
3287                 if (my $c = $gs->rev_db_get($r_max)) {
3288                         push @cmd, $c;
3289                 }
3290         } else {
3291                 my ($c_min, $c_max);
3292                 $c_max = $gs->rev_db_get($r_max);
3293                 $c_min = $gs->rev_db_get($r_min);
3294                 if (defined $c_min && defined $c_max) {
3295                         if ($r_max > $r_max) {
3296                                 push @cmd, "$c_min..$c_max";
3297                         } else {
3298                                 push @cmd, "$c_max..$c_min";
3299                         }
3300                 } elsif ($r_max > $r_min) {
3301                         push @cmd, $c_max;
3302                 } else {
3303                         push @cmd, $c_min;
3304                 }
3305         }
3306         return @cmd;
3307 }
3308
3309 # adapted from pager.c
3310 sub config_pager {
3311         $pager ||= $ENV{GIT_PAGER} || $ENV{PAGER};
3312         if (!defined $pager) {
3313                 $pager = 'less';
3314         } elsif (length $pager == 0 || $pager eq 'cat') {
3315                 $pager = undef;
3316         }
3317 }
3318
3319 sub run_pager {
3320         return unless -t *STDOUT;
3321         pipe my $rfd, my $wfd or return;
3322         defined(my $pid = fork) or ::fatal "Can't fork: $!\n";
3323         if (!$pid) {
3324                 open STDOUT, '>&', $wfd or
3325                                      ::fatal "Can't redirect to stdout: $!\n";
3326                 return;
3327         }
3328         open STDIN, '<&', $rfd or ::fatal "Can't redirect stdin: $!\n";
3329         $ENV{LESS} ||= 'FRSX';
3330         exec $pager or ::fatal "Can't run pager: $! ($pager)\n";
3331 }
3332
3333 sub get_author_info {
3334         my ($dest, $author, $t, $tz) = @_;
3335         $author =~ s/(?:^\s*|\s*$)//g;
3336         $dest->{a_raw} = $author;
3337         my $au;
3338         if ($_authors) {
3339                 $au = $rusers{$author} || undef;
3340         }
3341         if (!$au) {
3342                 ($au) = ($author =~ /<([^>]+)\@[^>]+>$/);
3343         }
3344         $dest->{t} = $t;
3345         $dest->{tz} = $tz;
3346         $dest->{a} = $au;
3347         # Date::Parse isn't in the standard Perl distro :(
3348         if ($tz =~ s/^\+//) {
3349                 $t += ::tz_to_s_offset($tz);
3350         } elsif ($tz =~ s/^\-//) {
3351                 $t -= ::tz_to_s_offset($tz);
3352         }
3353         $dest->{t_utc} = $t;
3354 }
3355
3356 sub process_commit {
3357         my ($c, $r_min, $r_max, $defer) = @_;
3358         if (defined $r_min && defined $r_max) {
3359                 if ($r_min == $c->{r} && $r_min == $r_max) {
3360                         show_commit($c);
3361                         return 0;
3362                 }
3363                 return 1 if $r_min == $r_max;
3364                 if ($r_min < $r_max) {
3365                         # we need to reverse the print order
3366                         return 0 if (defined $limit && --$limit < 0);
3367                         push @$defer, $c;
3368                         return 1;
3369                 }
3370                 if ($r_min != $r_max) {
3371                         return 1 if ($r_min < $c->{r});
3372                         return 1 if ($r_max > $c->{r});
3373                 }
3374         }
3375         return 0 if (defined $limit && --$limit < 0);
3376         show_commit($c);
3377         return 1;
3378 }
3379
3380 sub show_commit {
3381         my $c = shift;
3382         if ($oneline) {
3383                 my $x = "\n";
3384                 if (my $l = $c->{l}) {
3385                         while ($l->[0] =~ /^\s*$/) { shift @$l }
3386                         $x = $l->[0];
3387                 }
3388                 $l_fmt ||= 'A' . length($c->{r});
3389                 print 'r',pack($l_fmt, $c->{r}),' | ';
3390                 print "$c->{c} | " if $show_commit;
3391                 print $x;
3392         } else {
3393                 show_commit_normal($c);
3394         }
3395 }
3396
3397 sub show_commit_changed_paths {
3398         my ($c) = @_;
3399         return unless $c->{changed};
3400         print "Changed paths:\n", @{$c->{changed}};
3401 }
3402
3403 sub show_commit_normal {
3404         my ($c) = @_;
3405         print '-' x72, "\nr$c->{r} | ";
3406         print "$c->{c} | " if $show_commit;
3407         print "$c->{a} | ", strftime("%Y-%m-%d %H:%M:%S %z (%a, %d %b %Y)",
3408                                  localtime($c->{t_utc})), ' | ';
3409         my $nr_line = 0;
3410
3411         if (my $l = $c->{l}) {
3412                 while ($l->[$#$l] eq "\n" && $#$l > 0
3413                                           && $l->[($#$l - 1)] eq "\n") {
3414                         pop @$l;
3415                 }
3416                 $nr_line = scalar @$l;
3417                 if (!$nr_line) {
3418                         print "1 line\n\n\n";
3419                 } else {
3420                         if ($nr_line == 1) {
3421                                 $nr_line = '1 line';
3422                         } else {
3423                                 $nr_line .= ' lines';
3424                         }
3425                         print $nr_line, "\n";
3426                         show_commit_changed_paths($c);
3427                         print "\n";
3428                         print $_ foreach @$l;
3429                 }
3430         } else {
3431                 print "1 line\n";
3432                 show_commit_changed_paths($c);
3433                 print "\n";
3434
3435         }
3436         foreach my $x (qw/raw diff/) {
3437                 if ($c->{$x}) {
3438                         print "\n";
3439                         print $_ foreach @{$c->{$x}}
3440                 }
3441         }
3442 }
3443
3444 sub cmd_show_log {
3445         my (@args) = @_;
3446         my ($r_min, $r_max);
3447         my $r_last = -1; # prevent dupes
3448         if (defined $TZ) {
3449                 $ENV{TZ} = $TZ;
3450         } else {
3451                 delete $ENV{TZ};
3452         }
3453         if (defined $::_revision) {
3454                 if ($::_revision =~ /^(\d+):(\d+)$/) {
3455                         ($r_min, $r_max) = ($1, $2);
3456                 } elsif ($::_revision =~ /^\d+$/) {
3457                         $r_min = $r_max = $::_revision;
3458                 } else {
3459                         ::fatal "-r$::_revision is not supported, use ",
3460                                 "standard \'git log\' arguments instead\n";
3461                 }
3462         }
3463
3464         config_pager();
3465         @args = (git_svn_log_cmd($r_min, $r_max), @args);
3466         my $log = command_output_pipe(@args);
3467         run_pager();
3468         my (@k, $c, $d);
3469         my $esc_color = qr/(?:\033\[(?:(?:\d+;)*\d*)?m)*/;
3470         while (<$log>) {
3471                 if (/^${esc_color}commit ($::sha1_short)/o) {
3472                         my $cmt = $1;
3473                         if ($c && cmt_showable($c) && $c->{r} != $r_last) {
3474                                 $r_last = $c->{r};
3475                                 process_commit($c, $r_min, $r_max, \@k) or
3476                                                                 goto out;
3477                         }
3478                         $d = undef;
3479                         $c = { c => $cmt };
3480                 } elsif (/^${esc_color}author (.+) (\d+) ([\-\+]?\d+)$/o) {
3481                         get_author_info($c, $1, $2, $3);
3482                 } elsif (/^${esc_color}(?:tree|parent|committer) /o) {
3483                         # ignore
3484                 } elsif (/^${esc_color}:\d{6} \d{6} $::sha1_short/o) {
3485                         push @{$c->{raw}}, $_;
3486                 } elsif (/^${esc_color}[ACRMDT]\t/) {
3487                         # we could add $SVN->{svn_path} here, but that requires
3488                         # remote access at the moment (repo_path_split)...
3489                         s#^(${esc_color})([ACRMDT])\t#$1   $2 #o;
3490                         push @{$c->{changed}}, $_;
3491                 } elsif (/^${esc_color}diff /o) {
3492                         $d = 1;
3493                         push @{$c->{diff}}, $_;
3494                 } elsif ($d) {
3495                         push @{$c->{diff}}, $_;
3496                 } elsif (/^${esc_color}    (git-svn-id:.+)$/o) {
3497                         ($c->{url}, $c->{r}, undef) = ::extract_metadata($1);
3498                 } elsif (s/^${esc_color}    //o) {
3499                         push @{$c->{l}}, $_;
3500                 }
3501         }
3502         if ($c && defined $c->{r} && $c->{r} != $r_last) {
3503                 $r_last = $c->{r};
3504                 process_commit($c, $r_min, $r_max, \@k);
3505         }
3506         if (@k) {
3507                 my $swap = $r_max;
3508                 $r_max = $r_min;
3509                 $r_min = $swap;
3510                 process_commit($_, $r_min, $r_max) foreach reverse @k;
3511         }
3512 out:
3513         eval { command_close_pipe($log) };
3514         print '-' x72,"\n" unless $incremental || $oneline;
3515 }
3516
3517 __END__
3518
3519 Data structures:
3520
3521 $log_msg hashref as returned by libsvn_log_entry()
3522 {
3523         msg => 'whitespace-formatted log entry
3524 ',                                              # trailing newline is preserved
3525         revision => '8',                        # integer
3526         date => '2004-02-24T17:01:44.108345Z',  # commit date
3527         author => 'committer name'
3528 };
3529
3530 @mods = array of diff-index line hashes, each element represents one line
3531         of diff-index output
3532
3533 diff-index line ($m hash)
3534 {
3535         mode_a => first column of diff-index output, no leading ':',
3536         mode_b => second column of diff-index output,
3537         sha1_b => sha1sum of the final blob,
3538         chg => change type [MCRADT],
3539         file_a => original file name of a file (iff chg is 'C' or 'R')
3540         file_b => new/current file name of a file (any chg)
3541 }
3542 ;
3543
3544 # retval of read_url_paths{,_all}();
3545 $l_map = {
3546         # repository root url
3547         'https://svn.musicpd.org' => {
3548                 # repository path               # GIT_SVN_ID
3549                 'mpd/trunk'             =>      'trunk',
3550                 'mpd/tags/0.11.5'       =>      'tags/0.11.5',
3551         },
3552 }
3553
3554 Notes:
3555         I don't trust the each() function on unless I created %hash myself
3556         because the internal iterator may not have started at base.