Code

git-svn: do our best to ensure that our ref and rev_db are consistent
[git.git] / git-svn.perl
1 #!/usr/bin/env perl
2 # Copyright (C) 2006, Eric Wong <normalperson@yhbt.net>
3 # License: GPL v2 or later
4 use warnings;
5 use strict;
6 use vars qw/    $AUTHOR $VERSION
7                 $sha1 $sha1_short $_revision
8                 $_q $_authors %users/;
9 $AUTHOR = 'Eric Wong <normalperson@yhbt.net>';
10 $VERSION = '@@GIT_VERSION@@';
12 $ENV{GIT_DIR} ||= '.git';
13 $Git::SVN::default_repo_id = 'git-svn';
14 $Git::SVN::default_ref_id = $ENV{GIT_SVN_ID} || 'git-svn';
16 $Git::SVN::Log::TZ = $ENV{TZ};
17 $ENV{TZ} = 'UTC';
18 $| = 1; # unbuffer STDOUT
20 sub fatal (@) { print STDERR @_; exit 1 }
21 require SVN::Core; # use()-ing this causes segfaults for me... *shrug*
22 require SVN::Ra;
23 require SVN::Delta;
24 if ($SVN::Core::VERSION lt '1.1.0') {
25         fatal "Need SVN::Core 1.1.0 or better (got $SVN::Core::VERSION)\n";
26 }
27 push @Git::SVN::Ra::ISA, 'SVN::Ra';
28 push @SVN::Git::Editor::ISA, 'SVN::Delta::Editor';
29 push @SVN::Git::Fetcher::ISA, 'SVN::Delta::Editor';
30 use Carp qw/croak/;
31 use IO::File qw//;
32 use File::Basename qw/dirname basename/;
33 use File::Path qw/mkpath/;
34 use Getopt::Long qw/:config gnu_getopt no_ignore_case auto_abbrev pass_through/;
35 use IPC::Open3;
36 use Git;
38 BEGIN {
39         my $s;
40         foreach (qw/command command_oneline command_noisy command_output_pipe
41                     command_input_pipe command_close_pipe/) {
42                 $s .= "*SVN::Git::Editor::$_ = *SVN::Git::Fetcher::$_ = ".
43                       "*Git::SVN::Migration::$_ = ".
44                       "*Git::SVN::Log::$_ = *Git::SVN::$_ = *$_ = *Git::$_; ";
45         }
46         eval $s;
47 }
49 my ($SVN);
51 my $_optimize_commits = 1 unless $ENV{GIT_SVN_NO_OPTIMIZE_COMMITS};
52 $sha1 = qr/[a-f\d]{40}/;
53 $sha1_short = qr/[a-f\d]{4,40}/;
54 my ($_stdin, $_help, $_edit,
55         $_message, $_file,
56         $_template, $_shared,
57         $_version,
58         $_merge, $_strategy, $_dry_run,
59         $_prefix);
61 my %remote_opts = ( 'username=s' => \$Git::SVN::Prompt::_username,
62                     'config-dir=s' => \$Git::SVN::Ra::config_dir,
63                     'no-auth-cache' => \$Git::SVN::Prompt::_no_auth_cache );
64 my %fc_opts = ( 'follow-parent|follow' => \$Git::SVN::_follow_parent,
65                 'authors-file|A=s' => \$_authors,
66                 'repack:i' => \$Git::SVN::_repack,
67                 'no-metadata' => \$Git::SVN::_no_metadata,
68                 'quiet|q' => \$_q,
69                 'repack-flags|repack-args|repack-opts=s' =>
70                    \$Git::SVN::_repack_flags,
71                 %remote_opts );
73 my ($_trunk, $_tags, $_branches);
74 my %multi_opts = ( 'trunk|T=s' => \$_trunk,
75                 'tags|t=s' => \$_tags,
76                 'branches|b=s' => \$_branches );
77 my %init_opts = ( 'template=s' => \$_template, 'shared' => \$_shared );
78 my %cmt_opts = ( 'edit|e' => \$_edit,
79                 'rmdir' => \$SVN::Git::Editor::_rmdir,
80                 'find-copies-harder' => \$SVN::Git::Editor::_find_copies_harder,
81                 'l=i' => \$SVN::Git::Editor::_rename_limit,
82                 'copy-similarity|C=i'=> \$SVN::Git::Editor::_cp_similarity
83 );
85 my %cmd = (
86         fetch => [ \&cmd_fetch, "Download new revisions from SVN",
87                         { 'revision|r=s' => \$_revision, %fc_opts } ],
88         init => [ \&cmd_init, "Initialize a repo for tracking" .
89                           " (requires URL argument)",
90                           \%init_opts ],
91         dcommit => [ \&cmd_dcommit,
92                      'Commit several diffs to merge with upstream',
93                         { 'merge|m|M' => \$_merge,
94                           'strategy|s=s' => \$_strategy,
95                           'dry-run|n' => \$_dry_run,
96                         %cmt_opts, %fc_opts } ],
97         'set-tree' => [ \&cmd_set_tree,
98                         "Set an SVN repository to a git tree-ish",
99                         { 'stdin|' => \$_stdin, %cmt_opts, %fc_opts, } ],
100         'show-ignore' => [ \&cmd_show_ignore, "Show svn:ignore listings",
101                         { 'revision|r=i' => \$_revision } ],
102         'multi-init' => [ \&cmd_multi_init,
103                         'Initialize multiple trees (like git-svnimport)',
104                         { %multi_opts, %init_opts, %remote_opts,
105                          'revision|r=i' => \$_revision,
106                          'prefix=s' => \$_prefix,
107                         } ],
108         'multi-fetch' => [ \&cmd_multi_fetch,
109                         'Fetch multiple trees (like git-svnimport)',
110                         \%fc_opts ],
111         'migrate' => [ sub { },
112                        # no-op, we automatically run this anyways,
113                        'Migrate configuration/metadata/layout from
114                         previous versions of git-svn',
115                         \%remote_opts ],
116         'log' => [ \&Git::SVN::Log::cmd_show_log, 'Show commit logs',
117                         { 'limit=i' => \$Git::SVN::Log::limit,
118                           'revision|r=s' => \$_revision,
119                           'verbose|v' => \$Git::SVN::Log::verbose,
120                           'incremental' => \$Git::SVN::Log::incremental,
121                           'oneline' => \$Git::SVN::Log::oneline,
122                           'show-commit' => \$Git::SVN::Log::show_commit,
123                           'non-recursive' => \$Git::SVN::Log::non_recursive,
124                           'authors-file|A=s' => \$_authors,
125                           'color' => \$Git::SVN::Log::color,
126                           'pager=s' => \$Git::SVN::Log::pager,
127                         } ],
128         'commit-diff' => [ \&cmd_commit_diff,
129                            'Commit a diff between two trees',
130                         { 'message|m=s' => \$_message,
131                           'file|F=s' => \$_file,
132                           'revision|r=s' => \$_revision,
133                         %cmt_opts } ],
134 );
136 my $cmd;
137 for (my $i = 0; $i < @ARGV; $i++) {
138         if (defined $cmd{$ARGV[$i]}) {
139                 $cmd = $ARGV[$i];
140                 splice @ARGV, $i, 1;
141                 last;
142         }
143 };
145 my %opts = %{$cmd{$cmd}->[2]} if (defined $cmd);
147 read_repo_config(\%opts);
148 my $rv = GetOptions(%opts, 'help|H|h' => \$_help, 'version|V' => \$_version,
149                     'minimize-connections' => \$Git::SVN::Migration::_minimize,
150                     'id|i=s' => \$Git::SVN::default_ref_id,
151                     'svn-remote|remote|R=s' => \$Git::SVN::default_repo_id);
152 exit 1 if (!$rv && $cmd ne 'log');
154 usage(0) if $_help;
155 version() if $_version;
156 usage(1) unless defined $cmd;
157 load_authors() if $_authors;
158 unless ($cmd =~ /^(?:init|multi-init|commit-diff)$/) {
159         Git::SVN::Migration::migration_check();
161 Git::SVN::init_vars();
162 eval {
163         Git::SVN::verify_remotes_sanity();
164         $cmd{$cmd}->[0]->(@ARGV);
165 };
166 fatal $@ if $@;
167 exit 0;
169 ####################### primary functions ######################
170 sub usage {
171         my $exit = shift || 0;
172         my $fd = $exit ? \*STDERR : \*STDOUT;
173         print $fd <<"";
174 git-svn - bidirectional operations between a single Subversion tree and git
175 Usage: $0 <command> [options] [arguments]\n
177         print $fd "Available commands:\n" unless $cmd;
179         foreach (sort keys %cmd) {
180                 next if $cmd && $cmd ne $_;
181                 print $fd '  ',pack('A17',$_),$cmd{$_}->[1],"\n";
182                 foreach (keys %{$cmd{$_}->[2]}) {
183                         # prints out arguments as they should be passed:
184                         my $x = s#[:=]s$## ? '<arg>' : s#[:=]i$## ? '<num>' : '';
185                         print $fd ' ' x 21, join(', ', map { length $_ > 1 ?
186                                                         "--$_" : "-$_" }
187                                                 split /\|/,$_)," $x\n";
188                 }
189         }
190         print $fd <<"";
191 \nGIT_SVN_ID may be set in the environment or via the --id/-i switch to an
192 arbitrary identifier if you're tracking multiple SVN branches/repositories in
193 one git repository and want to keep them separate.  See git-svn(1) for more
194 information.
196         exit $exit;
199 sub version {
200         print "git-svn version $VERSION (svn $SVN::Core::VERSION)\n";
201         exit 0;
204 sub do_git_init_db {
205         unless (-d $ENV{GIT_DIR}) {
206                 my @init_db = ('init');
207                 push @init_db, "--template=$_template" if defined $_template;
208                 push @init_db, "--shared" if defined $_shared;
209                 command_noisy(@init_db);
210         }
213 sub cmd_init {
214         my $url = shift or die "SVN repository location required " .
215                                 "as a command-line argument\n";
216         if (my $repo_path = shift) {
217                 unless (-d $repo_path) {
218                         mkpath([$repo_path]);
219                 }
220                 chdir $repo_path or croak $!;
221                 $ENV{GIT_DIR} = $repo_path . "/.git";
222         }
223         do_git_init_db();
225         Git::SVN->init($url);
228 sub cmd_fetch {
229         if (@_) {
230                 die "Additional fetch arguments are no longer supported.\n",
231                     "Use --follow-parent if you have moved/copied directories
232                     instead.\n";
233         }
234         my $gs = Git::SVN->new;
235         $gs->fetch(parse_revision_argument());
236         if ($gs->{last_commit} && !verify_ref('refs/heads/master^0')) {
237                 command_noisy(qw(update-ref refs/heads/master),
238                               $gs->{last_commit});
239         }
242 sub cmd_set_tree {
243         my (@commits) = @_;
244         if ($_stdin || !@commits) {
245                 print "Reading from stdin...\n";
246                 @commits = ();
247                 while (<STDIN>) {
248                         if (/\b($sha1_short)\b/o) {
249                                 unshift @commits, $1;
250                         }
251                 }
252         }
253         my @revs;
254         foreach my $c (@commits) {
255                 my @tmp = command('rev-parse',$c);
256                 if (scalar @tmp == 1) {
257                         push @revs, $tmp[0];
258                 } elsif (scalar @tmp > 1) {
259                         push @revs, reverse(command('rev-list',@tmp));
260                 } else {
261                         fatal "Failed to rev-parse $c\n";
262                 }
263         }
264         my $gs = Git::SVN->new;
265         my ($r_last, $cmt_last) = $gs->last_rev_commit;
266         $gs->fetch;
267         if (defined $gs->{last_rev} && $r_last != $gs->{last_rev}) {
268                 fatal "There are new revisions that were fetched ",
269                       "and need to be merged (or acknowledged) ",
270                       "before committing.\nlast rev: $r_last\n",
271                       " current: $gs->{last_rev}\n";
272         }
273         $gs->set_tree($_) foreach @revs;
274         print "Done committing ",scalar @revs," revisions to SVN\n";
277 sub cmd_dcommit {
278         my $head = shift;
279         my $gs = Git::SVN->new;
280         $head ||= 'HEAD';
281         my @refs = command(qw/rev-list --no-merges/, $gs->refname."..$head");
282         my $last_rev;
283         foreach my $d (reverse @refs) {
284                 if (!verify_ref("$d~1")) {
285                         fatal "Commit $d\n",
286                               "has no parent commit, and therefore ",
287                               "nothing to diff against.\n",
288                               "You should be working from a repository ",
289                               "originally created by git-svn\n";
290                 }
291                 unless (defined $last_rev) {
292                         (undef, $last_rev, undef) = cmt_metadata("$d~1");
293                         unless (defined $last_rev) {
294                                 fatal "Unable to extract revision information ",
295                                       "from commit $d~1\n";
296                         }
297                 }
298                 if ($_dry_run) {
299                         print "diff-tree $d~1 $d\n";
300                 } else {
301                         my %ed_opts = ( r => $last_rev,
302                                         log => get_commit_entry($d)->{log},
303                                         ra => $gs->ra,
304                                         tree_a => "$d~1",
305                                         tree_b => $d,
306                                         editor_cb => sub {
307                                                print "Committed r$_[0]\n";
308                                                $last_rev = $_[0]; },
309                                         svn_path => $gs->{path} );
310                         if (!SVN::Git::Editor->new(\%ed_opts)->apply_diff) {
311                                 print "No changes\n$d~1 == $d\n";
312                         }
313                 }
314         }
315         return if $_dry_run;
316         $gs->fetch;
317         # we always want to rebase against the current HEAD, not any
318         # head that was passed to us
319         my @diff = command('diff-tree', 'HEAD', $gs->refname, '--');
320         my @finish;
321         if (@diff) {
322                 @finish = qw/rebase/;
323                 push @finish, qw/--merge/ if $_merge;
324                 push @finish, "--strategy=$_strategy" if $_strategy;
325                 print STDERR "W: HEAD and ", $gs->refname, " differ, ",
326                              "using @finish:\n", "@diff";
327         } else {
328                 print "No changes between current HEAD and ",
329                       $gs->refname, "\nResetting to the latest ",
330                       $gs->refname, "\n";
331                 @finish = qw/reset --mixed/;
332         }
333         command_noisy(@finish, $gs->refname);
336 sub cmd_show_ignore {
337         my $gs = Git::SVN->new;
338         my $r = (defined $_revision ? $_revision : $gs->ra->get_latest_revnum);
339         $gs->traverse_ignore(\*STDOUT, '', $r);
342 sub cmd_multi_init {
343         my $url = shift;
344         unless (defined $_trunk || defined $_branches || defined $_tags) {
345                 usage(1);
346         }
347         do_git_init_db();
348         $_prefix = '' unless defined $_prefix;
349         $url =~ s#/+$## if defined $url;
350         if (defined $_trunk) {
351                 my $trunk_ref = $_prefix . 'trunk';
352                 # try both old-style and new-style lookups:
353                 my $gs_trunk = eval { Git::SVN->new($trunk_ref) };
354                 unless ($gs_trunk) {
355                         my ($trunk_url, $trunk_path) =
356                                               complete_svn_url($url, $_trunk);
357                         $gs_trunk = Git::SVN->init($trunk_url, $trunk_path,
358                                                    undef, $trunk_ref);
359                 }
360         }
361         return unless defined $_branches || defined $_tags;
362         my $ra = $url ? Git::SVN::Ra->new($url) : undef;
363         complete_url_ls_init($ra, $_branches, '--branches/-b', $_prefix);
364         complete_url_ls_init($ra, $_tags, '--tags/-t', $_prefix . 'tags/');
367 sub cmd_multi_fetch {
368         my $remotes = Git::SVN::read_all_remotes();
369         foreach my $repo_id (sort keys %$remotes) {
370                 my $url = $remotes->{$repo_id}->{url} or next;
371                 my $fetch = $remotes->{$repo_id}->{fetch} or next;
372                 Git::SVN::fetch_all($repo_id, $url, $fetch);
373         }
376 # this command is special because it requires no metadata
377 sub cmd_commit_diff {
378         my ($ta, $tb, $url) = @_;
379         my $usage = "Usage: $0 commit-diff -r<revision> ".
380                     "<tree-ish> <tree-ish> [<URL>]\n";
381         fatal($usage) if (!defined $ta || !defined $tb);
382         my $svn_path;
383         if (!defined $url) {
384                 my $gs = eval { Git::SVN->new };
385                 if (!$gs) {
386                         fatal("Needed URL or usable git-svn --id in ",
387                               "the command-line\n", $usage);
388                 }
389                 $url = $gs->{url};
390                 $svn_path = $gs->{path};
391         }
392         unless (defined $_revision) {
393                 fatal("-r|--revision is a required argument\n", $usage);
394         }
395         if (defined $_message && defined $_file) {
396                 fatal("Both --message/-m and --file/-F specified ",
397                       "for the commit message.\n",
398                       "I have no idea what you mean\n");
399         }
400         if (defined $_file) {
401                 $_message = file_to_s($_file);
402         } else {
403                 $_message ||= get_commit_entry($tb)->{log};
404         }
405         my $ra ||= Git::SVN::Ra->new($url);
406         $svn_path ||= $ra->{svn_path};
407         my $r = $_revision;
408         if ($r eq 'HEAD') {
409                 $r = $ra->get_latest_revnum;
410         } elsif ($r !~ /^\d+$/) {
411                 die "revision argument: $r not understood by git-svn\n";
412         }
413         my %ed_opts = ( r => $r,
414                         log => $_message,
415                         ra => $ra,
416                         tree_a => $ta,
417                         tree_b => $tb,
418                         editor_cb => sub { print "Committed r$_[0]\n" },
419                         svn_path => $svn_path );
420         if (!SVN::Git::Editor->new(\%ed_opts)->apply_diff) {
421                 print "No changes\n$ta == $tb\n";
422         }
425 ########################### utility functions #########################
427 sub parse_revision_argument {
428         if (!defined $_revision || $_revision eq 'BASE:HEAD') {
429                 return (undef, undef);
430         }
431         return ($1, $2) if ($_revision =~ /^(\d+):(\d+)$/);
432         return ($_revision, $_revision) if ($_revision =~ /^\d+$/);
433         return (undef, $1) if ($_revision =~ /^BASE:(\d+)$/);
434         return ($1, undef) if ($_revision =~ /^(\d+):HEAD$/);
435         die "revision argument: $_revision not understood by git-svn\n",
436             "Try using the command-line svn client instead\n";
439 sub complete_svn_url {
440         my ($url, $path) = @_;
441         $path =~ s#/+$##;
442         if ($path !~ m#^[a-z\+]+://#) {
443                 if (!defined $url || $url !~ m#^[a-z\+]+://#) {
444                         fatal("E: '$path' is not a complete URL ",
445                               "and a separate URL is not specified\n");
446                 }
447                 return ($url, $path);
448         }
449         return ($path, '');
452 sub complete_url_ls_init {
453         my ($ra, $repo_path, $switch, $pfx) = @_;
454         unless ($repo_path) {
455                 print STDERR "W: $switch not specified\n";
456                 return;
457         }
458         $repo_path =~ s#/+$##;
459         if ($repo_path =~ m#^[a-z\+]+://#) {
460                 $ra = Git::SVN::Ra->new($repo_path);
461                 $repo_path = '';
462         } else {
463                 $repo_path =~ s#^/+##;
464                 unless ($ra) {
465                         fatal("E: '$repo_path' is not a complete URL ",
466                               "and a separate URL is not specified\n");
467                 }
468         }
469         my $r = defined $_revision ? $_revision : $ra->get_latest_revnum;
470         my ($dirent, undef, undef) = $ra->get_dir($repo_path, $r);
471         my $url = $ra->{url};
472         foreach my $d (sort keys %$dirent) {
473                 next if ($dirent->{$d}->kind != $SVN::Node::dir);
474                 my $path =  "$repo_path/$d";
475                 my $ref = "$pfx$d";
476                 my $gs = eval { Git::SVN->new($ref) };
477                 # don't try to init already existing refs
478                 unless ($gs) {
479                         print "init $url/$path => $ref\n";
480                         Git::SVN->init($url, $path, undef, $ref);
481                 }
482         }
485 sub verify_ref {
486         my ($ref) = @_;
487         eval { command_oneline([ 'rev-parse', '--verify', $ref ],
488                                { STDERR => 0 }); };
491 sub get_tree_from_treeish {
492         my ($treeish) = @_;
493         # $treeish can be a symbolic ref, too:
494         my $type = command_oneline(qw/cat-file -t/, $treeish);
495         my $expected;
496         while ($type eq 'tag') {
497                 ($treeish, $type) = command(qw/cat-file tag/, $treeish);
498         }
499         if ($type eq 'commit') {
500                 $expected = (grep /^tree /, command(qw/cat-file commit/,
501                                                     $treeish))[0];
502                 ($expected) = ($expected =~ /^tree ($sha1)$/o);
503                 die "Unable to get tree from $treeish\n" unless $expected;
504         } elsif ($type eq 'tree') {
505                 $expected = $treeish;
506         } else {
507                 die "$treeish is a $type, expected tree, tag or commit\n";
508         }
509         return $expected;
512 sub get_commit_entry {
513         my ($treeish) = shift;
514         my %log_entry = ( log => '', tree => get_tree_from_treeish($treeish) );
515         my $commit_editmsg = "$ENV{GIT_DIR}/COMMIT_EDITMSG";
516         my $commit_msg = "$ENV{GIT_DIR}/COMMIT_MSG";
517         open my $log_fh, '>', $commit_editmsg or croak $!;
519         my $type = command_oneline(qw/cat-file -t/, $treeish);
520         if ($type eq 'commit' || $type eq 'tag') {
521                 my ($msg_fh, $ctx) = command_output_pipe('cat-file',
522                                                          $type, $treeish);
523                 my $in_msg = 0;
524                 while (<$msg_fh>) {
525                         if (!$in_msg) {
526                                 $in_msg = 1 if (/^\s*$/);
527                         } elsif (/^git-svn-id: /) {
528                                 # skip this for now, we regenerate the
529                                 # correct one on re-fetch anyways
530                                 # TODO: set *:merge properties or like...
531                         } else {
532                                 print $log_fh $_ or croak $!;
533                         }
534                 }
535                 command_close_pipe($msg_fh, $ctx);
536         }
537         close $log_fh or croak $!;
539         if ($_edit || ($type eq 'tree')) {
540                 my $editor = $ENV{VISUAL} || $ENV{EDITOR} || 'vi';
541                 # TODO: strip out spaces, comments, like git-commit.sh
542                 system($editor, $commit_editmsg);
543         }
544         rename $commit_editmsg, $commit_msg or croak $!;
545         open $log_fh, '<', $commit_msg or croak $!;
546         { local $/; chomp($log_entry{log} = <$log_fh>); }
547         close $log_fh or croak $!;
548         unlink $commit_msg;
549         \%log_entry;
552 sub s_to_file {
553         my ($str, $file, $mode) = @_;
554         open my $fd,'>',$file or croak $!;
555         print $fd $str,"\n" or croak $!;
556         close $fd or croak $!;
557         chmod ($mode &~ umask, $file) if (defined $mode);
560 sub file_to_s {
561         my $file = shift;
562         open my $fd,'<',$file or croak "$!: file: $file\n";
563         local $/;
564         my $ret = <$fd>;
565         close $fd or croak $!;
566         $ret =~ s/\s*$//s;
567         return $ret;
570 # '<svn username> = real-name <email address>' mapping based on git-svnimport:
571 sub load_authors {
572         open my $authors, '<', $_authors or die "Can't open $_authors $!\n";
573         my $log = $cmd eq 'log';
574         while (<$authors>) {
575                 chomp;
576                 next unless /^(\S+?|\(no author\))\s*=\s*(.+?)\s*<(.+)>\s*$/;
577                 my ($user, $name, $email) = ($1, $2, $3);
578                 if ($log) {
579                         $Git::SVN::Log::rusers{"$name <$email>"} = $user;
580                 } else {
581                         $users{$user} = [$name, $email];
582                 }
583         }
584         close $authors or croak $!;
587 # convert GetOpt::Long specs for use by git-config
588 sub read_repo_config {
589         return unless -d $ENV{GIT_DIR};
590         my $opts = shift;
591         foreach my $o (keys %$opts) {
592                 my $v = $opts->{$o};
593                 my ($key) = ($o =~ /^([a-z\-]+)/);
594                 $key =~ s/-//g;
595                 my $arg = 'git-config';
596                 $arg .= ' --int' if ($o =~ /[:=]i$/);
597                 $arg .= ' --bool' if ($o !~ /[:=][sfi]$/);
598                 if (ref $v eq 'ARRAY') {
599                         chomp(my @tmp = `$arg --get-all svn.$key`);
600                         @$v = @tmp if @tmp;
601                 } else {
602                         chomp(my $tmp = `$arg --get svn.$key`);
603                         if ($tmp && !($arg =~ / --bool/ && $tmp eq 'false')) {
604                                 $$v = $tmp;
605                         }
606                 }
607         }
610 sub extract_metadata {
611         my $id = shift or return (undef, undef, undef);
612         my ($url, $rev, $uuid) = ($id =~ /^git-svn-id:\s(\S+?)\@(\d+)
613                                                         \s([a-f\d\-]+)$/x);
614         if (!defined $rev || !$uuid || !$url) {
615                 # some of the original repositories I made had
616                 # identifiers like this:
617                 ($rev, $uuid) = ($id =~/^git-svn-id:\s(\d+)\@([a-f\d\-]+)/);
618         }
619         return ($url, $rev, $uuid);
622 sub cmt_metadata {
623         return extract_metadata((grep(/^git-svn-id: /,
624                 command(qw/cat-file commit/, shift)))[-1]);
627 package Git::SVN;
628 use strict;
629 use warnings;
630 use vars qw/$default_repo_id $default_ref_id $_no_metadata $_follow_parent
631             $_repack $_repack_flags/;
632 use Carp qw/croak/;
633 use File::Path qw/mkpath/;
634 use File::Copy qw/copy/;
635 use IPC::Open3;
637 my $_repack_nr;
638 # properties that we do not log:
639 my %SKIP_PROP;
640 BEGIN {
641         %SKIP_PROP = map { $_ => 1 } qw/svn:wc:ra_dav:version-url
642                                         svn:special svn:executable
643                                         svn:entry:committed-rev
644                                         svn:entry:last-author
645                                         svn:entry:uuid
646                                         svn:entry:committed-date/;
649 my %LOCKFILES;
650 END { unlink keys %LOCKFILES if %LOCKFILES }
652 sub fetch_all {
653         my ($repo_id, $url, $fetch) = @_;
654         my @gs;
655         my $ra = Git::SVN::Ra->new($url);
656         my $head = $ra->get_latest_revnum;
657         my $base = $head;
658         my $new_remote;
659         foreach my $p (sort keys %$fetch) {
660                 my $gs = Git::SVN->new($fetch->{$p}, $repo_id, $p);
661                 my $lr = $gs->last_rev;
662                 if (defined $lr) {
663                         $base = $lr if ($lr < $base);
664                 } else {
665                         $new_remote = 1;
666                 }
667                 push @gs, $gs;
668         }
669         $base = 0 if $new_remote;
670         return if (++$base > $head);
671         $ra->gs_fetch_loop_common($base, $head, @gs);
674 sub read_all_remotes {
675         my $r = {};
676         foreach (grep { s/^svn-remote\.// } command(qw/config -l/)) {
677                 if (m!^(.+)\.fetch=\s*(.*)\s*:\s*refs/remotes/(.+)\s*$!) {
678                         $r->{$1}->{fetch}->{$2} = $3;
679                 } elsif (m!^(.+)\.url=\s*(.*)\s*$!) {
680                         $r->{$1}->{url} = $2;
681                 }
682         }
683         $r;
686 sub init_vars {
687         if (defined $_repack) {
688                 $_repack = 1000 if ($_repack <= 0);
689                 $_repack_nr = $_repack;
690                 $_repack_flags ||= '-d';
691         }
694 sub verify_remotes_sanity {
695         return unless -d $ENV{GIT_DIR};
696         my %seen;
697         foreach (command(qw/config -l/)) {
698                 if (m!^svn-remote\.(?:.+)\.fetch=.*:refs/remotes/(\S+)\s*$!) {
699                         if ($seen{$1}) {
700                                 die "Remote ref refs/remote/$1 is tracked by",
701                                     "\n  \"$_\"\nand\n  \"$seen{$1}\"\n",
702                                     "Please resolve this ambiguity in ",
703                                     "your git configuration file before ",
704                                     "continuing\n";
705                         }
706                         $seen{$1} = $_;
707                 }
708         }
711 # we allow more chars than remotes2config.sh...
712 sub sanitize_remote_name {
713         my ($name) = @_;
714         $name =~ tr{A-Za-z0-9:,/+-}{.}c;
715         $name;
718 sub find_existing_remote {
719         my ($url, $remotes) = @_;
720         my $existing;
721         foreach my $repo_id (keys %$remotes) {
722                 my $u = $remotes->{$repo_id}->{url} or next;
723                 next if $u ne $url;
724                 $existing = $repo_id;
725                 last;
726         }
727         $existing;
730 sub init_remote_config {
731         my ($self, $url) = @_;
732         $url =~ s!/+$!!; # strip trailing slash
733         my $r = read_all_remotes();
734         my $existing = find_existing_remote($url, $r);
735         if ($existing) {
736                 print STDERR "Using existing ",
737                              "[svn-remote \"$existing\"]\n";
738                 $self->{repo_id} = $existing;
739         } else {
740                 my $min_url = Git::SVN::Ra->new($url)->minimize_url;
741                 $existing = find_existing_remote($min_url, $r);
742                 if ($existing) {
743                         print STDERR "Using existing ",
744                                      "[svn-remote \"$existing\"]\n";
745                         $self->{repo_id} = $existing;
746                 }
747                 if ($min_url ne $url) {
748                         print STDERR "Using higher level of URL: ",
749                                      "$url => $min_url\n";
750                         my $old_path = $self->{path};
751                         $self->{path} = $url;
752                         $self->{path} =~ s!^\Q$min_url\E/*!!;
753                         if (length $old_path) {
754                                 $self->{path} .= "/$old_path";
755                         }
756                         $url = $min_url;
757                 }
758         }
759         my $orig_url;
760         if (!$existing) {
761                 # verify that we aren't overwriting anything:
762                 $orig_url = eval {
763                         command_oneline('config', '--get',
764                                         "svn-remote.$self->{repo_id}.url")
765                 };
766                 if ($orig_url && ($orig_url ne $url)) {
767                         die "svn-remote.$self->{repo_id}.url already set: ",
768                             "$orig_url\nwanted to set to: $url\n";
769                 }
770         }
771         my ($xrepo_id, $xpath) = find_ref($self->refname);
772         if (defined $xpath) {
773                 die "svn-remote.$xrepo_id.fetch already set to track ",
774                     "$xpath:refs/remotes/", $self->refname, "\n";
775         }
776         command_noisy('config',
777                       "svn-remote.$self->{repo_id}.url", $url);
778         command_noisy('config', '--add',
779                       "svn-remote.$self->{repo_id}.fetch",
780                       "$self->{path}:".$self->refname);
781         $self->{url} = $url;
784 sub init {
785         my ($class, $url, $path, $repo_id, $ref_id) = @_;
786         my $self = _new($class, $repo_id, $ref_id, $path);
787         if (defined $url) {
788                 $self->init_remote_config($url);
789         }
790         $self;
793 sub find_ref {
794         my ($ref_id) = @_;
795         foreach (command(qw/config -l/)) {
796                 next unless m!^svn-remote\.(.+)\.fetch=
797                               \s*(.*)\s*:\s*refs/remotes/(.+)\s*$!x;
798                 my ($repo_id, $path, $ref) = ($1, $2, $3);
799                 if ($ref eq $ref_id) {
800                         $path = '' if ($path =~ m#^\./?#);
801                         return ($repo_id, $path);
802                 }
803         }
804         (undef, undef, undef);
807 sub new {
808         my ($class, $ref_id, $repo_id, $path) = @_;
809         if (defined $ref_id && !defined $repo_id && !defined $path) {
810                 ($repo_id, $path) = find_ref($ref_id);
811                 if (!defined $repo_id) {
812                         die "Could not find a \"svn-remote.*.fetch\" key ",
813                             "in the repository configuration matching: ",
814                             "refs/remotes/$ref_id\n";
815                 }
816         }
817         my $self = _new($class, $repo_id, $ref_id, $path);
818         if (!defined $self->{path} || !length $self->{path}) {
819                 my $fetch = command_oneline('config', '--get',
820                                             "svn-remote.$repo_id.fetch",
821                                             ":refs/remotes/$ref_id\$") or
822                      die "Failed to read \"svn-remote.$repo_id.fetch\" ",
823                          "\":refs/remotes/$ref_id\$\" in config\n";
824                 ($self->{path}, undef) = split(/\s*:\s*/, $fetch);
825         }
826         $self->{url} = command_oneline('config', '--get',
827                                        "svn-remote.$repo_id.url") or
828                   die "Failed to read \"svn-remote.$repo_id.url\" in config\n";
829         if (-z $self->{db_path} && ::verify_ref($self->refname.'^0')) {
830                 $self->rebuild;
831         }
832         $self;
835 sub refname { "refs/remotes/$_[0]->{ref_id}" }
837 sub ra {
838         my ($self) = shift;
839         Git::SVN::Ra->new($self->{url});
842 sub rel_path {
843         my ($self) = @_;
844         my $repos_root = $self->ra->{repos_root};
845         return $self->{path} if ($self->{url} eq $repos_root);
846         my $url = $self->{url} .
847                   (length $self->{path} ? "/$self->{path}" : $self->{path});
848         $url =~ s!^\Q$repos_root\E/*!!g;
849         $url;
852 sub traverse_ignore {
853         my ($self, $fh, $path, $r) = @_;
854         $path =~ s#^/+##g;
855         my $ra = $self->ra;
856         my ($dirent, undef, $props) = $ra->get_dir($path, $r);
857         my $p = $path;
858         $p =~ s#^\Q$ra->{svn_path}\E/##;
859         print $fh length $p ? "\n# $p\n" : "\n# /\n";
860         if (my $s = $props->{'svn:ignore'}) {
861                 $s =~ s/[\r\n]+/\n/g;
862                 chomp $s;
863                 if (length $p == 0) {
864                         $s =~ s#\n#\n/$p#g;
865                         print $fh "/$s\n";
866                 } else {
867                         $s =~ s#\n#\n/$p/#g;
868                         print $fh "/$p/$s\n";
869                 }
870         }
871         foreach (sort keys %$dirent) {
872                 next if $dirent->{$_}->kind != $SVN::Node::dir;
873                 $self->traverse_ignore($fh, "$path/$_", $r);
874         }
877 sub last_rev { ($_[0]->last_rev_commit)[0] }
878 sub last_commit { ($_[0]->last_rev_commit)[1] }
880 # returns the newest SVN revision number and newest commit SHA1
881 sub last_rev_commit {
882         my ($self) = @_;
883         if (defined $self->{last_rev} && defined $self->{last_commit}) {
884                 return ($self->{last_rev}, $self->{last_commit});
885         }
886         my $c = ::verify_ref($self->refname.'^0');
887         if ($c) {
888                 my $rev = (::cmt_metadata($c))[1];
889                 if (defined $rev) {
890                         ($self->{last_rev}, $self->{last_commit}) = ($rev, $c);
891                         return ($rev, $c);
892                 }
893         }
894         my $offset = -41; # from tail
895         my $rl;
896         open my $fh, '<', $self->{db_path} or
897                                  croak "$self->{db_path} not readable: $!\n";
898         seek $fh, $offset, 2;
899         $rl = readline $fh;
900         defined $rl or return (undef, undef);
901         chomp $rl;
902         while ($c ne $rl && tell $fh != 0) {
903                 $offset -= 41;
904                 seek $fh, $offset, 2;
905                 $rl = readline $fh;
906                 defined $rl or return (undef, undef);
907                 chomp $rl;
908         }
909         my $rev = tell $fh;
910         croak $! if ($rev < 0);
911         $rev =  ($rev - 41) / 41;
912         close $fh or croak $!;
913         ($self->{last_rev}, $self->{last_commit}) = ($rev, $c);
914         return ($rev, $c);
917 sub get_fetch_range {
918         my ($self, $min, $max) = @_;
919         $max ||= $self->ra->get_latest_revnum;
920         $min ||= $self->last_rev || 0;
921         (++$min, $max);
924 sub tmp_index_do {
925         my ($self, $sub) = @_;
926         my $old_index = $ENV{GIT_INDEX_FILE};
927         $ENV{GIT_INDEX_FILE} = $self->{index};
928         my @ret = &$sub;
929         if ($old_index) {
930                 $ENV{GIT_INDEX_FILE} = $old_index;
931         } else {
932                 delete $ENV{GIT_INDEX_FILE};
933         }
934         wantarray ? @ret : $ret[0];
937 sub assert_index_clean {
938         my ($self, $treeish) = @_;
940         $self->tmp_index_do(sub {
941                 command_noisy('read-tree', $treeish) unless -e $self->{index};
942                 my $x = command_oneline('write-tree');
943                 my ($y) = (command(qw/cat-file commit/, $treeish) =~
944                            /^tree ($::sha1)/mo);
945                 if ($y ne $x) {
946                         unlink $self->{index} or croak $!;
947                         command_noisy('read-tree', $treeish);
948                 }
949                 $x = command_oneline('write-tree');
950                 if ($y ne $x) {
951                         ::fatal "trees ($treeish) $y != $x\n",
952                                 "Something is seriously wrong...\n";
953                 }
954         });
957 sub get_commit_parents {
958         my ($self, $log_entry) = @_;
959         my (%seen, @ret, @tmp);
960         # legacy support for 'set-tree'; this is only used by set_tree_cb:
961         if (my $ip = $self->{inject_parents}) {
962                 if (my $commit = delete $ip->{$log_entry->{revision}}) {
963                         push @tmp, $commit;
964                 }
965         }
966         if (my $cur = ::verify_ref($self->refname.'^0')) {
967                 push @tmp, $cur;
968         }
969         push @tmp, $_ foreach (@{$log_entry->{parents}}, @tmp);
970         while (my $p = shift @tmp) {
971                 next if $seen{$p};
972                 $seen{$p} = 1;
973                 push @ret, $p;
974                 # MAXPARENT is defined to 16 in commit-tree.c:
975                 last if @ret >= 16;
976         }
977         if (@tmp) {
978                 die "r$log_entry->{revision}: No room for parents:\n\t",
979                     join("\n\t", @tmp), "\n";
980         }
981         @ret;
984 sub full_url {
985         my ($self) = @_;
986         $self->{url} . (length $self->{path} ? '/' . $self->{path} : '');
989 sub do_git_commit {
990         my ($self, $log_entry) = @_;
991         my $lr = $self->last_rev;
992         if (defined $lr && $lr >= $log_entry->{revision}) {
993                 die "Last fetched revision of ", $self->refname,
994                     " was r$lr, but we are about to fetch: ",
995                     "r$log_entry->{revision}!\n";
996         }
997         if (my $c = $self->rev_db_get($log_entry->{revision})) {
998                 croak "$log_entry->{revision} = $c already exists! ",
999                       "Why are we refetching it?\n";
1000         }
1001         my $author = $log_entry->{author};
1002         my ($name, $email) = (defined $::users{$author} ? @{$::users{$author}}
1003                            : ($author, "$author\@".$self->ra->uuid));
1004         $ENV{GIT_AUTHOR_NAME} = $ENV{GIT_COMMITTER_NAME} = $name;
1005         $ENV{GIT_AUTHOR_EMAIL} = $ENV{GIT_COMMITTER_EMAIL} = $email;
1006         $ENV{GIT_AUTHOR_DATE} = $ENV{GIT_COMMITTER_DATE} = $log_entry->{date};
1008         my $tree = $log_entry->{tree};
1009         if (!defined $tree) {
1010                 $tree = $self->tmp_index_do(sub {
1011                                             command_oneline('write-tree') });
1012         }
1013         die "Tree is not a valid sha1: $tree\n" if $tree !~ /^$::sha1$/o;
1015         my @exec = ('git-commit-tree', $tree);
1016         foreach ($self->get_commit_parents($log_entry)) {
1017                 push @exec, '-p', $_;
1018         }
1019         defined(my $pid = open3(my $msg_fh, my $out_fh, '>&STDERR', @exec))
1020                                                                    or croak $!;
1021         print $msg_fh $log_entry->{log} or croak $!;
1022         unless ($_no_metadata) {
1023                 print $msg_fh "\ngit-svn-id: ", $self->full_url, '@',
1024                               $log_entry->{revision}, ' ',
1025                               $self->ra->uuid, "\n" or croak $!;
1026         }
1027         $msg_fh->flush == 0 or croak $!;
1028         close $msg_fh or croak $!;
1029         chomp(my $commit = do { local $/; <$out_fh> });
1030         close $out_fh or croak $!;
1031         waitpid $pid, 0;
1032         croak $? if $?;
1033         if ($commit !~ /^$::sha1$/o) {
1034                 die "Failed to commit, invalid sha1: $commit\n";
1035         }
1037         $self->rev_db_set($log_entry->{revision}, $commit, 1);
1039         $self->{last_rev} = $log_entry->{revision};
1040         $self->{last_commit} = $commit;
1041         print "r$log_entry->{revision} = $commit ($self->{ref_id})\n";
1042         if (defined $_repack && (--$_repack_nr == 0)) {
1043                 $_repack_nr = $_repack;
1044                 # repack doesn't use any arguments with spaces in them, does it?
1045                 print "Running git repack $_repack_flags ...\n";
1046                 command_noisy('repack', split(/\s+/, $_repack_flags));
1047                 print "Done repacking\n";
1048         }
1049         return $commit;
1052 sub revisions_eq {
1053         my ($self, $r0, $r1) = @_;
1054         return 1 if $r0 == $r1;
1055         my $nr = 0;
1056         $self->ra->get_log([$self->{path}], $r0, $r1,
1057                            0, 0, 1, sub { $nr++ });
1058         return 0 if ($nr > 1);
1059         return 1;
1062 sub find_parent_branch {
1063         my ($self, $paths, $rev) = @_;
1064         return undef unless $_follow_parent;
1065         unless (defined $paths) {
1066                 my $err_handler = $SVN::Error::handler;
1067                 $SVN::Error::handler = \&Git::SVN::Ra::skip_unknown_revs;
1068                 $self->ra->get_log([$self->{path}], $rev, $rev, 0, 1, 1, sub {
1069                                    $paths =
1070                                       Git::SVN::Ra::dup_changed_paths($_[0]) });
1071                 $SVN::Error::handler = $err_handler;
1072         }
1073         return undef unless defined $paths;
1075         # look for a parent from another branch:
1076         my @b_path_components = split m#/#, $self->rel_path;
1077         my @a_path_components;
1078         my $i;
1079         while (@b_path_components) {
1080                 $i = $paths->{'/'.join('/', @b_path_components)};
1081                 last if $i;
1082                 unshift(@a_path_components, pop(@b_path_components));
1083         }
1084         goto not_found unless defined $i;
1085         my $branch_from = $i->{copyfrom_path} or goto not_found;
1086         if (@a_path_components) {
1087                 print STDERR "branch_from: $branch_from => ";
1088                 $branch_from .= '/'.join('/', @a_path_components);
1089                 print STDERR $branch_from, "\n";
1090         }
1091         my $r = $i->{copyfrom_rev};
1092         my $repos_root = $self->ra->{repos_root};
1093         my $url = $self->ra->{url};
1094         my $new_url = $repos_root . $branch_from;
1095         print STDERR  "Found possible branch point: ",
1096                       "$new_url => ", $self->full_url, ", $r\n";
1097         $branch_from =~ s#^/##;
1098         my $remotes = read_all_remotes();
1099         my $gs;
1100         foreach my $repo_id (keys %$remotes) {
1101                 my $u = $remotes->{$repo_id}->{url} or next;
1102                 next if $url ne $u;
1103                 my $fetch = $remotes->{$repo_id}->{fetch};
1104                 foreach my $f (keys %$fetch) {
1105                         next if $f ne $branch_from;
1106                         $gs = Git::SVN->new($fetch->{$f}, $repo_id, $f);
1107                         last;
1108                 }
1109                 last if $gs;
1110         }
1111         unless ($gs) {
1112                 my $ref_id = $self->{ref_id};
1113                 $ref_id =~ s/\@\d+$//;
1114                 $ref_id .= "\@$r";
1115                 # just grow a tail if we're not unique enough :x
1116                 $ref_id .= '-' while find_ref($ref_id);
1117                 print STDERR "Initializing parent: $ref_id\n";
1118                 $gs = Git::SVN->init($new_url, '', $ref_id, $ref_id);
1119         }
1120         my ($r0, $parent) = $gs->find_rev_before($r, 1);
1121         if ($_follow_parent && (!defined $r0 || !defined $parent)) {
1122                 $gs->fetch(0, $r);
1123                 ($r0, $parent) = $gs->last_rev_commit;
1124         }
1125         if (defined $r0 && defined $parent && $gs->revisions_eq($r0, $r)) {
1126                 print STDERR "Found branch parent: ($self->{ref_id}) $parent\n";
1127                 $self->assert_index_clean($parent);
1128                 my $ed;
1129                 if ($self->ra->can_do_switch) {
1130                         print STDERR "Following parent with do_switch\n";
1131                         # do_switch works with svn/trunk >= r22312, but that
1132                         # is not included with SVN 1.4.3 (the latest version
1133                         # at the moment), so we can't rely on it
1134                         $self->{last_commit} = $parent;
1135                         $ed = SVN::Git::Fetcher->new($self);
1136                         $gs->ra->gs_do_switch($r0, $rev, $gs,
1137                                               $self->full_url, $ed)
1138                           or die "SVN connection failed somewhere...\n";
1139                 } else {
1140                         print STDERR "Following parent with do_update\n";
1141                         $ed = SVN::Git::Fetcher->new($self);
1142                         $self->ra->gs_do_update($rev, $rev, $self, $ed)
1143                           or die "SVN connection failed somewhere...\n";
1144                 }
1145                 print STDERR "Successfully followed parent\n";
1146                 return $self->make_log_entry($rev, [$parent], $ed);
1147         }
1148 not_found:
1149         print STDERR "Branch parent for path: '/",
1150                      $self->rel_path, "' @ r$rev not found:\n";
1151         return undef unless $paths;
1152         print STDERR "Changed paths:\n";
1153         foreach my $x (sort keys %$paths) {
1154                 my $p = $paths->{$x};
1155                 print STDERR "\t$p->{action}\t$x";
1156                 if ($p->{copyfrom_path}) {
1157                         print STDERR "(from $p->{copyfrom_path}: ",
1158                                      "$p->{copyfrom_rev})";
1159                 }
1160                 print STDERR "\n";
1161         }
1162         print STDERR '-'x72, "\n";
1163         return undef;
1166 sub do_fetch {
1167         my ($self, $paths, $rev) = @_;
1168         my $ed;
1169         my ($last_rev, @parents);
1170         if ($self->{last_commit}) {
1171                 $ed = SVN::Git::Fetcher->new($self);
1172                 $last_rev = $self->{last_rev};
1173                 $ed->{c} = $self->{last_commit};
1174                 @parents = ($self->{last_commit});
1175         } else {
1176                 $last_rev = $rev;
1177                 if (my $log_entry = $self->find_parent_branch($paths, $rev)) {
1178                         return $log_entry;
1179                 }
1180                 $ed = SVN::Git::Fetcher->new($self);
1181         }
1182         unless ($self->ra->gs_do_update($last_rev, $rev, $self, $ed)) {
1183                 die "SVN connection failed somewhere...\n";
1184         }
1185         $self->make_log_entry($rev, \@parents, $ed);
1188 sub get_untracked {
1189         my ($self, $ed) = @_;
1190         my @out;
1191         my $h = $ed->{empty};
1192         foreach (sort keys %$h) {
1193                 my $act = $h->{$_} ? '+empty_dir' : '-empty_dir';
1194                 push @out, "  $act: " . uri_encode($_);
1195                 warn "W: $act: $_\n";
1196         }
1197         foreach my $t (qw/dir_prop file_prop/) {
1198                 $h = $ed->{$t} or next;
1199                 foreach my $path (sort keys %$h) {
1200                         my $ppath = $path eq '' ? '.' : $path;
1201                         foreach my $prop (sort keys %{$h->{$path}}) {
1202                                 next if $SKIP_PROP{$prop};
1203                                 my $v = $h->{$path}->{$prop};
1204                                 my $t_ppath_prop = "$t: " .
1205                                                     uri_encode($ppath) . ' ' .
1206                                                     uri_encode($prop);
1207                                 if (defined $v) {
1208                                         push @out, "  +$t_ppath_prop " .
1209                                                    uri_encode($v);
1210                                 } else {
1211                                         push @out, "  -$t_ppath_prop";
1212                                 }
1213                         }
1214                 }
1215         }
1216         foreach my $t (qw/absent_file absent_directory/) {
1217                 $h = $ed->{$t} or next;
1218                 foreach my $parent (sort keys %$h) {
1219                         foreach my $path (sort @{$h->{$parent}}) {
1220                                 push @out, "  $t: " .
1221                                            uri_encode("$parent/$path");
1222                                 warn "W: $t: $parent/$path ",
1223                                      "Insufficient permissions?\n";
1224                         }
1225                 }
1226         }
1227         \@out;
1230 sub parse_svn_date {
1231         my $date = shift || return '+0000 1970-01-01 00:00:00';
1232         my ($Y,$m,$d,$H,$M,$S) = ($date =~ /^(\d{4})\-(\d\d)\-(\d\d)T
1233                                             (\d\d)\:(\d\d)\:(\d\d).\d+Z$/x) or
1234                                          croak "Unable to parse date: $date\n";
1235         "+0000 $Y-$m-$d $H:$M:$S";
1238 sub check_author {
1239         my ($author) = @_;
1240         if (!defined $author || length $author == 0) {
1241                 $author = '(no author)';
1242         }
1243         if (defined $::_authors && ! defined $::users{$author}) {
1244                 die "Author: $author not defined in $::_authors file\n";
1245         }
1246         $author;
1249 sub make_log_entry {
1250         my ($self, $rev, $parents, $ed) = @_;
1251         my $untracked = $self->get_untracked($ed);
1253         open my $un, '>>', "$self->{dir}/unhandled.log" or croak $!;
1254         print $un "r$rev\n" or croak $!;
1255         print $un $_, "\n" foreach @$untracked;
1256         my %log_entry = ( parents => $parents || [], revision => $rev,
1257                           log => '');
1258         my $rp = $self->ra->rev_proplist($rev);
1259         foreach (sort keys %$rp) {
1260                 my $v = $rp->{$_};
1261                 if (/^svn:(author|date|log)$/) {
1262                         $log_entry{$1} = $v;
1263                 } else {
1264                         print $un "  rev_prop: ", uri_encode($_), ' ',
1265                                   uri_encode($v), "\n";
1266                 }
1267         }
1268         close $un or croak $!;
1270         $log_entry{date} = parse_svn_date($log_entry{date});
1271         $log_entry{author} = check_author($log_entry{author});
1272         $log_entry{log} .= "\n";
1273         \%log_entry;
1276 sub fetch {
1277         my ($self, $min_rev, $max_rev, @parents) = @_;
1278         my ($last_rev, $last_commit) = $self->last_rev_commit;
1279         my ($base, $head) = $self->get_fetch_range($min_rev, $max_rev);
1280         return if ($base > $head);
1281         $self->ra->gs_fetch_loop_common($base, $head, $self);
1284 sub set_tree_cb {
1285         my ($self, $log_entry, $tree, $rev, $date, $author) = @_;
1286         # TODO: enable and test optimized commits:
1287         if (0 && $rev == ($self->{last_rev} + 1)) {
1288                 $log_entry->{revision} = $rev;
1289                 $log_entry->{author} = $author;
1290                 $self->do_git_commit($log_entry, "$rev=$tree");
1291         } else {
1292                 $self->{inject_parents} = { $rev => $tree };
1293                 $self->fetch(undef, undef);
1294         }
1297 sub set_tree {
1298         my ($self, $tree) = (shift, shift);
1299         my $log_entry = ::get_commit_entry($tree);
1300         unless ($self->{last_rev}) {
1301                 fatal("Must have an existing revision to commit\n");
1302         }
1303         my %ed_opts = ( r => $self->{last_rev},
1304                         log => $log_entry->{log},
1305                         ra => $self->ra,
1306                         tree_a => $self->{last_commit},
1307                         tree_b => $tree,
1308                         editor_cb => sub {
1309                                $self->set_tree_cb($log_entry, $tree, @_) },
1310                         svn_path => $self->{path} );
1311         if (!SVN::Git::Editor->new(\%ed_opts)->apply_diff) {
1312                 print "No changes\nr$self->{last_rev} = $tree\n";
1313         }
1316 sub rebuild {
1317         my ($self) = @_;
1318         print "Rebuilding $self->{db_path} ...\n";
1319         my ($rev_list, $ctx) = command_output_pipe("rev-list", $self->refname);
1320         my $latest;
1321         my $full_url = $self->full_url;
1322         my $svn_uuid;
1323         while (<$rev_list>) {
1324                 chomp;
1325                 my $c = $_;
1326                 die "Non-SHA1: $c\n" unless $c =~ /^$::sha1$/o;
1327                 my ($url, $rev, $uuid) = ::cmt_metadata($c);
1329                 # ignore merges (from set-tree)
1330                 next if (!defined $rev || !$uuid);
1332                 # if we merged or otherwise started elsewhere, this is
1333                 # how we break out of it
1334                 if ((defined $svn_uuid && ($uuid ne $svn_uuid)) ||
1335                     ($full_url && $url && ($url ne $full_url))) {
1336                         next;
1337                 }
1338                 $latest ||= $rev;
1339                 $svn_uuid ||= $uuid;
1341                 $self->rev_db_set($rev, $c);
1342                 print "r$rev = $c\n";
1343         }
1344         command_close_pipe($rev_list, $ctx);
1345         print "Done rebuilding $self->{db_path}\n";
1348 # rev_db:
1349 # Tie::File seems to be prone to offset errors if revisions get sparse,
1350 # it's not that fast, either.  Tie::File is also not in Perl 5.6.  So
1351 # one of my favorite modules is out :<  Next up would be one of the DBM
1352 # modules, but I'm not sure which is most portable...  So I'll just
1353 # go with something that's plain-text, but still capable of
1354 # being randomly accessed.  So here's my ultra-simple fixed-width
1355 # database.  All records are 40 characters + "\n", so it's easy to seek
1356 # to a revision: (41 * rev) is the byte offset.
1357 # A record of 40 0s denotes an empty revision.
1358 # And yes, it's still pretty fast (faster than Tie::File).
1359 # These files are disposable unless --no-metadata is set
1361 sub rev_db_set {
1362         my ($self, $rev, $commit, $update_ref) = @_;
1363         length $commit == 40 or croak "arg3 must be a full SHA1 hexsum\n";
1364         my ($db, $db_lock) = ($self->{db_path}, "$self->{db_path}.lock");
1365         my $sig;
1366         if ($update_ref) {
1367                 $SIG{INT} = $SIG{HUP} = $SIG{TERM} = $SIG{ALRM} = $SIG{PIPE} =
1368                             $SIG{USR1} = $SIG{USR2} = sub { $sig = $_[0] };
1369         }
1370         $LOCKFILES{$db_lock} = 1;
1371         if ($_no_metadata) {
1372                 copy($db, $db_lock) or die "rev_db_set(@_): ",
1373                                            "Failed to copy: ",
1374                                            "$db => $db_lock ($!)\n";
1375         } else {
1376                 rename $db, $db_lock or die "rev_db_set(@_): ",
1377                                             "Failed to rename: ",
1378                                             "$db => $db_lock ($!)\n";
1379         }
1380         open my $fh, '+<', $db_lock or croak $!;
1381         my $offset = $rev * 41;
1382         # assume that append is the common case:
1383         seek $fh, 0, 2 or croak $!;
1384         my $pos = tell $fh;
1385         if ($pos < $offset) {
1386                 for (1 .. (($offset - $pos) / 41)) {
1387                         print $fh (('0' x 40),"\n") or croak $!;
1388                 }
1389         }
1390         seek $fh, $offset, 0 or croak $!;
1391         print $fh $commit,"\n" or croak $!;
1392         close $fh or croak $!;
1393         if ($update_ref) {
1394                 command_noisy('update-ref', '-m', "r$rev",
1395                               $self->refname, $commit);
1396         }
1397         rename $db_lock, $db or die "rev_db_set(@_): ", "Failed to rename: ",
1398                                     "$db_lock => $db ($!)\n";
1399         delete $LOCKFILES{$db_lock};
1400         if ($update_ref) {
1401                 $SIG{INT} = $SIG{HUP} = $SIG{TERM} = $SIG{ALRM} = $SIG{PIPE} =
1402                             $SIG{USR1} = $SIG{USR2} = 'DEFAULT';
1403                 kill $sig, $$ if defined $sig;
1404         }
1407 sub rev_db_get {
1408         my ($self, $rev) = @_;
1409         my $ret;
1410         my $offset = $rev * 41;
1411         open my $fh, '<', $self->{db_path} or croak $!;
1412         if (seek $fh, $offset, 0) {
1413                 $ret = readline $fh;
1414                 if (defined $ret) {
1415                         chomp $ret;
1416                         $ret = undef if ($ret =~ /^0{40}$/);
1417                 }
1418         }
1419         close $fh or croak $!;
1420         $ret;
1423 sub find_rev_before {
1424         my ($self, $rev, $eq_ok) = @_;
1425         --$rev unless $eq_ok;
1426         while ($rev > 0) {
1427                 if (my $c = $self->rev_db_get($rev)) {
1428                         return ($rev, $c);
1429                 }
1430                 --$rev;
1431         }
1432         return (undef, undef);
1435 sub _new {
1436         my ($class, $repo_id, $ref_id, $path) = @_;
1437         unless (defined $repo_id && length $repo_id) {
1438                 $repo_id = $Git::SVN::default_repo_id;
1439         }
1440         unless (defined $ref_id && length $ref_id) {
1441                 $_[2] = $ref_id = $Git::SVN::default_ref_id;
1442         }
1443         $_[1] = $repo_id = sanitize_remote_name($repo_id);
1444         my $dir = "$ENV{GIT_DIR}/svn/$ref_id";
1445         $_[3] = $path = '' unless (defined $path);
1446         mkpath([$dir]);
1447         unless (-f "$dir/.rev_db") {
1448                 open my $fh, '>>', "$dir/.rev_db" or croak $!;
1449                 close $fh or croak $!;
1450         }
1451         bless { ref_id => $ref_id, dir => $dir, index => "$dir/index",
1452                 path => $path,
1453                 db_path => "$dir/.rev_db", repo_id => $repo_id }, $class;
1456 sub uri_encode {
1457         my ($f) = @_;
1458         $f =~ s#([^a-zA-Z0-9\*!\:_\./\-])#uc sprintf("%%%02x",ord($1))#eg;
1459         $f
1462 package Git::SVN::Prompt;
1463 use strict;
1464 use warnings;
1465 require SVN::Core;
1466 use vars qw/$_no_auth_cache $_username/;
1468 sub simple {
1469         my ($cred, $realm, $default_username, $may_save, $pool) = @_;
1470         $may_save = undef if $_no_auth_cache;
1471         $default_username = $_username if defined $_username;
1472         if (defined $default_username && length $default_username) {
1473                 if (defined $realm && length $realm) {
1474                         print STDERR "Authentication realm: $realm\n";
1475                         STDERR->flush;
1476                 }
1477                 $cred->username($default_username);
1478         } else {
1479                 username($cred, $realm, $may_save, $pool);
1480         }
1481         $cred->password(_read_password("Password for '" .
1482                                        $cred->username . "': ", $realm));
1483         $cred->may_save($may_save);
1484         $SVN::_Core::SVN_NO_ERROR;
1487 sub ssl_server_trust {
1488         my ($cred, $realm, $failures, $cert_info, $may_save, $pool) = @_;
1489         $may_save = undef if $_no_auth_cache;
1490         print STDERR "Error validating server certificate for '$realm':\n";
1491         if ($failures & $SVN::Auth::SSL::UNKNOWNCA) {
1492                 print STDERR " - The certificate is not issued by a trusted ",
1493                       "authority. Use the\n",
1494                       "   fingerprint to validate the certificate manually!\n";
1495         }
1496         if ($failures & $SVN::Auth::SSL::CNMISMATCH) {
1497                 print STDERR " - The certificate hostname does not match.\n";
1498         }
1499         if ($failures & $SVN::Auth::SSL::NOTYETVALID) {
1500                 print STDERR " - The certificate is not yet valid.\n";
1501         }
1502         if ($failures & $SVN::Auth::SSL::EXPIRED) {
1503                 print STDERR " - The certificate has expired.\n";
1504         }
1505         if ($failures & $SVN::Auth::SSL::OTHER) {
1506                 print STDERR " - The certificate has an unknown error.\n";
1507         }
1508         printf STDERR
1509                 "Certificate information:\n".
1510                 " - Hostname: %s\n".
1511                 " - Valid: from %s until %s\n".
1512                 " - Issuer: %s\n".
1513                 " - Fingerprint: %s\n",
1514                 map $cert_info->$_, qw(hostname valid_from valid_until
1515                                        issuer_dname fingerprint);
1516         my $choice;
1517 prompt:
1518         print STDERR $may_save ?
1519               "(R)eject, accept (t)emporarily or accept (p)ermanently? " :
1520               "(R)eject or accept (t)emporarily? ";
1521         STDERR->flush;
1522         $choice = lc(substr(<STDIN> || 'R', 0, 1));
1523         if ($choice =~ /^t$/i) {
1524                 $cred->may_save(undef);
1525         } elsif ($choice =~ /^r$/i) {
1526                 return -1;
1527         } elsif ($may_save && $choice =~ /^p$/i) {
1528                 $cred->may_save($may_save);
1529         } else {
1530                 goto prompt;
1531         }
1532         $cred->accepted_failures($failures);
1533         $SVN::_Core::SVN_NO_ERROR;
1536 sub ssl_client_cert {
1537         my ($cred, $realm, $may_save, $pool) = @_;
1538         $may_save = undef if $_no_auth_cache;
1539         print STDERR "Client certificate filename: ";
1540         STDERR->flush;
1541         chomp(my $filename = <STDIN>);
1542         $cred->cert_file($filename);
1543         $cred->may_save($may_save);
1544         $SVN::_Core::SVN_NO_ERROR;
1547 sub ssl_client_cert_pw {
1548         my ($cred, $realm, $may_save, $pool) = @_;
1549         $may_save = undef if $_no_auth_cache;
1550         $cred->password(_read_password("Password: ", $realm));
1551         $cred->may_save($may_save);
1552         $SVN::_Core::SVN_NO_ERROR;
1555 sub username {
1556         my ($cred, $realm, $may_save, $pool) = @_;
1557         $may_save = undef if $_no_auth_cache;
1558         if (defined $realm && length $realm) {
1559                 print STDERR "Authentication realm: $realm\n";
1560         }
1561         my $username;
1562         if (defined $_username) {
1563                 $username = $_username;
1564         } else {
1565                 print STDERR "Username: ";
1566                 STDERR->flush;
1567                 chomp($username = <STDIN>);
1568         }
1569         $cred->username($username);
1570         $cred->may_save($may_save);
1571         $SVN::_Core::SVN_NO_ERROR;
1574 sub _read_password {
1575         my ($prompt, $realm) = @_;
1576         print STDERR $prompt;
1577         STDERR->flush;
1578         require Term::ReadKey;
1579         Term::ReadKey::ReadMode('noecho');
1580         my $password = '';
1581         while (defined(my $key = Term::ReadKey::ReadKey(0))) {
1582                 last if $key =~ /[\012\015]/; # \n\r
1583                 $password .= $key;
1584         }
1585         Term::ReadKey::ReadMode('restore');
1586         print STDERR "\n";
1587         STDERR->flush;
1588         $password;
1591 package main;
1594         my $kill_stupid_warnings = $SVN::Node::none.$SVN::Node::file.
1595                                 $SVN::Node::dir.$SVN::Node::unknown.
1596                                 $SVN::Node::none.$SVN::Node::file.
1597                                 $SVN::Node::dir.$SVN::Node::unknown.
1598                                 $SVN::Auth::SSL::CNMISMATCH.
1599                                 $SVN::Auth::SSL::NOTYETVALID.
1600                                 $SVN::Auth::SSL::EXPIRED.
1601                                 $SVN::Auth::SSL::UNKNOWNCA.
1602                                 $SVN::Auth::SSL::OTHER;
1605 package SVN::Git::Fetcher;
1606 use vars qw/@ISA/;
1607 use strict;
1608 use warnings;
1609 use Carp qw/croak/;
1610 use IO::File qw//;
1611 use Digest::MD5;
1613 # file baton members: path, mode_a, mode_b, pool, fh, blob, base
1614 sub new {
1615         my ($class, $git_svn) = @_;
1616         my $self = SVN::Delta::Editor->new;
1617         bless $self, $class;
1618         $self->{c} = $git_svn->{last_commit} if exists $git_svn->{last_commit};
1619         $self->{empty} = {};
1620         $self->{dir_prop} = {};
1621         $self->{file_prop} = {};
1622         $self->{absent_dir} = {};
1623         $self->{absent_file} = {};
1624         $self->{gii} = $git_svn->tmp_index_do(sub { Git::IndexInfo->new });
1625         $self;
1628 sub set_path_strip {
1629         my ($self, $path) = @_;
1630         $self->{path_strip} = qr/^\Q$path\E\/?/;
1633 sub open_root {
1634         { path => '' };
1637 sub open_directory {
1638         my ($self, $path, $pb, $rev) = @_;
1639         { path => $path };
1642 sub git_path {
1643         my ($self, $path) = @_;
1644         if ($self->{path_strip}) {
1645                 $path =~ s!$self->{path_strip}!! or
1646                   die "Failed to strip path '$path' ($self->{path_strip})\n";
1647         }
1648         $path;
1651 sub delete_entry {
1652         my ($self, $path, $rev, $pb) = @_;
1654         my $gpath = $self->git_path($path);
1655         return undef if ($gpath eq '');
1657         # remove entire directories.
1658         if (command('ls-tree', $self->{c}, '--', $gpath) =~ /^040000 tree/) {
1659                 my ($ls, $ctx) = command_output_pipe(qw/ls-tree
1660                                                      -r --name-only -z/,
1661                                                      $self->{c}, '--', $gpath);
1662                 local $/ = "\0";
1663                 while (<$ls>) {
1664                         chomp;
1665                         $self->{gii}->remove($_);
1666                         print "\tD\t$_\n" unless $self->{q};
1667                 }
1668                 print "\tD\t$gpath/\n" unless $self->{q};
1669                 command_close_pipe($ls, $ctx);
1670                 $self->{empty}->{$path} = 0
1671         } else {
1672                 $self->{gii}->remove($gpath);
1673                 print "\tD\t$gpath\n" unless $self->{q};
1674         }
1675         undef;
1678 sub open_file {
1679         my ($self, $path, $pb, $rev) = @_;
1680         my $gpath = $self->git_path($path);
1681         my ($mode, $blob) = (command('ls-tree', $self->{c}, '--', $gpath)
1682                              =~ /^(\d{6}) blob ([a-f\d]{40})\t/);
1683         unless (defined $mode && defined $blob) {
1684                 die "$path was not found in commit $self->{c} (r$rev)\n";
1685         }
1686         { path => $path, mode_a => $mode, mode_b => $mode, blob => $blob,
1687           pool => SVN::Pool->new, action => 'M' };
1690 sub add_file {
1691         my ($self, $path, $pb, $cp_path, $cp_rev) = @_;
1692         my ($dir, $file) = ($path =~ m#^(.*?)/?([^/]+)$#);
1693         delete $self->{empty}->{$dir};
1694         { path => $path, mode_a => 100644, mode_b => 100644,
1695           pool => SVN::Pool->new, action => 'A' };
1698 sub add_directory {
1699         my ($self, $path, $cp_path, $cp_rev) = @_;
1700         my ($dir, $file) = ($path =~ m#^(.*?)/?([^/]+)$#);
1701         delete $self->{empty}->{$dir};
1702         $self->{empty}->{$path} = 1;
1703         { path => $path };
1706 sub change_dir_prop {
1707         my ($self, $db, $prop, $value) = @_;
1708         $self->{dir_prop}->{$db->{path}} ||= {};
1709         $self->{dir_prop}->{$db->{path}}->{$prop} = $value;
1710         undef;
1713 sub absent_directory {
1714         my ($self, $path, $pb) = @_;
1715         $self->{absent_dir}->{$pb->{path}} ||= [];
1716         push @{$self->{absent_dir}->{$pb->{path}}}, $path;
1717         undef;
1720 sub absent_file {
1721         my ($self, $path, $pb) = @_;
1722         $self->{absent_file}->{$pb->{path}} ||= [];
1723         push @{$self->{absent_file}->{$pb->{path}}}, $path;
1724         undef;
1727 sub change_file_prop {
1728         my ($self, $fb, $prop, $value) = @_;
1729         if ($prop eq 'svn:executable') {
1730                 if ($fb->{mode_b} != 120000) {
1731                         $fb->{mode_b} = defined $value ? 100755 : 100644;
1732                 }
1733         } elsif ($prop eq 'svn:special') {
1734                 $fb->{mode_b} = defined $value ? 120000 : 100644;
1735         } else {
1736                 $self->{file_prop}->{$fb->{path}} ||= {};
1737                 $self->{file_prop}->{$fb->{path}}->{$prop} = $value;
1738         }
1739         undef;
1742 sub apply_textdelta {
1743         my ($self, $fb, $exp) = @_;
1744         my $fh = IO::File->new_tmpfile;
1745         $fh->autoflush(1);
1746         # $fh gets auto-closed() by SVN::TxDelta::apply(),
1747         # (but $base does not,) so dup() it for reading in close_file
1748         open my $dup, '<&', $fh or croak $!;
1749         my $base = IO::File->new_tmpfile;
1750         $base->autoflush(1);
1751         if ($fb->{blob}) {
1752                 defined (my $pid = fork) or croak $!;
1753                 if (!$pid) {
1754                         open STDOUT, '>&', $base or croak $!;
1755                         print STDOUT 'link ' if ($fb->{mode_a} == 120000);
1756                         exec qw/git-cat-file blob/, $fb->{blob} or croak $!;
1757                 }
1758                 waitpid $pid, 0;
1759                 croak $? if $?;
1761                 if (defined $exp) {
1762                         seek $base, 0, 0 or croak $!;
1763                         my $md5 = Digest::MD5->new;
1764                         $md5->addfile($base);
1765                         my $got = $md5->hexdigest;
1766                         die "Checksum mismatch: $fb->{path} $fb->{blob}\n",
1767                             "expected: $exp\n",
1768                             "     got: $got\n" if ($got ne $exp);
1769                 }
1770         }
1771         seek $base, 0, 0 or croak $!;
1772         $fb->{fh} = $dup;
1773         $fb->{base} = $base;
1774         [ SVN::TxDelta::apply($base, $fh, undef, $fb->{path}, $fb->{pool}) ];
1777 sub close_file {
1778         my ($self, $fb, $exp) = @_;
1779         my $hash;
1780         my $path = $self->git_path($fb->{path});
1781         if (my $fh = $fb->{fh}) {
1782                 seek($fh, 0, 0) or croak $!;
1783                 my $md5 = Digest::MD5->new;
1784                 $md5->addfile($fh);
1785                 my $got = $md5->hexdigest;
1786                 die "Checksum mismatch: $path\n",
1787                     "expected: $exp\n    got: $got\n" if ($got ne $exp);
1788                 seek($fh, 0, 0) or croak $!;
1789                 if ($fb->{mode_b} == 120000) {
1790                         read($fh, my $buf, 5) == 5 or croak $!;
1791                         $buf eq 'link ' or die "$path has mode 120000",
1792                                                "but is not a link\n";
1793                 }
1794                 defined(my $pid = open my $out,'-|') or die "Can't fork: $!\n";
1795                 if (!$pid) {
1796                         open STDIN, '<&', $fh or croak $!;
1797                         exec qw/git-hash-object -w --stdin/ or croak $!;
1798                 }
1799                 chomp($hash = do { local $/; <$out> });
1800                 close $out or croak $!;
1801                 close $fh or croak $!;
1802                 $hash =~ /^[a-f\d]{40}$/ or die "not a sha1: $hash\n";
1803                 close $fb->{base} or croak $!;
1804         } else {
1805                 $hash = $fb->{blob} or die "no blob information\n";
1806         }
1807         $fb->{pool}->clear;
1808         $self->{gii}->update($fb->{mode_b}, $hash, $path) or croak $!;
1809         print "\t$fb->{action}\t$path\n" if $fb->{action} && ! $self->{q};
1810         undef;
1813 sub abort_edit {
1814         my $self = shift;
1815         $self->{nr} = $self->{gii}->{nr};
1816         delete $self->{gii};
1817         $self->SUPER::abort_edit(@_);
1820 sub close_edit {
1821         my $self = shift;
1822         $self->{git_commit_ok} = 1;
1823         $self->{nr} = $self->{gii}->{nr};
1824         delete $self->{gii};
1825         $self->SUPER::close_edit(@_);
1828 package SVN::Git::Editor;
1829 use vars qw/@ISA $_rmdir $_cp_similarity $_find_copies_harder $_rename_limit/;
1830 use strict;
1831 use warnings;
1832 use Carp qw/croak/;
1833 use IO::File;
1834 use Digest::MD5;
1836 sub new {
1837         my ($class, $opts) = @_;
1838         foreach (qw/svn_path r ra tree_a tree_b log editor_cb/) {
1839                 die "$_ required!\n" unless (defined $opts->{$_});
1840         }
1842         my $pool = SVN::Pool->new;
1843         my $mods = generate_diff($opts->{tree_a}, $opts->{tree_b});
1844         my $types = check_diff_paths($opts->{ra}, $opts->{svn_path},
1845                                      $opts->{r}, $mods);
1847         # $opts->{ra} functions should not be used after this:
1848         my @ce  = $opts->{ra}->get_commit_editor($opts->{log},
1849                                                 $opts->{editor_cb}, $pool);
1850         my $self = SVN::Delta::Editor->new(@ce, $pool);
1851         bless $self, $class;
1852         foreach (qw/svn_path r tree_a tree_b/) {
1853                 $self->{$_} = $opts->{$_};
1854         }
1855         $self->{url} = $opts->{ra}->{url};
1856         $self->{mods} = $mods;
1857         $self->{types} = $types;
1858         $self->{pool} = $pool;
1859         $self->{bat} = { '' => $self->open_root($self->{r}, $self->{pool}) };
1860         $self->{rm} = { };
1861         $self->{path_prefix} = length $self->{svn_path} ?
1862                                "$self->{svn_path}/" : '';
1863         return $self;
1866 sub generate_diff {
1867         my ($tree_a, $tree_b) = @_;
1868         my @diff_tree = qw(diff-tree -z -r);
1869         if ($_cp_similarity) {
1870                 push @diff_tree, "-C$_cp_similarity";
1871         } else {
1872                 push @diff_tree, '-C';
1873         }
1874         push @diff_tree, '--find-copies-harder' if $_find_copies_harder;
1875         push @diff_tree, "-l$_rename_limit" if defined $_rename_limit;
1876         push @diff_tree, $tree_a, $tree_b;
1877         my ($diff_fh, $ctx) = command_output_pipe(@diff_tree);
1878         local $/ = "\0";
1879         my $state = 'meta';
1880         my @mods;
1881         while (<$diff_fh>) {
1882                 chomp $_; # this gets rid of the trailing "\0"
1883                 if ($state eq 'meta' && /^:(\d{6})\s(\d{6})\s
1884                                         $::sha1\s($::sha1)\s
1885                                         ([MTCRAD])\d*$/xo) {
1886                         push @mods, {   mode_a => $1, mode_b => $2,
1887                                         sha1_b => $3, chg => $4 };
1888                         if ($4 =~ /^(?:C|R)$/) {
1889                                 $state = 'file_a';
1890                         } else {
1891                                 $state = 'file_b';
1892                         }
1893                 } elsif ($state eq 'file_a') {
1894                         my $x = $mods[$#mods] or croak "Empty array\n";
1895                         if ($x->{chg} !~ /^(?:C|R)$/) {
1896                                 croak "Error parsing $_, $x->{chg}\n";
1897                         }
1898                         $x->{file_a} = $_;
1899                         $state = 'file_b';
1900                 } elsif ($state eq 'file_b') {
1901                         my $x = $mods[$#mods] or croak "Empty array\n";
1902                         if (exists $x->{file_a} && $x->{chg} !~ /^(?:C|R)$/) {
1903                                 croak "Error parsing $_, $x->{chg}\n";
1904                         }
1905                         if (!exists $x->{file_a} && $x->{chg} =~ /^(?:C|R)$/) {
1906                                 croak "Error parsing $_, $x->{chg}\n";
1907                         }
1908                         $x->{file_b} = $_;
1909                         $state = 'meta';
1910                 } else {
1911                         croak "Error parsing $_\n";
1912                 }
1913         }
1914         command_close_pipe($diff_fh, $ctx);
1915         \@mods;
1918 sub check_diff_paths {
1919         my ($ra, $pfx, $rev, $mods) = @_;
1920         my %types;
1921         $pfx .= '/' if length $pfx;
1923         sub type_diff_paths {
1924                 my ($ra, $types, $path, $rev) = @_;
1925                 my @p = split m#/+#, $path;
1926                 my $c = shift @p;
1927                 unless (defined $types->{$c}) {
1928                         $types->{$c} = $ra->check_path($c, $rev);
1929                 }
1930                 while (@p) {
1931                         $c .= '/' . shift @p;
1932                         next if defined $types->{$c};
1933                         $types->{$c} = $ra->check_path($c, $rev);
1934                 }
1935         }
1937         foreach my $m (@$mods) {
1938                 foreach my $f (qw/file_a file_b/) {
1939                         next unless defined $m->{$f};
1940                         my ($dir) = ($m->{$f} =~ m#^(.*?)/?(?:[^/]+)$#);
1941                         if (length $pfx.$dir && ! defined $types{$dir}) {
1942                                 type_diff_paths($ra, \%types, $pfx.$dir, $rev);
1943                         }
1944                 }
1945         }
1946         \%types;
1949 sub split_path {
1950         return ($_[0] =~ m#^(.*?)/?([^/]+)$#);
1953 sub repo_path {
1954         my ($self, $path) = @_;
1955         $self->{path_prefix}.(defined $path ? $path : '');
1958 sub url_path {
1959         my ($self, $path) = @_;
1960         $self->{url} . '/' . $self->repo_path($path);
1963 sub rmdirs {
1964         my ($self) = @_;
1965         my $rm = $self->{rm};
1966         delete $rm->{''}; # we never delete the url we're tracking
1967         return unless %$rm;
1969         foreach (keys %$rm) {
1970                 my @d = split m#/#, $_;
1971                 my $c = shift @d;
1972                 $rm->{$c} = 1;
1973                 while (@d) {
1974                         $c .= '/' . shift @d;
1975                         $rm->{$c} = 1;
1976                 }
1977         }
1978         delete $rm->{$self->{svn_path}};
1979         delete $rm->{''}; # we never delete the url we're tracking
1980         return unless %$rm;
1982         my ($fh, $ctx) = command_output_pipe(qw/ls-tree --name-only -r -z/,
1983                                              $self->{tree_b});
1984         local $/ = "\0";
1985         while (<$fh>) {
1986                 chomp;
1987                 my @dn = split m#/#, $_;
1988                 while (pop @dn) {
1989                         delete $rm->{join '/', @dn};
1990                 }
1991                 unless (%$rm) {
1992                         close $fh;
1993                         return;
1994                 }
1995         }
1996         command_close_pipe($fh, $ctx);
1998         my ($r, $p, $bat) = ($self->{r}, $self->{pool}, $self->{bat});
1999         foreach my $d (sort { $b =~ tr#/#/# <=> $a =~ tr#/#/# } keys %$rm) {
2000                 $self->close_directory($bat->{$d}, $p);
2001                 my ($dn) = ($d =~ m#^(.*?)/?(?:[^/]+)$#);
2002                 print "\tD+\t$d/\n" unless $::_q;
2003                 $self->SUPER::delete_entry($d, $r, $bat->{$dn}, $p);
2004                 delete $bat->{$d};
2005         }
2008 sub open_or_add_dir {
2009         my ($self, $full_path, $baton) = @_;
2010         my $t = $self->{types}->{$full_path};
2011         if (!defined $t) {
2012                 die "$full_path not known in r$self->{r} or we have a bug!\n";
2013         }
2014         if ($t == $SVN::Node::none) {
2015                 return $self->add_directory($full_path, $baton,
2016                                                 undef, -1, $self->{pool});
2017         } elsif ($t == $SVN::Node::dir) {
2018                 return $self->open_directory($full_path, $baton,
2019                                                 $self->{r}, $self->{pool});
2020         }
2021         print STDERR "$full_path already exists in repository at ",
2022                 "r$self->{r} and it is not a directory (",
2023                 ($t == $SVN::Node::file ? 'file' : 'unknown'),"/$t)\n";
2024         exit 1;
2027 sub ensure_path {
2028         my ($self, $path) = @_;
2029         my $bat = $self->{bat};
2030         my $repo_path = $self->repo_path($path);
2031         return $bat->{''} unless (length $repo_path);
2032         my @p = split m#/+#, $repo_path;
2033         my $c = shift @p;
2034         $bat->{$c} ||= $self->open_or_add_dir($c, $bat->{''});
2035         while (@p) {
2036                 my $c0 = $c;
2037                 $c .= '/' . shift @p;
2038                 $bat->{$c} ||= $self->open_or_add_dir($c, $bat->{$c0});
2039         }
2040         return $bat->{$c};
2043 sub A {
2044         my ($self, $m) = @_;
2045         my ($dir, $file) = split_path($m->{file_b});
2046         my $pbat = $self->ensure_path($dir);
2047         my $fbat = $self->add_file($self->repo_path($m->{file_b}), $pbat,
2048                                         undef, -1);
2049         print "\tA\t$m->{file_b}\n" unless $::_q;
2050         $self->chg_file($fbat, $m);
2051         $self->close_file($fbat,undef,$self->{pool});
2054 sub C {
2055         my ($self, $m) = @_;
2056         my ($dir, $file) = split_path($m->{file_b});
2057         my $pbat = $self->ensure_path($dir);
2058         my $fbat = $self->add_file($self->repo_path($m->{file_b}), $pbat,
2059                                 $self->url_path($m->{file_a}), $self->{r});
2060         print "\tC\t$m->{file_a} => $m->{file_b}\n" unless $::_q;
2061         $self->chg_file($fbat, $m);
2062         $self->close_file($fbat,undef,$self->{pool});
2065 sub delete_entry {
2066         my ($self, $path, $pbat) = @_;
2067         my $rpath = $self->repo_path($path);
2068         my ($dir, $file) = split_path($rpath);
2069         $self->{rm}->{$dir} = 1;
2070         $self->SUPER::delete_entry($rpath, $self->{r}, $pbat, $self->{pool});
2073 sub R {
2074         my ($self, $m) = @_;
2075         my ($dir, $file) = split_path($m->{file_b});
2076         my $pbat = $self->ensure_path($dir);
2077         my $fbat = $self->add_file($self->repo_path($m->{file_b}), $pbat,
2078                                 $self->url_path($m->{file_a}), $self->{r});
2079         print "\tR\t$m->{file_a} => $m->{file_b}\n" unless $::_q;
2080         $self->chg_file($fbat, $m);
2081         $self->close_file($fbat,undef,$self->{pool});
2083         ($dir, $file) = split_path($m->{file_a});
2084         $pbat = $self->ensure_path($dir);
2085         $self->delete_entry($m->{file_a}, $pbat);
2088 sub M {
2089         my ($self, $m) = @_;
2090         my ($dir, $file) = split_path($m->{file_b});
2091         my $pbat = $self->ensure_path($dir);
2092         my $fbat = $self->open_file($self->repo_path($m->{file_b}),
2093                                 $pbat,$self->{r},$self->{pool});
2094         print "\t$m->{chg}\t$m->{file_b}\n" unless $::_q;
2095         $self->chg_file($fbat, $m);
2096         $self->close_file($fbat,undef,$self->{pool});
2099 sub T { shift->M(@_) }
2101 sub change_file_prop {
2102         my ($self, $fbat, $pname, $pval) = @_;
2103         $self->SUPER::change_file_prop($fbat, $pname, $pval, $self->{pool});
2106 sub chg_file {
2107         my ($self, $fbat, $m) = @_;
2108         if ($m->{mode_b} =~ /755$/ && $m->{mode_a} !~ /755$/) {
2109                 $self->change_file_prop($fbat,'svn:executable','*');
2110         } elsif ($m->{mode_b} !~ /755$/ && $m->{mode_a} =~ /755$/) {
2111                 $self->change_file_prop($fbat,'svn:executable',undef);
2112         }
2113         my $fh = IO::File->new_tmpfile or croak $!;
2114         if ($m->{mode_b} =~ /^120/) {
2115                 print $fh 'link ' or croak $!;
2116                 $self->change_file_prop($fbat,'svn:special','*');
2117         } elsif ($m->{mode_a} =~ /^120/ && $m->{mode_b} !~ /^120/) {
2118                 $self->change_file_prop($fbat,'svn:special',undef);
2119         }
2120         defined(my $pid = fork) or croak $!;
2121         if (!$pid) {
2122                 open STDOUT, '>&', $fh or croak $!;
2123                 exec qw/git-cat-file blob/, $m->{sha1_b} or croak $!;
2124         }
2125         waitpid $pid, 0;
2126         croak $? if $?;
2127         $fh->flush == 0 or croak $!;
2128         seek $fh, 0, 0 or croak $!;
2130         my $md5 = Digest::MD5->new;
2131         $md5->addfile($fh) or croak $!;
2132         seek $fh, 0, 0 or croak $!;
2134         my $exp = $md5->hexdigest;
2135         my $pool = SVN::Pool->new;
2136         my $atd = $self->apply_textdelta($fbat, undef, $pool);
2137         my $got = SVN::TxDelta::send_stream($fh, @$atd, $pool);
2138         die "Checksum mismatch\nexpected: $exp\ngot: $got\n" if ($got ne $exp);
2139         $pool->clear;
2141         close $fh or croak $!;
2144 sub D {
2145         my ($self, $m) = @_;
2146         my ($dir, $file) = split_path($m->{file_b});
2147         my $pbat = $self->ensure_path($dir);
2148         print "\tD\t$m->{file_b}\n" unless $::_q;
2149         $self->delete_entry($m->{file_b}, $pbat);
2152 sub close_edit {
2153         my ($self) = @_;
2154         my ($p,$bat) = ($self->{pool}, $self->{bat});
2155         foreach (sort { $b =~ tr#/#/# <=> $a =~ tr#/#/# } keys %$bat) {
2156                 $self->close_directory($bat->{$_}, $p);
2157         }
2158         $self->SUPER::close_edit($p);
2159         $p->clear;
2162 sub abort_edit {
2163         my ($self) = @_;
2164         $self->SUPER::abort_edit($self->{pool});
2167 sub DESTROY {
2168         my $self = shift;
2169         $self->SUPER::DESTROY(@_);
2170         $self->{pool}->clear;
2173 # this drives the editor
2174 sub apply_diff {
2175         my ($self) = @_;
2176         my $mods = $self->{mods};
2177         my %o = ( D => 1, R => 0, C => -1, A => 3, M => 3, T => 3 );
2178         foreach my $m (sort { $o{$a->{chg}} <=> $o{$b->{chg}} } @$mods) {
2179                 my $f = $m->{chg};
2180                 if (defined $o{$f}) {
2181                         $self->$f($m);
2182                 } else {
2183                         fatal("Invalid change type: $f\n");
2184                 }
2185         }
2186         $self->rmdirs if $_rmdir;
2187         if (@$mods == 0) {
2188                 $self->abort_edit;
2189         } else {
2190                 $self->close_edit;
2191         }
2192         return scalar @$mods;
2195 package Git::SVN::Ra;
2196 use vars qw/@ISA $config_dir/;
2197 use strict;
2198 use warnings;
2199 my ($can_do_switch);
2200 my $RA;
2202 BEGIN {
2203         # enforce temporary pool usage for some simple functions
2204         my $e;
2205         foreach (qw/get_latest_revnum rev_proplist get_file
2206                     check_path get_dir get_uuid get_repos_root/) {
2207                 $e .= "sub $_ {
2208                         my \$self = shift;
2209                         my \$pool = SVN::Pool->new;
2210                         my \@ret = \$self->SUPER::$_(\@_,\$pool);
2211                         \$pool->clear;
2212                         wantarray ? \@ret : \$ret[0]; }\n";
2213         }
2214         eval $e;
2217 sub new {
2218         my ($class, $url) = @_;
2219         $url =~ s!/+$!!;
2220         return $RA if ($RA && $RA->{url} eq $url);
2222         SVN::_Core::svn_config_ensure($config_dir, undef);
2223         my ($baton, $callbacks) = SVN::Core::auth_open_helper([
2224             SVN::Client::get_simple_provider(),
2225             SVN::Client::get_ssl_server_trust_file_provider(),
2226             SVN::Client::get_simple_prompt_provider(
2227               \&Git::SVN::Prompt::simple, 2),
2228             SVN::Client::get_ssl_client_cert_prompt_provider(
2229               \&Git::SVN::Prompt::ssl_client_cert, 2),
2230             SVN::Client::get_ssl_client_cert_pw_prompt_provider(
2231               \&Git::SVN::Prompt::ssl_client_cert_pw, 2),
2232             SVN::Client::get_username_provider(),
2233             SVN::Client::get_ssl_server_trust_prompt_provider(
2234               \&Git::SVN::Prompt::ssl_server_trust),
2235             SVN::Client::get_username_prompt_provider(
2236               \&Git::SVN::Prompt::username, 2),
2237           ]);
2238         my $config = SVN::Core::config_get_config($config_dir);
2239         my $self = SVN::Ra->new(url => $url, auth => $baton,
2240                               config => $config,
2241                               pool => SVN::Pool->new,
2242                               auth_provider_callbacks => $callbacks);
2243         $self->{svn_path} = $url;
2244         $self->{repos_root} = $self->get_repos_root;
2245         $self->{svn_path} =~ s#^\Q$self->{repos_root}\E/*##;
2246         $RA = bless $self, $class;
2249 sub DESTROY {
2250         # do not call the real DESTROY since we store ourselves in $RA
2253 sub get_log {
2254         my ($self, @args) = @_;
2255         my $pool = SVN::Pool->new;
2256         splice(@args, 3, 1) if ($SVN::Core::VERSION le '1.2.0');
2257         my $ret = $self->SUPER::get_log(@args, $pool);
2258         $pool->clear;
2259         $ret;
2262 sub get_commit_editor {
2263         my ($self, $log, $cb, $pool) = @_;
2264         my @lock = $SVN::Core::VERSION ge '1.2.0' ? (undef, 0) : ();
2265         $self->SUPER::get_commit_editor($log, $cb, @lock, $pool);
2268 sub uuid {
2269         my ($self) = @_;
2270         $self->{uuid} ||= $self->get_uuid;
2273 sub gs_do_update {
2274         my ($self, $rev_a, $rev_b, $gs, $editor) = @_;
2275         my $new = ($rev_a == $rev_b);
2276         my $path = $gs->{path};
2278         my $ta = $self->check_path($path, $rev_a);
2279         my $tb = $new ? $ta : $self->check_path($path, $rev_b);
2280         return 1 if ($tb != $SVN::Node::dir && $ta != $SVN::Node::dir);
2281         if ($ta == $SVN::Node::none) {
2282                 $rev_a = $rev_b;
2283                 $new = 1;
2284         }
2286         my $pool = SVN::Pool->new;
2287         $editor->set_path_strip($path);
2288         my (@pc) = split m#/#, $path;
2289         my $reporter = $self->do_update($rev_b, (@pc ? shift @pc : ''),
2290                                         1, $editor, $pool);
2291         my @lock = $SVN::Core::VERSION ge '1.2.0' ? (undef) : ();
2293         # Since we can't rely on svn_ra_reparent being available, we'll
2294         # just have to do some magic with set_path to make it so
2295         # we only want a partial path.
2296         my $sp = '';
2297         my $final = join('/', @pc);
2298         while (@pc) {
2299                 $reporter->set_path($sp, $rev_b, 0, @lock, $pool);
2300                 $sp .= '/' if length $sp;
2301                 $sp .= shift @pc;
2302         }
2303         die "BUG: '$sp' != '$final'\n" if ($sp ne $final);
2305         $reporter->set_path($sp, $rev_a, $new, @lock, $pool);
2307         $reporter->finish_report($pool);
2308         $pool->clear;
2309         $editor->{git_commit_ok};
2312 # this requires SVN 1.4.3 or later (do_switch didn't work before 1.4.3, and
2313 # svn_ra_reparent didn't work before 1.4)
2314 sub gs_do_switch {
2315         my ($self, $rev_a, $rev_b, $gs, $url_b, $editor) = @_;
2316         my $path = $gs->{path};
2317         my $pool = SVN::Pool->new;
2319         my $full_url = $self->{url};
2320         my $old_url = $full_url;
2321         $full_url .= "/$path" if length $path;
2322         my ($ra, $reparented);
2323         if ($old_url ne $full_url) {
2324                 if ($old_url !~ m#^svn(\+ssh)?://#) {
2325                         SVN::_Ra::svn_ra_reparent($self->{session}, $full_url,
2326                                                   $pool);
2327                         $self->{url} = $full_url;
2328                         $reparented = 1;
2329                 } else {
2330                         $ra = Git::SVN::Ra->new($full_url);
2331                 }
2332         }
2333         $ra ||= $self;
2334         my $reporter = $ra->do_switch($rev_b, '', 1, $url_b, $editor, $pool);
2335         my @lock = $SVN::Core::VERSION ge '1.2.0' ? (undef) : ();
2336         $reporter->set_path('', $rev_a, 0, @lock, $pool);
2337         $reporter->finish_report($pool);
2339         if ($reparented) {
2340                 SVN::_Ra::svn_ra_reparent($self->{session}, $old_url, $pool);
2341                 $self->{url} = $old_url;
2342         }
2344         $pool->clear;
2345         $editor->{git_commit_ok};
2348 sub gs_fetch_loop_common {
2349         my ($self, $base, $head, @gs) = @_;
2350         my $inc = 1000;
2351         my ($min, $max) = ($base, $head < $base + $inc ? $head : $base + $inc);
2352         foreach my $gs (@gs) {
2353                 if (my $last_commit = $gs->last_commit) {
2354                         $gs->assert_index_clean($last_commit);
2355                 }
2356         }
2357         while (1) {
2358                 my %revs;
2359                 my $err;
2360                 my $err_handler = $SVN::Error::handler;
2361                 $SVN::Error::handler = sub {
2362                         ($err) = @_;
2363                         skip_unknown_revs($err);
2364                 };
2365                 foreach my $gs (@gs) {
2366                         $self->get_log([$gs->{path}], $min, $max, 0, 1, 1, sub
2367                                        { my ($paths, $rev) = @_;
2368                                          push @{$revs{$rev}},
2369                                               [ $gs,
2370                                                 dup_changed_paths($paths) ] });
2372                         next unless ($err && $max >= $head);
2374                         print STDERR "Path '$gs->{path}' ",
2375                                      "was probably deleted:\n",
2376                                      $err->expanded_message,
2377                                      "\nWill attempt to follow ",
2378                                      "revisions r$min .. r$max ",
2379                                      "committed before the deletion\n";
2380                         my $hi = $max;
2381                         while (--$hi >= $min) {
2382                                 my $ok;
2383                                 $self->get_log([$gs->{path}], $min, $hi,
2384                                                0, 1, 1, sub {
2385                                         my ($paths, $rev) = @_;
2386                                         $ok = $rev;
2387                                         push @{$revs{$rev}}, [ $gs,
2388                                            dup_changed_paths($_[0])]});
2389                                 if ($ok) {
2390                                         print STDERR "r$min .. r$ok OK\n";
2391                                         last;
2392                                 }
2393                         }
2394                 }
2395                 $SVN::Error::handler = $err_handler;
2396                 foreach my $r (sort {$a <=> $b} keys %revs) {
2397                         foreach (@{$revs{$r}}) {
2398                                 my ($gs, $paths) = @$_;
2399                                 my $lr = $gs->last_rev;
2400                                 next if defined $lr && $lr >= $r;
2401                                 next if defined $gs->rev_db_get($r);
2402                                 if (my $log_entry = $gs->do_fetch($paths, $r)) {
2403                                         $gs->do_git_commit($log_entry);
2404                                 }
2405                         }
2406                 }
2407                 last if $max >= $head;
2408                 $min = $max + 1;
2409                 $max += $inc;
2410                 $max = $head if ($max > $head);
2411         }
2414 sub minimize_url {
2415         my ($self) = @_;
2416         return $self->{url} if ($self->{url} eq $self->{repos_root});
2417         my $url = $self->{repos_root};
2418         my @components = split(m!/!, $self->{svn_path});
2419         my $c = '';
2420         do {
2421                 $url .= "/$c" if length $c;
2422                 eval { (ref $self)->new($url)->get_latest_revnum };
2423         } while ($@ && ($c = shift @components));
2424         $url;
2427 sub can_do_switch {
2428         my $self = shift;
2429         unless (defined $can_do_switch) {
2430                 my $pool = SVN::Pool->new;
2431                 my $rep = eval {
2432                         $self->do_switch(1, '', 0, $self->{url},
2433                                          SVN::Delta::Editor->new, $pool);
2434                 };
2435                 if ($@) {
2436                         $can_do_switch = 0;
2437                 } else {
2438                         $rep->abort_report($pool);
2439                         $can_do_switch = 1;
2440                 }
2441                 $pool->clear;
2442         }
2443         $can_do_switch;
2446 sub skip_unknown_revs {
2447         my ($err) = @_;
2448         my $errno = $err->apr_err();
2449         # Maybe the branch we're tracking didn't
2450         # exist when the repo started, so it's
2451         # not an error if it doesn't, just continue
2452         #
2453         # Wonderfully consistent library, eh?
2454         # 160013 - svn:// and file://
2455         # 175002 - http(s)://
2456         # 175007 - http(s):// (this repo required authorization, too...)
2457         #   More codes may be discovered later...
2458         if ($errno == 175007 || $errno == 175002 || $errno == 160013) {
2459                 return;
2460         }
2461         die "Error from SVN, ($errno): ", $err->expanded_message,"\n";
2464 # svn_log_changed_path_t objects passed to get_log are likely to be
2465 # overwritten even if only the refs are copied to an external variable,
2466 # so we should dup the structures in their entirety.  Using an externally
2467 # passed pool (instead of our temporary and quickly cleared pool in
2468 # Git::SVN::Ra) does not help matters at all...
2469 sub dup_changed_paths {
2470         my ($paths) = @_;
2471         return undef unless $paths;
2472         my %ret;
2473         foreach my $p (keys %$paths) {
2474                 my $i = $paths->{$p};
2475                 my %s = map { $_ => $i->$_ }
2476                               qw/copyfrom_path copyfrom_rev action/;
2477                 $ret{$p} = \%s;
2478         }
2479         \%ret;
2482 package Git::SVN::Log;
2483 use strict;
2484 use warnings;
2485 use POSIX qw/strftime/;
2486 use vars qw/$TZ $limit $color $pager $non_recursive $verbose $oneline
2487             %rusers $show_commit $incremental/;
2488 my $l_fmt;
2490 sub cmt_showable {
2491         my ($c) = @_;
2492         return 1 if defined $c->{r};
2493         if ($c->{l} && $c->{l}->[-1] eq "...\n" &&
2494                                 $c->{a_raw} =~ /\@([a-f\d\-]+)>$/) {
2495                 my @log = command(qw/cat-file commit/, $c->{c});
2496                 shift @log while ($log[0] ne "\n");
2497                 shift @log;
2498                 @{$c->{l}} = grep !/^git-svn-id: /, @log;
2500                 (undef, $c->{r}, undef) = ::extract_metadata(
2501                                 (grep(/^git-svn-id: /, @log))[-1]);
2502         }
2503         return defined $c->{r};
2506 sub log_use_color {
2507         return 1 if $color;
2508         my ($dc, $dcvar);
2509         $dcvar = 'color.diff';
2510         $dc = `git-config --get $dcvar`;
2511         if ($dc eq '') {
2512                 # nothing at all; fallback to "diff.color"
2513                 $dcvar = 'diff.color';
2514                 $dc = `git-config --get $dcvar`;
2515         }
2516         chomp($dc);
2517         if ($dc eq 'auto') {
2518                 my $pc;
2519                 $pc = `git-config --get color.pager`;
2520                 if ($pc eq '') {
2521                         # does not have it -- fallback to pager.color
2522                         $pc = `git-config --bool --get pager.color`;
2523                 }
2524                 else {
2525                         $pc = `git-config --bool --get color.pager`;
2526                         if ($?) {
2527                                 $pc = 'false';
2528                         }
2529                 }
2530                 chomp($pc);
2531                 if (-t *STDOUT || (defined $pager && $pc eq 'true')) {
2532                         return ($ENV{TERM} && $ENV{TERM} ne 'dumb');
2533                 }
2534                 return 0;
2535         }
2536         return 0 if $dc eq 'never';
2537         return 1 if $dc eq 'always';
2538         chomp($dc = `git-config --bool --get $dcvar`);
2539         return ($dc eq 'true');
2542 sub git_svn_log_cmd {
2543         my ($r_min, $r_max) = @_;
2544         my $gs = Git::SVN->_new;
2545         my @cmd = (qw/log --abbrev-commit --pretty=raw --default/,
2546                    $gs->refname);
2547         push @cmd, '-r' unless $non_recursive;
2548         push @cmd, qw/--raw --name-status/ if $verbose;
2549         push @cmd, '--color' if log_use_color();
2550         return @cmd unless defined $r_max;
2551         if ($r_max == $r_min) {
2552                 push @cmd, '--max-count=1';
2553                 if (my $c = $gs->rev_db_get($r_max)) {
2554                         push @cmd, $c;
2555                 }
2556         } else {
2557                 my ($c_min, $c_max);
2558                 $c_max = $gs->rev_db_get($r_max);
2559                 $c_min = $gs->rev_db_get($r_min);
2560                 if (defined $c_min && defined $c_max) {
2561                         if ($r_max > $r_max) {
2562                                 push @cmd, "$c_min..$c_max";
2563                         } else {
2564                                 push @cmd, "$c_max..$c_min";
2565                         }
2566                 } elsif ($r_max > $r_min) {
2567                         push @cmd, $c_max;
2568                 } else {
2569                         push @cmd, $c_min;
2570                 }
2571         }
2572         return @cmd;
2575 # adapted from pager.c
2576 sub config_pager {
2577         $pager ||= $ENV{GIT_PAGER} || $ENV{PAGER};
2578         if (!defined $pager) {
2579                 $pager = 'less';
2580         } elsif (length $pager == 0 || $pager eq 'cat') {
2581                 $pager = undef;
2582         }
2585 sub run_pager {
2586         return unless -t *STDOUT;
2587         pipe my $rfd, my $wfd or return;
2588         defined(my $pid = fork) or ::fatal "Can't fork: $!\n";
2589         if (!$pid) {
2590                 open STDOUT, '>&', $wfd or
2591                                      ::fatal "Can't redirect to stdout: $!\n";
2592                 return;
2593         }
2594         open STDIN, '<&', $rfd or ::fatal "Can't redirect stdin: $!\n";
2595         $ENV{LESS} ||= 'FRSX';
2596         exec $pager or ::fatal "Can't run pager: $! ($pager)\n";
2599 sub tz_to_s_offset {
2600         my ($tz) = @_;
2601         $tz =~ s/(\d\d)$//;
2602         return ($1 * 60) + ($tz * 3600);
2605 sub get_author_info {
2606         my ($dest, $author, $t, $tz) = @_;
2607         $author =~ s/(?:^\s*|\s*$)//g;
2608         $dest->{a_raw} = $author;
2609         my $au;
2610         if ($::_authors) {
2611                 $au = $rusers{$author} || undef;
2612         }
2613         if (!$au) {
2614                 ($au) = ($author =~ /<([^>]+)\@[^>]+>$/);
2615         }
2616         $dest->{t} = $t;
2617         $dest->{tz} = $tz;
2618         $dest->{a} = $au;
2619         # Date::Parse isn't in the standard Perl distro :(
2620         if ($tz =~ s/^\+//) {
2621                 $t += tz_to_s_offset($tz);
2622         } elsif ($tz =~ s/^\-//) {
2623                 $t -= tz_to_s_offset($tz);
2624         }
2625         $dest->{t_utc} = $t;
2628 sub process_commit {
2629         my ($c, $r_min, $r_max, $defer) = @_;
2630         if (defined $r_min && defined $r_max) {
2631                 if ($r_min == $c->{r} && $r_min == $r_max) {
2632                         show_commit($c);
2633                         return 0;
2634                 }
2635                 return 1 if $r_min == $r_max;
2636                 if ($r_min < $r_max) {
2637                         # we need to reverse the print order
2638                         return 0 if (defined $limit && --$limit < 0);
2639                         push @$defer, $c;
2640                         return 1;
2641                 }
2642                 if ($r_min != $r_max) {
2643                         return 1 if ($r_min < $c->{r});
2644                         return 1 if ($r_max > $c->{r});
2645                 }
2646         }
2647         return 0 if (defined $limit && --$limit < 0);
2648         show_commit($c);
2649         return 1;
2652 sub show_commit {
2653         my $c = shift;
2654         if ($oneline) {
2655                 my $x = "\n";
2656                 if (my $l = $c->{l}) {
2657                         while ($l->[0] =~ /^\s*$/) { shift @$l }
2658                         $x = $l->[0];
2659                 }
2660                 $l_fmt ||= 'A' . length($c->{r});
2661                 print 'r',pack($l_fmt, $c->{r}),' | ';
2662                 print "$c->{c} | " if $show_commit;
2663                 print $x;
2664         } else {
2665                 show_commit_normal($c);
2666         }
2669 sub show_commit_changed_paths {
2670         my ($c) = @_;
2671         return unless $c->{changed};
2672         print "Changed paths:\n", @{$c->{changed}};
2675 sub show_commit_normal {
2676         my ($c) = @_;
2677         print '-' x72, "\nr$c->{r} | ";
2678         print "$c->{c} | " if $show_commit;
2679         print "$c->{a} | ", strftime("%Y-%m-%d %H:%M:%S %z (%a, %d %b %Y)",
2680                                  localtime($c->{t_utc})), ' | ';
2681         my $nr_line = 0;
2683         if (my $l = $c->{l}) {
2684                 while ($l->[$#$l] eq "\n" && $#$l > 0
2685                                           && $l->[($#$l - 1)] eq "\n") {
2686                         pop @$l;
2687                 }
2688                 $nr_line = scalar @$l;
2689                 if (!$nr_line) {
2690                         print "1 line\n\n\n";
2691                 } else {
2692                         if ($nr_line == 1) {
2693                                 $nr_line = '1 line';
2694                         } else {
2695                                 $nr_line .= ' lines';
2696                         }
2697                         print $nr_line, "\n";
2698                         show_commit_changed_paths($c);
2699                         print "\n";
2700                         print $_ foreach @$l;
2701                 }
2702         } else {
2703                 print "1 line\n";
2704                 show_commit_changed_paths($c);
2705                 print "\n";
2707         }
2708         foreach my $x (qw/raw diff/) {
2709                 if ($c->{$x}) {
2710                         print "\n";
2711                         print $_ foreach @{$c->{$x}}
2712                 }
2713         }
2716 sub cmd_show_log {
2717         my (@args) = @_;
2718         my ($r_min, $r_max);
2719         my $r_last = -1; # prevent dupes
2720         if (defined $TZ) {
2721                 $ENV{TZ} = $TZ;
2722         } else {
2723                 delete $ENV{TZ};
2724         }
2725         if (defined $::_revision) {
2726                 if ($::_revision =~ /^(\d+):(\d+)$/) {
2727                         ($r_min, $r_max) = ($1, $2);
2728                 } elsif ($::_revision =~ /^\d+$/) {
2729                         $r_min = $r_max = $::_revision;
2730                 } else {
2731                         ::fatal "-r$::_revision is not supported, use ",
2732                                 "standard \'git log\' arguments instead\n";
2733                 }
2734         }
2736         config_pager();
2737         @args = (git_svn_log_cmd($r_min, $r_max), @args);
2738         my $log = command_output_pipe(@args);
2739         run_pager();
2740         my (@k, $c, $d);
2741         my $esc_color = qr/(?:\033\[(?:(?:\d+;)*\d*)?m)*/;
2742         while (<$log>) {
2743                 if (/^${esc_color}commit ($::sha1_short)/o) {
2744                         my $cmt = $1;
2745                         if ($c && cmt_showable($c) && $c->{r} != $r_last) {
2746                                 $r_last = $c->{r};
2747                                 process_commit($c, $r_min, $r_max, \@k) or
2748                                                                 goto out;
2749                         }
2750                         $d = undef;
2751                         $c = { c => $cmt };
2752                 } elsif (/^${esc_color}author (.+) (\d+) ([\-\+]?\d+)$/o) {
2753                         get_author_info($c, $1, $2, $3);
2754                 } elsif (/^${esc_color}(?:tree|parent|committer) /o) {
2755                         # ignore
2756                 } elsif (/^${esc_color}:\d{6} \d{6} $::sha1_short/o) {
2757                         push @{$c->{raw}}, $_;
2758                 } elsif (/^${esc_color}[ACRMDT]\t/) {
2759                         # we could add $SVN->{svn_path} here, but that requires
2760                         # remote access at the moment (repo_path_split)...
2761                         s#^(${esc_color})([ACRMDT])\t#$1   $2 #o;
2762                         push @{$c->{changed}}, $_;
2763                 } elsif (/^${esc_color}diff /o) {
2764                         $d = 1;
2765                         push @{$c->{diff}}, $_;
2766                 } elsif ($d) {
2767                         push @{$c->{diff}}, $_;
2768                 } elsif (/^${esc_color}    (git-svn-id:.+)$/o) {
2769                         ($c->{url}, $c->{r}, undef) = ::extract_metadata($1);
2770                 } elsif (s/^${esc_color}    //o) {
2771                         push @{$c->{l}}, $_;
2772                 }
2773         }
2774         if ($c && defined $c->{r} && $c->{r} != $r_last) {
2775                 $r_last = $c->{r};
2776                 process_commit($c, $r_min, $r_max, \@k);
2777         }
2778         if (@k) {
2779                 my $swap = $r_max;
2780                 $r_max = $r_min;
2781                 $r_min = $swap;
2782                 process_commit($_, $r_min, $r_max) foreach reverse @k;
2783         }
2784 out:
2785         close $log;
2786         print '-' x72,"\n" unless $incremental || $oneline;
2789 package Git::SVN::Migration;
2790 # these version numbers do NOT correspond to actual version numbers
2791 # of git nor git-svn.  They are just relative.
2793 # v0 layout: .git/$id/info/url, refs/heads/$id-HEAD
2795 # v1 layout: .git/$id/info/url, refs/remotes/$id
2797 # v2 layout: .git/svn/$id/info/url, refs/remotes/$id
2799 # v3 layout: .git/svn/$id, refs/remotes/$id
2800 #            - info/url may remain for backwards compatibility
2801 #            - this is what we migrate up to this layout automatically,
2802 #            - this will be used by git svn init on single branches
2804 # v4 layout: .git/svn/$repo_id/$id, refs/remotes/$repo_id/$id
2805 #            - this is only created for newly multi-init-ed
2806 #              repositories.  Similar in spirit to the
2807 #              --use-separate-remotes option in git-clone (now default)
2808 #            - we do not automatically migrate to this (following
2809 #              the example set by core git)
2810 use strict;
2811 use warnings;
2812 use Carp qw/croak/;
2813 use File::Path qw/mkpath/;
2814 use File::Basename qw/dirname basename/;
2815 use vars qw/$_minimize/;
2817 sub migrate_from_v0 {
2818         my $git_dir = $ENV{GIT_DIR};
2819         return undef unless -d $git_dir;
2820         my ($fh, $ctx) = command_output_pipe(qw/rev-parse --symbolic --all/);
2821         my $migrated = 0;
2822         while (<$fh>) {
2823                 chomp;
2824                 my ($id, $orig_ref) = ($_, $_);
2825                 next unless $id =~ s#^refs/heads/(.+)-HEAD$#$1#;
2826                 next unless -f "$git_dir/$id/info/url";
2827                 my $new_ref = "refs/remotes/$id";
2828                 if (::verify_ref("$new_ref^0")) {
2829                         print STDERR "W: $orig_ref is probably an old ",
2830                                      "branch used by an ancient version of ",
2831                                      "git-svn.\n",
2832                                      "However, $new_ref also exists.\n",
2833                                      "We will not be able ",
2834                                      "to use this branch until this ",
2835                                      "ambiguity is resolved.\n";
2836                         next;
2837                 }
2838                 print STDERR "Migrating from v0 layout...\n" if !$migrated;
2839                 print STDERR "Renaming ref: $orig_ref => $new_ref\n";
2840                 command_noisy('update-ref', $new_ref, $orig_ref);
2841                 command_noisy('update-ref', '-d', $orig_ref, $orig_ref);
2842                 $migrated++;
2843         }
2844         command_close_pipe($fh, $ctx);
2845         print STDERR "Done migrating from v0 layout...\n" if $migrated;
2846         $migrated;
2849 sub migrate_from_v1 {
2850         my $git_dir = $ENV{GIT_DIR};
2851         my $migrated = 0;
2852         return $migrated unless -d $git_dir;
2853         my $svn_dir = "$git_dir/svn";
2855         # just in case somebody used 'svn' as their $id at some point...
2856         return $migrated if -d $svn_dir && ! -f "$svn_dir/info/url";
2858         print STDERR "Migrating from a git-svn v1 layout...\n";
2859         mkpath([$svn_dir]);
2860         print STDERR "Data from a previous version of git-svn exists, but\n\t",
2861                      "$svn_dir\n\t(required for this version ",
2862                      "($::VERSION) of git-svn) does not. exist\n";
2863         my ($fh, $ctx) = command_output_pipe(qw/rev-parse --symbolic --all/);
2864         while (<$fh>) {
2865                 my $x = $_;
2866                 next unless $x =~ s#^refs/remotes/##;
2867                 chomp $x;
2868                 next unless -f "$git_dir/$x/info/url";
2869                 my $u = eval { ::file_to_s("$git_dir/$x/info/url") };
2870                 next unless $u;
2871                 my $dn = dirname("$git_dir/svn/$x");
2872                 mkpath([$dn]) unless -d $dn;
2873                 if ($x eq 'svn') { # they used 'svn' as GIT_SVN_ID:
2874                         mkpath(["$git_dir/svn/svn"]);
2875                         print STDERR " - $git_dir/$x/info => ",
2876                                         "$git_dir/svn/$x/info\n";
2877                         rename "$git_dir/$x/info", "$git_dir/svn/$x/info" or
2878                                croak "$!: $x";
2879                         # don't worry too much about these, they probably
2880                         # don't exist with repos this old (save for index,
2881                         # and we can easily regenerate that)
2882                         foreach my $f (qw/unhandled.log index .rev_db/) {
2883                                 rename "$git_dir/$x/$f", "$git_dir/svn/$x/$f";
2884                         }
2885                 } else {
2886                         print STDERR " - $git_dir/$x => $git_dir/svn/$x\n";
2887                         rename "$git_dir/$x", "$git_dir/svn/$x" or
2888                                croak "$!: $x";
2889                 }
2890                 $migrated++;
2891         }
2892         command_close_pipe($fh, $ctx);
2893         print STDERR "Done migrating from a git-svn v1 layout\n";
2894         $migrated;
2897 sub read_old_urls {
2898         my ($l_map, $pfx, $path) = @_;
2899         my @dir;
2900         foreach (<$path/*>) {
2901                 if (-r "$_/info/url") {
2902                         $pfx .= '/' if $pfx && $pfx !~ m!/$!;
2903                         my $ref_id = $pfx . basename $_;
2904                         my $url = ::file_to_s("$_/info/url");
2905                         $l_map->{$ref_id} = $url;
2906                 } elsif (-d $_) {
2907                         push @dir, $_;
2908                 }
2909         }
2910         foreach (@dir) {
2911                 my $x = $_;
2912                 $x =~ s!^\Q$ENV{GIT_DIR}\E/svn/!!o;
2913                 read_old_urls($l_map, $x, $_);
2914         }
2917 sub migrate_from_v2 {
2918         my @cfg = command(qw/config -l/);
2919         return if grep /^svn-remote\..+\.url=/, @cfg;
2920         my %l_map;
2921         read_old_urls(\%l_map, '', "$ENV{GIT_DIR}/svn");
2922         my $migrated = 0;
2924         foreach my $ref_id (sort keys %l_map) {
2925                 Git::SVN->init($l_map{$ref_id}, '', $ref_id, $ref_id);
2926                 $migrated++;
2927         }
2928         $migrated;
2931 sub minimize_connections {
2932         my $r = Git::SVN::read_all_remotes();
2933         my $new_urls = {};
2934         my $root_repos = {};
2935         foreach my $repo_id (keys %$r) {
2936                 my $url = $r->{$repo_id}->{url} or next;
2937                 my $fetch = $r->{$repo_id}->{fetch} or next;
2938                 my $ra = Git::SVN::Ra->new($url);
2940                 # skip existing cases where we already connect to the root
2941                 if (($ra->{url} eq $ra->{repos_root}) ||
2942                     (Git::SVN::sanitize_remote_name($ra->{repos_root}) eq
2943                      $repo_id)) {
2944                         $root_repos->{$ra->{url}} = $repo_id;
2945                         next;
2946                 }
2948                 my $root_ra = Git::SVN::Ra->new($ra->{repos_root});
2949                 my $root_path = $ra->{url};
2950                 $root_path =~ s#^\Q$ra->{repos_root}\E/*##;
2951                 foreach my $path (keys %$fetch) {
2952                         my $ref_id = $fetch->{$path};
2953                         my $gs = Git::SVN->new($ref_id, $repo_id, $path);
2955                         # make sure we can read when connecting to
2956                         # a higher level of a repository
2957                         my ($last_rev, undef) = $gs->last_rev_commit;
2958                         if (!defined $last_rev) {
2959                                 $last_rev = eval {
2960                                         $root_ra->get_latest_revnum;
2961                                 };
2962                                 next if $@;
2963                         }
2964                         my $new = $root_path;
2965                         $new .= length $path ? "/$path" : '';
2966                         eval {
2967                                 $root_ra->get_log([$new], $last_rev, $last_rev,
2968                                                   0, 0, 1, sub { });
2969                         };
2970                         next if $@;
2971                         $new_urls->{$ra->{repos_root}}->{$new} =
2972                                 { ref_id => $ref_id,
2973                                   old_repo_id => $repo_id,
2974                                   old_path => $path };
2975                 }
2976         }
2978         my @emptied;
2979         foreach my $url (keys %$new_urls) {
2980                 # see if we can re-use an existing [svn-remote "repo_id"]
2981                 # instead of creating a(n ugly) new section:
2982                 my $repo_id = $root_repos->{$url} ||
2983                               Git::SVN::sanitize_remote_name($url);
2985                 my $fetch = $new_urls->{$url};
2986                 foreach my $path (keys %$fetch) {
2987                         my $x = $fetch->{$path};
2988                         Git::SVN->init($url, $path, $repo_id, $x->{ref_id});
2989                         my $pfx = "svn-remote.$x->{old_repo_id}";
2991                         my $old_fetch = quotemeta("$x->{old_path}:".
2992                                                   "refs/remotes/$x->{ref_id}");
2993                         command_noisy(qw/config --unset/,
2994                                       "$pfx.fetch", '^'. $old_fetch . '$');
2995                         delete $r->{$x->{old_repo_id}}->
2996                                {fetch}->{$x->{old_path}};
2997                         if (!keys %{$r->{$x->{old_repo_id}}->{fetch}}) {
2998                                 command_noisy(qw/config --unset/,
2999                                               "$pfx.url");
3000                                 push @emptied, $x->{old_repo_id}
3001                         }
3002                 }
3003         }
3004         if (@emptied) {
3005                 my $file = $ENV{GIT_CONFIG} || $ENV{GIT_CONFIG_LOCAL} ||
3006                            "$ENV{GIT_DIR}/config";
3007                 print STDERR <<EOF;
3008 The following [svn-remote] sections in your config file ($file) are empty
3009 and can be safely removed:
3010 EOF
3011                 print STDERR "[svn-remote \"$_\"]\n" foreach @emptied;
3012         }
3015 sub migration_check {
3016         migrate_from_v0();
3017         migrate_from_v1();
3018         migrate_from_v2();
3019         minimize_connections() if $_minimize;
3022 package Git::IndexInfo;
3023 use strict;
3024 use warnings;
3025 use Git qw/command_input_pipe command_close_pipe/;
3027 sub new {
3028         my ($class) = @_;
3029         my ($gui, $ctx) = command_input_pipe(qw/update-index -z --index-info/);
3030         bless { gui => $gui, ctx => $ctx, nr => 0}, $class;
3033 sub remove {
3034         my ($self, $path) = @_;
3035         if (print { $self->{gui} } '0 ', 0 x 40, "\t", $path, "\0") {
3036                 return ++$self->{nr};
3037         }
3038         undef;
3041 sub update {
3042         my ($self, $mode, $hash, $path) = @_;
3043         if (print { $self->{gui} } $mode, ' ', $hash, "\t", $path, "\0") {
3044                 return ++$self->{nr};
3045         }
3046         undef;
3049 sub DESTROY {
3050         my ($self) = @_;
3051         command_close_pipe($self->{gui}, $self->{ctx});
3054 __END__
3056 Data structures:
3058 $log_entry hashref as returned by libsvn_log_entry()
3060         log => 'whitespace-formatted log entry
3061 ',                                              # trailing newline is preserved
3062         revision => '8',                        # integer
3063         date => '2004-02-24T17:01:44.108345Z',  # commit date
3064         author => 'committer name'
3065 };
3068 # this is generated by generate_diff();
3069 @mods = array of diff-index line hashes, each element represents one line
3070         of diff-index output
3072 diff-index line ($m hash)
3074         mode_a => first column of diff-index output, no leading ':',
3075         mode_b => second column of diff-index output,
3076         sha1_b => sha1sum of the final blob,
3077         chg => change type [MCRADT],
3078         file_a => original file name of a file (iff chg is 'C' or 'R')
3079         file_b => new/current file name of a file (any chg)
3083 # retval of read_url_paths{,_all}();
3084 $l_map = {
3085         # repository root url
3086         'https://svn.musicpd.org' => {
3087                 # repository path               # GIT_SVN_ID
3088                 'mpd/trunk'             =>      'trunk',
3089                 'mpd/tags/0.11.5'       =>      'tags/0.11.5',
3090         },
3093 Notes:
3094         I don't trust the each() function on unless I created %hash myself
3095         because the internal iterator may not have started at base.