Code

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