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