Code

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