Code

git-svn: run get_log() on a sub-directory if possible
[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 = '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                 if ($remotes->{$repo_id}->{url} &&
371                     $remotes->{$repo_id}->{fetch}) {
372                         Git::SVN::fetch_all($repo_id, $remotes);
373                 }
374         }
377 # this command is special because it requires no metadata
378 sub cmd_commit_diff {
379         my ($ta, $tb, $url) = @_;
380         my $usage = "Usage: $0 commit-diff -r<revision> ".
381                     "<tree-ish> <tree-ish> [<URL>]\n";
382         fatal($usage) if (!defined $ta || !defined $tb);
383         my $svn_path;
384         if (!defined $url) {
385                 my $gs = eval { Git::SVN->new };
386                 if (!$gs) {
387                         fatal("Needed URL or usable git-svn --id in ",
388                               "the command-line\n", $usage);
389                 }
390                 $url = $gs->{url};
391                 $svn_path = $gs->{path};
392         }
393         unless (defined $_revision) {
394                 fatal("-r|--revision is a required argument\n", $usage);
395         }
396         if (defined $_message && defined $_file) {
397                 fatal("Both --message/-m and --file/-F specified ",
398                       "for the commit message.\n",
399                       "I have no idea what you mean\n");
400         }
401         if (defined $_file) {
402                 $_message = file_to_s($_file);
403         } else {
404                 $_message ||= get_commit_entry($tb)->{log};
405         }
406         my $ra ||= Git::SVN::Ra->new($url);
407         $svn_path ||= $ra->{svn_path};
408         my $r = $_revision;
409         if ($r eq 'HEAD') {
410                 $r = $ra->get_latest_revnum;
411         } elsif ($r !~ /^\d+$/) {
412                 die "revision argument: $r not understood by git-svn\n";
413         }
414         my %ed_opts = ( r => $r,
415                         log => $_message,
416                         ra => $ra,
417                         tree_a => $ta,
418                         tree_b => $tb,
419                         editor_cb => sub { print "Committed r$_[0]\n" },
420                         svn_path => $svn_path );
421         if (!SVN::Git::Editor->new(\%ed_opts)->apply_diff) {
422                 print "No changes\n$ta == $tb\n";
423         }
426 ########################### utility functions #########################
428 sub parse_revision_argument {
429         if (!defined $_revision || $_revision eq 'BASE:HEAD') {
430                 return (undef, undef);
431         }
432         return ($1, $2) if ($_revision =~ /^(\d+):(\d+)$/);
433         return ($_revision, $_revision) if ($_revision =~ /^\d+$/);
434         return (undef, $1) if ($_revision =~ /^BASE:(\d+)$/);
435         return ($1, undef) if ($_revision =~ /^(\d+):HEAD$/);
436         die "revision argument: $_revision not understood by git-svn\n",
437             "Try using the command-line svn client instead\n";
440 sub complete_svn_url {
441         my ($url, $path) = @_;
442         $path =~ s#/+$##;
443         if ($path !~ m#^[a-z\+]+://#) {
444                 if (!defined $url || $url !~ m#^[a-z\+]+://#) {
445                         fatal("E: '$path' is not a complete URL ",
446                               "and a separate URL is not specified\n");
447                 }
448                 return ($url, $path);
449         }
450         return ($path, '');
453 sub complete_url_ls_init {
454         my ($ra, $repo_path, $switch, $pfx) = @_;
455         unless ($repo_path) {
456                 print STDERR "W: $switch not specified\n";
457                 return;
458         }
459         $repo_path =~ s#/+$##;
460         if ($repo_path =~ m#^[a-z\+]+://#) {
461                 $ra = Git::SVN::Ra->new($repo_path);
462                 $repo_path = '';
463         } else {
464                 $repo_path =~ s#^/+##;
465                 unless ($ra) {
466                         fatal("E: '$repo_path' is not a complete URL ",
467                               "and a separate URL is not specified\n");
468                 }
469         }
470         my $r = defined $_revision ? $_revision : $ra->get_latest_revnum;
471         my ($dirent, undef, undef) = $ra->get_dir($repo_path, $r);
472         my $url = $ra->{url};
473         my $remote_id;
474         my $remote_path;
475         foreach my $d (sort keys %$dirent) {
476                 next if ($dirent->{$d}->kind != $SVN::Node::dir);
477                 my $path =  "$repo_path/$d";
478                 my $ref = "$pfx$d";
479                 my $gs = eval { Git::SVN->new($ref) };
480                 # don't try to init already existing refs
481                 unless ($gs) {
482                         print "init $url/$path => $ref\n";
483                         $gs = Git::SVN->init($url, $path, undef, $ref, 1);
484                 }
485                 if ($gs) {
486                         $remote_id = $gs->{repo_id};
487                         last;
488                 }
489         }
490         if (defined $remote_id) {
491                 $remote_path = "$ra->{svn_path}/$repo_path/*";
492                 $remote_path =~ s#/+#/#g;
493                 $remote_path =~ s#^/##g;
494                 my ($n) = ($switch =~ /^--(\w+)/);
495                 command_noisy('config', "svn-remote.$remote_id.$n",
496                                         "$remote_path:refs/remotes/$pfx*");
497         }
500 sub verify_ref {
501         my ($ref) = @_;
502         eval { command_oneline([ 'rev-parse', '--verify', $ref ],
503                                { STDERR => 0 }); };
506 sub get_tree_from_treeish {
507         my ($treeish) = @_;
508         # $treeish can be a symbolic ref, too:
509         my $type = command_oneline(qw/cat-file -t/, $treeish);
510         my $expected;
511         while ($type eq 'tag') {
512                 ($treeish, $type) = command(qw/cat-file tag/, $treeish);
513         }
514         if ($type eq 'commit') {
515                 $expected = (grep /^tree /, command(qw/cat-file commit/,
516                                                     $treeish))[0];
517                 ($expected) = ($expected =~ /^tree ($sha1)$/o);
518                 die "Unable to get tree from $treeish\n" unless $expected;
519         } elsif ($type eq 'tree') {
520                 $expected = $treeish;
521         } else {
522                 die "$treeish is a $type, expected tree, tag or commit\n";
523         }
524         return $expected;
527 sub get_commit_entry {
528         my ($treeish) = shift;
529         my %log_entry = ( log => '', tree => get_tree_from_treeish($treeish) );
530         my $commit_editmsg = "$ENV{GIT_DIR}/COMMIT_EDITMSG";
531         my $commit_msg = "$ENV{GIT_DIR}/COMMIT_MSG";
532         open my $log_fh, '>', $commit_editmsg or croak $!;
534         my $type = command_oneline(qw/cat-file -t/, $treeish);
535         if ($type eq 'commit' || $type eq 'tag') {
536                 my ($msg_fh, $ctx) = command_output_pipe('cat-file',
537                                                          $type, $treeish);
538                 my $in_msg = 0;
539                 while (<$msg_fh>) {
540                         if (!$in_msg) {
541                                 $in_msg = 1 if (/^\s*$/);
542                         } elsif (/^git-svn-id: /) {
543                                 # skip this for now, we regenerate the
544                                 # correct one on re-fetch anyways
545                                 # TODO: set *:merge properties or like...
546                         } else {
547                                 print $log_fh $_ or croak $!;
548                         }
549                 }
550                 command_close_pipe($msg_fh, $ctx);
551         }
552         close $log_fh or croak $!;
554         if ($_edit || ($type eq 'tree')) {
555                 my $editor = $ENV{VISUAL} || $ENV{EDITOR} || 'vi';
556                 # TODO: strip out spaces, comments, like git-commit.sh
557                 system($editor, $commit_editmsg);
558         }
559         rename $commit_editmsg, $commit_msg or croak $!;
560         open $log_fh, '<', $commit_msg or croak $!;
561         { local $/; chomp($log_entry{log} = <$log_fh>); }
562         close $log_fh or croak $!;
563         unlink $commit_msg;
564         \%log_entry;
567 sub s_to_file {
568         my ($str, $file, $mode) = @_;
569         open my $fd,'>',$file or croak $!;
570         print $fd $str,"\n" or croak $!;
571         close $fd or croak $!;
572         chmod ($mode &~ umask, $file) if (defined $mode);
575 sub file_to_s {
576         my $file = shift;
577         open my $fd,'<',$file or croak "$!: file: $file\n";
578         local $/;
579         my $ret = <$fd>;
580         close $fd or croak $!;
581         $ret =~ s/\s*$//s;
582         return $ret;
585 # '<svn username> = real-name <email address>' mapping based on git-svnimport:
586 sub load_authors {
587         open my $authors, '<', $_authors or die "Can't open $_authors $!\n";
588         my $log = $cmd eq 'log';
589         while (<$authors>) {
590                 chomp;
591                 next unless /^(\S+?|\(no author\))\s*=\s*(.+?)\s*<(.+)>\s*$/;
592                 my ($user, $name, $email) = ($1, $2, $3);
593                 if ($log) {
594                         $Git::SVN::Log::rusers{"$name <$email>"} = $user;
595                 } else {
596                         $users{$user} = [$name, $email];
597                 }
598         }
599         close $authors or croak $!;
602 # convert GetOpt::Long specs for use by git-config
603 sub read_repo_config {
604         return unless -d $ENV{GIT_DIR};
605         my $opts = shift;
606         foreach my $o (keys %$opts) {
607                 my $v = $opts->{$o};
608                 my ($key) = ($o =~ /^([a-z\-]+)/);
609                 $key =~ s/-//g;
610                 my $arg = 'git-config';
611                 $arg .= ' --int' if ($o =~ /[:=]i$/);
612                 $arg .= ' --bool' if ($o !~ /[:=][sfi]$/);
613                 if (ref $v eq 'ARRAY') {
614                         chomp(my @tmp = `$arg --get-all svn.$key`);
615                         @$v = @tmp if @tmp;
616                 } else {
617                         chomp(my $tmp = `$arg --get svn.$key`);
618                         if ($tmp && !($arg =~ / --bool/ && $tmp eq 'false')) {
619                                 $$v = $tmp;
620                         }
621                 }
622         }
625 sub extract_metadata {
626         my $id = shift or return (undef, undef, undef);
627         my ($url, $rev, $uuid) = ($id =~ /^git-svn-id:\s(\S+?)\@(\d+)
628                                                         \s([a-f\d\-]+)$/x);
629         if (!defined $rev || !$uuid || !$url) {
630                 # some of the original repositories I made had
631                 # identifiers like this:
632                 ($rev, $uuid) = ($id =~/^git-svn-id:\s(\d+)\@([a-f\d\-]+)/);
633         }
634         return ($url, $rev, $uuid);
637 sub cmt_metadata {
638         return extract_metadata((grep(/^git-svn-id: /,
639                 command(qw/cat-file commit/, shift)))[-1]);
642 package Git::SVN;
643 use strict;
644 use warnings;
645 use vars qw/$default_repo_id $default_ref_id $_no_metadata $_follow_parent
646             $_repack $_repack_flags/;
647 use Carp qw/croak/;
648 use File::Path qw/mkpath/;
649 use File::Copy qw/copy/;
650 use IPC::Open3;
652 my $_repack_nr;
653 # properties that we do not log:
654 my %SKIP_PROP;
655 BEGIN {
656         %SKIP_PROP = map { $_ => 1 } qw/svn:wc:ra_dav:version-url
657                                         svn:special svn:executable
658                                         svn:entry:committed-rev
659                                         svn:entry:last-author
660                                         svn:entry:uuid
661                                         svn:entry:committed-date/;
664 my %LOCKFILES;
665 END { unlink keys %LOCKFILES if %LOCKFILES }
667 sub resolve_local_globs {
668         my ($url, $fetch, $glob_spec) = @_;
669         return unless defined $glob_spec;
670         my $ref = $glob_spec->{ref};
671         my $path = $glob_spec->{path};
672         foreach (command(qw#for-each-ref --format=%(refname) refs/remotes#)) {
673                 next unless m#^refs/remotes/$ref->{regex}$#;
674                 my $p = $1;
675                 my $pathname = $path->full_path($p);
676                 my $refname = $ref->full_path($p);
677                 if (my $existing = $fetch->{$pathname}) {
678                         if ($existing ne $refname) {
679                                 die "Refspec conflict:\n",
680                                     "existing: refs/remotes/$existing\n",
681                                     " globbed: refs/remotes/$refname\n";
682                         }
683                         my $u = (::cmt_metadata("refs/remotes/$refname"))[0];
684                         $u =~ s!^\Q$url\E/?!! or die
685                           "refs/remotes/$refname: '$url' not found in '$u'\n";
686                         if ($pathname ne $u) {
687                                 warn "W: Refspec glob conflict ",
688                                      "(ref: refs/remotes/$refname):\n",
689                                      "expected path: $pathname\n",
690                                      "    real path: $u\n",
691                                      "Continuing ahead with $u\n";
692                                 next;
693                         }
694                 } else {
695                         warn "Globbed ($path->{glob}:$ref->{glob}): ",
696                              "$pathname == $refname\n";
697                         $fetch->{$pathname} = $refname;
698                 }
699         }
702 sub fetch_all {
703         my ($repo_id, $remotes) = @_;
704         my $fetch = $remotes->{$repo_id}->{fetch};
705         my $url = $remotes->{$repo_id}->{url};
706         my @gs;
707         resolve_local_globs($url, $fetch, $remotes->{$repo_id}->{branches});
708         resolve_local_globs($url, $fetch, $remotes->{$repo_id}->{tags});
709         my $ra = Git::SVN::Ra->new($url);
710         my $head = $ra->get_latest_revnum;
711         my $base = $head;
712         foreach my $p (sort keys %$fetch) {
713                 my $gs = Git::SVN->new($fetch->{$p}, $repo_id, $p);
714                 my $lr = $gs->rev_db_max;
715                 if (defined $lr) {
716                         $base = $lr if ($lr < $base);
717                 }
718                 push @gs, $gs;
719         }
720         return if (++$base > $head);
721         $ra->gs_fetch_loop_common($base, $head, @gs);
724 sub read_all_remotes {
725         my $r = {};
726         foreach (grep { s/^svn-remote\.// } command(qw/config -l/)) {
727                 if (m!^(.+)\.fetch=\s*(.*)\s*:\s*refs/remotes/(.+)\s*$!) {
728                         $r->{$1}->{fetch}->{$2} = $3;
729                 } elsif (m!^(.+)\.url=\s*(.*)\s*$!) {
730                         $r->{$1}->{url} = $2;
731                 } elsif (m!^(.+)\.(branches|tags)=
732                            (.*):refs/remotes/(.+)\s*$/!x) {
733                         my ($p, $g) = ($3, $4);
734                         my $rs = $r->{$1}->{$2} = {
735                                           path => Git::SVN::GlobSpec->new($p),
736                                           ref => Git::SVN::GlobSpec->new($g) };
737                         if (length($rs->{ref}->{right}) != 0) {
738                                 die "The '*' glob character must be the last ",
739                                     "character of '$g'\n";
740                         }
741                 }
742         }
743         $r;
746 sub init_vars {
747         if (defined $_repack) {
748                 $_repack = 1000 if ($_repack <= 0);
749                 $_repack_nr = $_repack;
750                 $_repack_flags ||= '-d';
751         }
754 sub verify_remotes_sanity {
755         return unless -d $ENV{GIT_DIR};
756         my %seen;
757         foreach (command(qw/config -l/)) {
758                 if (m!^svn-remote\.(?:.+)\.fetch=.*:refs/remotes/(\S+)\s*$!) {
759                         if ($seen{$1}) {
760                                 die "Remote ref refs/remote/$1 is tracked by",
761                                     "\n  \"$_\"\nand\n  \"$seen{$1}\"\n",
762                                     "Please resolve this ambiguity in ",
763                                     "your git configuration file before ",
764                                     "continuing\n";
765                         }
766                         $seen{$1} = $_;
767                 }
768         }
771 # we allow more chars than remotes2config.sh...
772 sub sanitize_remote_name {
773         my ($name) = @_;
774         $name =~ tr{A-Za-z0-9:,/+-}{.}c;
775         $name;
778 sub find_existing_remote {
779         my ($url, $remotes) = @_;
780         my $existing;
781         foreach my $repo_id (keys %$remotes) {
782                 my $u = $remotes->{$repo_id}->{url} or next;
783                 next if $u ne $url;
784                 $existing = $repo_id;
785                 last;
786         }
787         $existing;
790 sub init_remote_config {
791         my ($self, $url, $no_write) = @_;
792         $url =~ s!/+$!!; # strip trailing slash
793         my $r = read_all_remotes();
794         my $existing = find_existing_remote($url, $r);
795         if ($existing) {
796                 print STDERR "Using existing ",
797                              "[svn-remote \"$existing\"]\n";
798                 $self->{repo_id} = $existing;
799         } else {
800                 my $min_url = Git::SVN::Ra->new($url)->minimize_url;
801                 $existing = find_existing_remote($min_url, $r);
802                 if ($existing) {
803                         print STDERR "Using existing ",
804                                      "[svn-remote \"$existing\"]\n";
805                         $self->{repo_id} = $existing;
806                 }
807                 if ($min_url ne $url) {
808                         print STDERR "Using higher level of URL: ",
809                                      "$url => $min_url\n";
810                         my $old_path = $self->{path};
811                         $self->{path} = $url;
812                         $self->{path} =~ s!^\Q$min_url\E/*!!;
813                         if (length $old_path) {
814                                 $self->{path} .= "/$old_path";
815                         }
816                         $url = $min_url;
817                 }
818         }
819         my $orig_url;
820         if (!$existing) {
821                 # verify that we aren't overwriting anything:
822                 $orig_url = eval {
823                         command_oneline('config', '--get',
824                                         "svn-remote.$self->{repo_id}.url")
825                 };
826                 if ($orig_url && ($orig_url ne $url)) {
827                         die "svn-remote.$self->{repo_id}.url already set: ",
828                             "$orig_url\nwanted to set to: $url\n";
829                 }
830         }
831         my ($xrepo_id, $xpath) = find_ref($self->refname);
832         if (defined $xpath) {
833                 die "svn-remote.$xrepo_id.fetch already set to track ",
834                     "$xpath:refs/remotes/", $self->refname, "\n";
835         }
836         unless ($no_write) {
837                 command_noisy('config',
838                               "svn-remote.$self->{repo_id}.url", $url);
839                 command_noisy('config', '--add',
840                               "svn-remote.$self->{repo_id}.fetch",
841                               "$self->{path}:".$self->refname);
842         }
843         $self->{url} = $url;
846 sub init {
847         my ($class, $url, $path, $repo_id, $ref_id, $no_write) = @_;
848         my $self = _new($class, $repo_id, $ref_id, $path);
849         if (defined $url) {
850                 $self->init_remote_config($url, $no_write);
851         }
852         $self;
855 sub find_ref {
856         my ($ref_id) = @_;
857         foreach (command(qw/config -l/)) {
858                 next unless m!^svn-remote\.(.+)\.fetch=
859                               \s*(.*)\s*:\s*refs/remotes/(.+)\s*$!x;
860                 my ($repo_id, $path, $ref) = ($1, $2, $3);
861                 if ($ref eq $ref_id) {
862                         $path = '' if ($path =~ m#^\./?#);
863                         return ($repo_id, $path);
864                 }
865         }
866         (undef, undef, undef);
869 sub new {
870         my ($class, $ref_id, $repo_id, $path) = @_;
871         if (defined $ref_id && !defined $repo_id && !defined $path) {
872                 ($repo_id, $path) = find_ref($ref_id);
873                 if (!defined $repo_id) {
874                         die "Could not find a \"svn-remote.*.fetch\" key ",
875                             "in the repository configuration matching: ",
876                             "refs/remotes/$ref_id\n";
877                 }
878         }
879         my $self = _new($class, $repo_id, $ref_id, $path);
880         if (!defined $self->{path} || !length $self->{path}) {
881                 my $fetch = command_oneline('config', '--get',
882                                             "svn-remote.$repo_id.fetch",
883                                             ":refs/remotes/$ref_id\$") or
884                      die "Failed to read \"svn-remote.$repo_id.fetch\" ",
885                          "\":refs/remotes/$ref_id\$\" in config\n";
886                 ($self->{path}, undef) = split(/\s*:\s*/, $fetch);
887         }
888         $self->{url} = command_oneline('config', '--get',
889                                        "svn-remote.$repo_id.url") or
890                   die "Failed to read \"svn-remote.$repo_id.url\" in config\n";
891         if (-z $self->{db_path} && ::verify_ref($self->refname.'^0')) {
892                 $self->rebuild;
893         }
894         $self;
897 sub refname { "refs/remotes/$_[0]->{ref_id}" }
899 sub ra {
900         my ($self) = shift;
901         Git::SVN::Ra->new($self->{url});
904 sub rel_path {
905         my ($self) = @_;
906         my $repos_root = $self->ra->{repos_root};
907         return $self->{path} if ($self->{url} eq $repos_root);
908         my $url = $self->{url} .
909                   (length $self->{path} ? "/$self->{path}" : $self->{path});
910         $url =~ s!^\Q$repos_root\E/*!!g;
911         $url;
914 sub traverse_ignore {
915         my ($self, $fh, $path, $r) = @_;
916         $path =~ s#^/+##g;
917         my $ra = $self->ra;
918         my ($dirent, undef, $props) = $ra->get_dir($path, $r);
919         my $p = $path;
920         $p =~ s#^\Q$ra->{svn_path}\E/##;
921         print $fh length $p ? "\n# $p\n" : "\n# /\n";
922         if (my $s = $props->{'svn:ignore'}) {
923                 $s =~ s/[\r\n]+/\n/g;
924                 chomp $s;
925                 if (length $p == 0) {
926                         $s =~ s#\n#\n/$p#g;
927                         print $fh "/$s\n";
928                 } else {
929                         $s =~ s#\n#\n/$p/#g;
930                         print $fh "/$p/$s\n";
931                 }
932         }
933         foreach (sort keys %$dirent) {
934                 next if $dirent->{$_}->kind != $SVN::Node::dir;
935                 $self->traverse_ignore($fh, "$path/$_", $r);
936         }
939 sub last_rev { ($_[0]->last_rev_commit)[0] }
940 sub last_commit { ($_[0]->last_rev_commit)[1] }
942 # returns the newest SVN revision number and newest commit SHA1
943 sub last_rev_commit {
944         my ($self) = @_;
945         if (defined $self->{last_rev} && defined $self->{last_commit}) {
946                 return ($self->{last_rev}, $self->{last_commit});
947         }
948         my $c = ::verify_ref($self->refname.'^0');
949         if ($c) {
950                 my $rev = (::cmt_metadata($c))[1];
951                 if (defined $rev) {
952                         ($self->{last_rev}, $self->{last_commit}) = ($rev, $c);
953                         return ($rev, $c);
954                 }
955         }
956         my $offset = -41; # from tail
957         my $rl;
958         open my $fh, '<', $self->{db_path} or
959                                  croak "$self->{db_path} not readable: $!\n";
960         sysseek($fh, $offset, 2); # don't care for errors
961         sysread($fh, $rl, 41) == 41 or return (undef, undef);
962         chomp $rl;
963         while (('0' x40) eq $rl && sysseek($fh, 0, 1) != 0) {
964                 $offset -= 41;
965                 sysseek($fh, $offset, 2); # don't care for errors
966                 sysread($fh, $rl, 41) == 41 or return (undef, undef);
967                 chomp $rl;
968         }
969         if ($c) {
970                 die "$self->{db_path} and ", $self->refname,
971                     " inconsistent!:\n$c != $rl\n";
972         }
973         my $rev = sysseek($fh, 0, 1) or croak $!;
974         $rev =  ($rev - 41) / 41;
975         close $fh or croak $!;
976         ($self->{last_rev}, $self->{last_commit}) = ($rev, $c);
977         return ($rev, $c);
980 sub get_fetch_range {
981         my ($self, $min, $max) = @_;
982         $max ||= $self->ra->get_latest_revnum;
983         $min ||= $self->rev_db_max;
984         (++$min, $max);
987 sub tmp_index_do {
988         my ($self, $sub) = @_;
989         my $old_index = $ENV{GIT_INDEX_FILE};
990         $ENV{GIT_INDEX_FILE} = $self->{index};
991         my @ret = &$sub;
992         if ($old_index) {
993                 $ENV{GIT_INDEX_FILE} = $old_index;
994         } else {
995                 delete $ENV{GIT_INDEX_FILE};
996         }
997         wantarray ? @ret : $ret[0];
1000 sub assert_index_clean {
1001         my ($self, $treeish) = @_;
1003         $self->tmp_index_do(sub {
1004                 command_noisy('read-tree', $treeish) unless -e $self->{index};
1005                 my $x = command_oneline('write-tree');
1006                 my ($y) = (command(qw/cat-file commit/, $treeish) =~
1007                            /^tree ($::sha1)/mo);
1008                 if ($y ne $x) {
1009                         unlink $self->{index} or croak $!;
1010                         command_noisy('read-tree', $treeish);
1011                 }
1012                 $x = command_oneline('write-tree');
1013                 if ($y ne $x) {
1014                         ::fatal "trees ($treeish) $y != $x\n",
1015                                 "Something is seriously wrong...\n";
1016                 }
1017         });
1020 sub get_commit_parents {
1021         my ($self, $log_entry) = @_;
1022         my (%seen, @ret, @tmp);
1023         # legacy support for 'set-tree'; this is only used by set_tree_cb:
1024         if (my $ip = $self->{inject_parents}) {
1025                 if (my $commit = delete $ip->{$log_entry->{revision}}) {
1026                         push @tmp, $commit;
1027                 }
1028         }
1029         if (my $cur = ::verify_ref($self->refname.'^0')) {
1030                 push @tmp, $cur;
1031         }
1032         push @tmp, $_ foreach (@{$log_entry->{parents}}, @tmp);
1033         while (my $p = shift @tmp) {
1034                 next if $seen{$p};
1035                 $seen{$p} = 1;
1036                 push @ret, $p;
1037                 # MAXPARENT is defined to 16 in commit-tree.c:
1038                 last if @ret >= 16;
1039         }
1040         if (@tmp) {
1041                 die "r$log_entry->{revision}: No room for parents:\n\t",
1042                     join("\n\t", @tmp), "\n";
1043         }
1044         @ret;
1047 sub full_url {
1048         my ($self) = @_;
1049         $self->{url} . (length $self->{path} ? '/' . $self->{path} : '');
1052 sub do_git_commit {
1053         my ($self, $log_entry) = @_;
1054         my $lr = $self->last_rev;
1055         if (defined $lr && $lr >= $log_entry->{revision}) {
1056                 die "Last fetched revision of ", $self->refname,
1057                     " was r$lr, but we are about to fetch: ",
1058                     "r$log_entry->{revision}!\n";
1059         }
1060         if (my $c = $self->rev_db_get($log_entry->{revision})) {
1061                 croak "$log_entry->{revision} = $c already exists! ",
1062                       "Why are we refetching it?\n";
1063         }
1064         my $author = $log_entry->{author};
1065         my ($name, $email) = (defined $::users{$author} ? @{$::users{$author}}
1066                            : ($author, "$author\@".$self->ra->uuid));
1067         $ENV{GIT_AUTHOR_NAME} = $ENV{GIT_COMMITTER_NAME} = $name;
1068         $ENV{GIT_AUTHOR_EMAIL} = $ENV{GIT_COMMITTER_EMAIL} = $email;
1069         $ENV{GIT_AUTHOR_DATE} = $ENV{GIT_COMMITTER_DATE} = $log_entry->{date};
1071         my $tree = $log_entry->{tree};
1072         if (!defined $tree) {
1073                 $tree = $self->tmp_index_do(sub {
1074                                             command_oneline('write-tree') });
1075         }
1076         die "Tree is not a valid sha1: $tree\n" if $tree !~ /^$::sha1$/o;
1078         my @exec = ('git-commit-tree', $tree);
1079         foreach ($self->get_commit_parents($log_entry)) {
1080                 push @exec, '-p', $_;
1081         }
1082         defined(my $pid = open3(my $msg_fh, my $out_fh, '>&STDERR', @exec))
1083                                                                    or croak $!;
1084         print $msg_fh $log_entry->{log} or croak $!;
1085         unless ($_no_metadata) {
1086                 print $msg_fh "\ngit-svn-id: ", $self->full_url, '@',
1087                               $log_entry->{revision}, ' ',
1088                               $self->ra->uuid, "\n" or croak $!;
1089         }
1090         $msg_fh->flush == 0 or croak $!;
1091         close $msg_fh or croak $!;
1092         chomp(my $commit = do { local $/; <$out_fh> });
1093         close $out_fh or croak $!;
1094         waitpid $pid, 0;
1095         croak $? if $?;
1096         if ($commit !~ /^$::sha1$/o) {
1097                 die "Failed to commit, invalid sha1: $commit\n";
1098         }
1100         $self->rev_db_set($log_entry->{revision}, $commit, 1);
1102         $self->{last_rev} = $log_entry->{revision};
1103         $self->{last_commit} = $commit;
1104         print "r$log_entry->{revision} = $commit ($self->{ref_id})\n";
1105         if (defined $_repack && (--$_repack_nr == 0)) {
1106                 $_repack_nr = $_repack;
1107                 # repack doesn't use any arguments with spaces in them, does it?
1108                 print "Running git repack $_repack_flags ...\n";
1109                 command_noisy('repack', split(/\s+/, $_repack_flags));
1110                 print "Done repacking\n";
1111         }
1112         return $commit;
1115 sub match_paths {
1116         my ($self, $paths, $r) = @_;
1117         $self->{path_regex} ||= qr/^\/\Q$self->{path}\E\/?/;
1118         if (grep /$self->{path_regex}/, keys %$paths) {
1119                 return 1;
1120         }
1121         my $c = '';
1122         foreach (split m#/#, $self->{path}) {
1123                 $c .= "/$_";
1124                 next unless ($paths->{$c} && ($paths->{$c}->{action} eq 'A'));
1125                 my @x = eval { $self->ra->get_dir($self->{path}, $r) };
1126                 if (scalar @x == 3) {
1127                         return 1;
1128                 }
1129         }
1130         return 0;
1133 sub find_parent_branch {
1134         my ($self, $paths, $rev) = @_;
1135         return undef unless $_follow_parent;
1136         unless (defined $paths) {
1137                 my $err_handler = $SVN::Error::handler;
1138                 $SVN::Error::handler = \&Git::SVN::Ra::skip_unknown_revs;
1139                 $self->ra->get_log([$self->{path}], $rev, $rev, 0, 1, 1, sub {
1140                                    $paths =
1141                                       Git::SVN::Ra::dup_changed_paths($_[0]) });
1142                 $SVN::Error::handler = $err_handler;
1143         }
1144         return undef unless defined $paths;
1146         # look for a parent from another branch:
1147         my @b_path_components = split m#/#, $self->rel_path;
1148         my @a_path_components;
1149         my $i;
1150         while (@b_path_components) {
1151                 $i = $paths->{'/'.join('/', @b_path_components)};
1152                 last if $i;
1153                 unshift(@a_path_components, pop(@b_path_components));
1154         }
1155         goto not_found unless defined $i;
1156         my $branch_from = $i->{copyfrom_path} or goto not_found;
1157         if (@a_path_components) {
1158                 print STDERR "branch_from: $branch_from => ";
1159                 $branch_from .= '/'.join('/', @a_path_components);
1160                 print STDERR $branch_from, "\n";
1161         }
1162         my $r = $i->{copyfrom_rev};
1163         my $repos_root = $self->ra->{repos_root};
1164         my $url = $self->ra->{url};
1165         my $new_url = $repos_root . $branch_from;
1166         print STDERR  "Found possible branch point: ",
1167                       "$new_url => ", $self->full_url, ", $r\n";
1168         $branch_from =~ s#^/##;
1169         my $remotes = read_all_remotes();
1170         my $gs;
1171         foreach my $repo_id (keys %$remotes) {
1172                 my $u = $remotes->{$repo_id}->{url} or next;
1173                 next if $url ne $u;
1174                 my $fetch = $remotes->{$repo_id}->{fetch};
1175                 foreach my $f (keys %$fetch) {
1176                         next if $f ne $branch_from;
1177                         $gs = Git::SVN->new($fetch->{$f}, $repo_id, $f);
1178                         last;
1179                 }
1180                 last if $gs;
1181         }
1182         unless ($gs) {
1183                 my $ref_id = $self->{ref_id};
1184                 $ref_id =~ s/\@\d+$//;
1185                 $ref_id .= "\@$r";
1186                 # just grow a tail if we're not unique enough :x
1187                 $ref_id .= '-' while find_ref($ref_id);
1188                 print STDERR "Initializing parent: $ref_id\n";
1189                 $gs = Git::SVN->init($new_url, '', $ref_id, $ref_id, 1);
1190         }
1191         my ($r0, $parent) = $gs->find_rev_before($r, 1);
1192         if ($_follow_parent && (!defined $r0 || !defined $parent)) {
1193                 $gs->fetch(0, $r);
1194                 ($r0, $parent) = $gs->last_rev_commit;
1195         }
1196         if (defined $r0 && defined $parent) {
1197                 print STDERR "Found branch parent: ($self->{ref_id}) $parent\n";
1198                 $self->assert_index_clean($parent);
1199                 my $ed;
1200                 if ($self->ra->can_do_switch) {
1201                         print STDERR "Following parent with do_switch\n";
1202                         # do_switch works with svn/trunk >= r22312, but that
1203                         # is not included with SVN 1.4.3 (the latest version
1204                         # at the moment), so we can't rely on it
1205                         $self->{last_commit} = $parent;
1206                         $ed = SVN::Git::Fetcher->new($self);
1207                         $gs->ra->gs_do_switch($r0, $rev, $gs,
1208                                               $self->full_url, $ed)
1209                           or die "SVN connection failed somewhere...\n";
1210                 } else {
1211                         print STDERR "Following parent with do_update\n";
1212                         $ed = SVN::Git::Fetcher->new($self);
1213                         $self->ra->gs_do_update($rev, $rev, $self, $ed)
1214                           or die "SVN connection failed somewhere...\n";
1215                 }
1216                 print STDERR "Successfully followed parent\n";
1217                 return $self->make_log_entry($rev, [$parent], $ed);
1218         }
1219 not_found:
1220         print STDERR "Branch parent for path: '/",
1221                      $self->rel_path, "' @ r$rev not found:\n";
1222         return undef unless $paths;
1223         print STDERR "Changed paths:\n";
1224         foreach my $x (sort keys %$paths) {
1225                 my $p = $paths->{$x};
1226                 print STDERR "\t$p->{action}\t$x";
1227                 if ($p->{copyfrom_path}) {
1228                         print STDERR "(from $p->{copyfrom_path}: ",
1229                                      "$p->{copyfrom_rev})";
1230                 }
1231                 print STDERR "\n";
1232         }
1233         print STDERR '-'x72, "\n";
1234         return undef;
1237 sub do_fetch {
1238         my ($self, $paths, $rev) = @_;
1239         my $ed;
1240         my ($last_rev, @parents);
1241         if ($self->{last_commit}) {
1242                 $ed = SVN::Git::Fetcher->new($self);
1243                 $last_rev = $self->{last_rev};
1244                 $ed->{c} = $self->{last_commit};
1245                 @parents = ($self->{last_commit});
1246         } else {
1247                 $last_rev = $rev;
1248                 if (my $log_entry = $self->find_parent_branch($paths, $rev)) {
1249                         return $log_entry;
1250                 }
1251                 $ed = SVN::Git::Fetcher->new($self);
1252         }
1253         unless ($self->ra->gs_do_update($last_rev, $rev, $self, $ed)) {
1254                 die "SVN connection failed somewhere...\n";
1255         }
1256         $self->make_log_entry($rev, \@parents, $ed);
1259 sub get_untracked {
1260         my ($self, $ed) = @_;
1261         my @out;
1262         my $h = $ed->{empty};
1263         foreach (sort keys %$h) {
1264                 my $act = $h->{$_} ? '+empty_dir' : '-empty_dir';
1265                 push @out, "  $act: " . uri_encode($_);
1266                 warn "W: $act: $_\n";
1267         }
1268         foreach my $t (qw/dir_prop file_prop/) {
1269                 $h = $ed->{$t} or next;
1270                 foreach my $path (sort keys %$h) {
1271                         my $ppath = $path eq '' ? '.' : $path;
1272                         foreach my $prop (sort keys %{$h->{$path}}) {
1273                                 next if $SKIP_PROP{$prop};
1274                                 my $v = $h->{$path}->{$prop};
1275                                 my $t_ppath_prop = "$t: " .
1276                                                     uri_encode($ppath) . ' ' .
1277                                                     uri_encode($prop);
1278                                 if (defined $v) {
1279                                         push @out, "  +$t_ppath_prop " .
1280                                                    uri_encode($v);
1281                                 } else {
1282                                         push @out, "  -$t_ppath_prop";
1283                                 }
1284                         }
1285                 }
1286         }
1287         foreach my $t (qw/absent_file absent_directory/) {
1288                 $h = $ed->{$t} or next;
1289                 foreach my $parent (sort keys %$h) {
1290                         foreach my $path (sort @{$h->{$parent}}) {
1291                                 push @out, "  $t: " .
1292                                            uri_encode("$parent/$path");
1293                                 warn "W: $t: $parent/$path ",
1294                                      "Insufficient permissions?\n";
1295                         }
1296                 }
1297         }
1298         \@out;
1301 sub parse_svn_date {
1302         my $date = shift || return '+0000 1970-01-01 00:00:00';
1303         my ($Y,$m,$d,$H,$M,$S) = ($date =~ /^(\d{4})\-(\d\d)\-(\d\d)T
1304                                             (\d\d)\:(\d\d)\:(\d\d).\d+Z$/x) or
1305                                          croak "Unable to parse date: $date\n";
1306         "+0000 $Y-$m-$d $H:$M:$S";
1309 sub check_author {
1310         my ($author) = @_;
1311         if (!defined $author || length $author == 0) {
1312                 $author = '(no author)';
1313         }
1314         if (defined $::_authors && ! defined $::users{$author}) {
1315                 die "Author: $author not defined in $::_authors file\n";
1316         }
1317         $author;
1320 sub make_log_entry {
1321         my ($self, $rev, $parents, $ed) = @_;
1322         my $untracked = $self->get_untracked($ed);
1324         open my $un, '>>', "$self->{dir}/unhandled.log" or croak $!;
1325         print $un "r$rev\n" or croak $!;
1326         print $un $_, "\n" foreach @$untracked;
1327         my %log_entry = ( parents => $parents || [], revision => $rev,
1328                           log => '');
1330         my $logged = delete $self->{logged_rev_props};
1331         if (!$logged || $self->{-want_extra_revprops}) {
1332                 my $rp = $self->ra->rev_proplist($rev);
1333                 foreach (sort keys %$rp) {
1334                         my $v = $rp->{$_};
1335                         if (/^svn:(author|date|log)$/) {
1336                                 $log_entry{$1} = $v;
1337                         } else {
1338                                 print $un "  rev_prop: ", uri_encode($_), ' ',
1339                                           uri_encode($v), "\n";
1340                         }
1341                 }
1342         } else {
1343                 map { $log_entry{$_} = $logged->{$_} } keys %$logged;
1344         }
1345         close $un or croak $!;
1347         $log_entry{date} = parse_svn_date($log_entry{date});
1348         $log_entry{author} = check_author($log_entry{author});
1349         $log_entry{log} .= "\n";
1350         \%log_entry;
1353 sub fetch {
1354         my ($self, $min_rev, $max_rev, @parents) = @_;
1355         my ($last_rev, $last_commit) = $self->last_rev_commit;
1356         my ($base, $head) = $self->get_fetch_range($min_rev, $max_rev);
1357         return if ($base > $head);
1358         $self->ra->gs_fetch_loop_common($base, $head, $self);
1361 sub set_tree_cb {
1362         my ($self, $log_entry, $tree, $rev, $date, $author) = @_;
1363         # TODO: enable and test optimized commits:
1364         if (0 && $rev == ($self->{last_rev} + 1)) {
1365                 $log_entry->{revision} = $rev;
1366                 $log_entry->{author} = $author;
1367                 $self->do_git_commit($log_entry, "$rev=$tree");
1368         } else {
1369                 $self->{inject_parents} = { $rev => $tree };
1370                 $self->fetch(undef, undef);
1371         }
1374 sub set_tree {
1375         my ($self, $tree) = (shift, shift);
1376         my $log_entry = ::get_commit_entry($tree);
1377         unless ($self->{last_rev}) {
1378                 fatal("Must have an existing revision to commit\n");
1379         }
1380         my %ed_opts = ( r => $self->{last_rev},
1381                         log => $log_entry->{log},
1382                         ra => $self->ra,
1383                         tree_a => $self->{last_commit},
1384                         tree_b => $tree,
1385                         editor_cb => sub {
1386                                $self->set_tree_cb($log_entry, $tree, @_) },
1387                         svn_path => $self->{path} );
1388         if (!SVN::Git::Editor->new(\%ed_opts)->apply_diff) {
1389                 print "No changes\nr$self->{last_rev} = $tree\n";
1390         }
1393 sub rebuild {
1394         my ($self) = @_;
1395         print "Rebuilding $self->{db_path} ...\n";
1396         my ($rev_list, $ctx) = command_output_pipe("rev-list", $self->refname);
1397         my $latest;
1398         my $full_url = $self->full_url;
1399         my $svn_uuid;
1400         while (<$rev_list>) {
1401                 chomp;
1402                 my $c = $_;
1403                 die "Non-SHA1: $c\n" unless $c =~ /^$::sha1$/o;
1404                 my ($url, $rev, $uuid) = ::cmt_metadata($c);
1406                 # ignore merges (from set-tree)
1407                 next if (!defined $rev || !$uuid);
1409                 # if we merged or otherwise started elsewhere, this is
1410                 # how we break out of it
1411                 if ((defined $svn_uuid && ($uuid ne $svn_uuid)) ||
1412                     ($full_url && $url && ($url ne $full_url))) {
1413                         next;
1414                 }
1415                 $latest ||= $rev;
1416                 $svn_uuid ||= $uuid;
1418                 $self->rev_db_set($rev, $c);
1419                 print "r$rev = $c\n";
1420         }
1421         command_close_pipe($rev_list, $ctx);
1422         print "Done rebuilding $self->{db_path}\n";
1425 # rev_db:
1426 # Tie::File seems to be prone to offset errors if revisions get sparse,
1427 # it's not that fast, either.  Tie::File is also not in Perl 5.6.  So
1428 # one of my favorite modules is out :<  Next up would be one of the DBM
1429 # modules, but I'm not sure which is most portable...  So I'll just
1430 # go with something that's plain-text, but still capable of
1431 # being randomly accessed.  So here's my ultra-simple fixed-width
1432 # database.  All records are 40 characters + "\n", so it's easy to seek
1433 # to a revision: (41 * rev) is the byte offset.
1434 # A record of 40 0s denotes an empty revision.
1435 # And yes, it's still pretty fast (faster than Tie::File).
1436 # These files are disposable unless --no-metadata is set
1438 sub rev_db_set {
1439         my ($self, $rev, $commit, $update_ref) = @_;
1440         length $commit == 40 or croak "arg3 must be a full SHA1 hexsum\n";
1441         my ($db, $db_lock) = ($self->{db_path}, "$self->{db_path}.lock");
1442         my $sig;
1443         if ($update_ref) {
1444                 $SIG{INT} = $SIG{HUP} = $SIG{TERM} = $SIG{ALRM} = $SIG{PIPE} =
1445                             $SIG{USR1} = $SIG{USR2} = sub { $sig = $_[0] };
1446         }
1447         $LOCKFILES{$db_lock} = 1;
1448         if ($_no_metadata) {
1449                 copy($db, $db_lock) or die "rev_db_set(@_): ",
1450                                            "Failed to copy: ",
1451                                            "$db => $db_lock ($!)\n";
1452         } else {
1453                 rename $db, $db_lock or die "rev_db_set(@_): ",
1454                                             "Failed to rename: ",
1455                                             "$db => $db_lock ($!)\n";
1456         }
1457         open my $fh, '+<', $db_lock or croak $!;
1458         my $offset = $rev * 41;
1459         # assume that append is the common case:
1460         seek $fh, 0, 2 or croak $!;
1461         my $pos = tell $fh;
1462         if ($pos < $offset) {
1463                 for (1 .. (($offset - $pos) / 41)) {
1464                         print $fh (('0' x 40),"\n") or croak $!;
1465                 }
1466         }
1467         seek $fh, $offset, 0 or croak $!;
1468         print $fh $commit,"\n" or croak $!;
1469         close $fh or croak $!;
1470         if ($update_ref) {
1471                 command_noisy('update-ref', '-m', "r$rev",
1472                               $self->refname, $commit);
1473         }
1474         rename $db_lock, $db or die "rev_db_set(@_): ", "Failed to rename: ",
1475                                     "$db_lock => $db ($!)\n";
1476         delete $LOCKFILES{$db_lock};
1477         if ($update_ref) {
1478                 $SIG{INT} = $SIG{HUP} = $SIG{TERM} = $SIG{ALRM} = $SIG{PIPE} =
1479                             $SIG{USR1} = $SIG{USR2} = 'DEFAULT';
1480                 kill $sig, $$ if defined $sig;
1481         }
1484 sub rev_db_max {
1485         my ($self) = @_;
1486         my @stat = stat $self->{db_path} or
1487                         die "Couldn't stat $self->{db_path}: $!\n";
1488         ($stat[7] % 41) == 0 or
1489                         die "$self->{db_path} inconsistent size:$stat[7]\n";
1490         my $max = $stat[7] / 41;
1491         (($max > 0) ? $max - 1 : 0);
1494 sub rev_db_get {
1495         my ($self, $rev) = @_;
1496         my $ret;
1497         my $offset = $rev * 41;
1498         open my $fh, '<', $self->{db_path} or croak $!;
1499         if (sysseek($fh, $offset, 0) == $offset) {
1500                 my $read = sysread($fh, $ret, 40);
1501                 $ret = undef if ($read != 40 || $ret eq ('0'x40));
1502         }
1503         close $fh or croak $!;
1504         $ret;
1507 sub find_rev_before {
1508         my ($self, $rev, $eq_ok) = @_;
1509         --$rev unless $eq_ok;
1510         while ($rev > 0) {
1511                 if (my $c = $self->rev_db_get($rev)) {
1512                         return ($rev, $c);
1513                 }
1514                 --$rev;
1515         }
1516         return (undef, undef);
1519 sub _new {
1520         my ($class, $repo_id, $ref_id, $path) = @_;
1521         unless (defined $repo_id && length $repo_id) {
1522                 $repo_id = $Git::SVN::default_repo_id;
1523         }
1524         unless (defined $ref_id && length $ref_id) {
1525                 $_[2] = $ref_id = $Git::SVN::default_ref_id;
1526         }
1527         $_[1] = $repo_id = sanitize_remote_name($repo_id);
1528         my $dir = "$ENV{GIT_DIR}/svn/$ref_id";
1529         $_[3] = $path = '' unless (defined $path);
1530         mkpath([$dir]);
1531         unless (-f "$dir/.rev_db") {
1532                 open my $fh, '>>', "$dir/.rev_db" or croak $!;
1533                 close $fh or croak $!;
1534         }
1535         bless { ref_id => $ref_id, dir => $dir, index => "$dir/index",
1536                 path => $path,
1537                 db_path => "$dir/.rev_db", repo_id => $repo_id }, $class;
1540 sub uri_encode {
1541         my ($f) = @_;
1542         $f =~ s#([^a-zA-Z0-9\*!\:_\./\-])#uc sprintf("%%%02x",ord($1))#eg;
1543         $f
1546 package Git::SVN::Prompt;
1547 use strict;
1548 use warnings;
1549 require SVN::Core;
1550 use vars qw/$_no_auth_cache $_username/;
1552 sub simple {
1553         my ($cred, $realm, $default_username, $may_save, $pool) = @_;
1554         $may_save = undef if $_no_auth_cache;
1555         $default_username = $_username if defined $_username;
1556         if (defined $default_username && length $default_username) {
1557                 if (defined $realm && length $realm) {
1558                         print STDERR "Authentication realm: $realm\n";
1559                         STDERR->flush;
1560                 }
1561                 $cred->username($default_username);
1562         } else {
1563                 username($cred, $realm, $may_save, $pool);
1564         }
1565         $cred->password(_read_password("Password for '" .
1566                                        $cred->username . "': ", $realm));
1567         $cred->may_save($may_save);
1568         $SVN::_Core::SVN_NO_ERROR;
1571 sub ssl_server_trust {
1572         my ($cred, $realm, $failures, $cert_info, $may_save, $pool) = @_;
1573         $may_save = undef if $_no_auth_cache;
1574         print STDERR "Error validating server certificate for '$realm':\n";
1575         if ($failures & $SVN::Auth::SSL::UNKNOWNCA) {
1576                 print STDERR " - The certificate is not issued by a trusted ",
1577                       "authority. Use the\n",
1578                       "   fingerprint to validate the certificate manually!\n";
1579         }
1580         if ($failures & $SVN::Auth::SSL::CNMISMATCH) {
1581                 print STDERR " - The certificate hostname does not match.\n";
1582         }
1583         if ($failures & $SVN::Auth::SSL::NOTYETVALID) {
1584                 print STDERR " - The certificate is not yet valid.\n";
1585         }
1586         if ($failures & $SVN::Auth::SSL::EXPIRED) {
1587                 print STDERR " - The certificate has expired.\n";
1588         }
1589         if ($failures & $SVN::Auth::SSL::OTHER) {
1590                 print STDERR " - The certificate has an unknown error.\n";
1591         }
1592         printf STDERR
1593                 "Certificate information:\n".
1594                 " - Hostname: %s\n".
1595                 " - Valid: from %s until %s\n".
1596                 " - Issuer: %s\n".
1597                 " - Fingerprint: %s\n",
1598                 map $cert_info->$_, qw(hostname valid_from valid_until
1599                                        issuer_dname fingerprint);
1600         my $choice;
1601 prompt:
1602         print STDERR $may_save ?
1603               "(R)eject, accept (t)emporarily or accept (p)ermanently? " :
1604               "(R)eject or accept (t)emporarily? ";
1605         STDERR->flush;
1606         $choice = lc(substr(<STDIN> || 'R', 0, 1));
1607         if ($choice =~ /^t$/i) {
1608                 $cred->may_save(undef);
1609         } elsif ($choice =~ /^r$/i) {
1610                 return -1;
1611         } elsif ($may_save && $choice =~ /^p$/i) {
1612                 $cred->may_save($may_save);
1613         } else {
1614                 goto prompt;
1615         }
1616         $cred->accepted_failures($failures);
1617         $SVN::_Core::SVN_NO_ERROR;
1620 sub ssl_client_cert {
1621         my ($cred, $realm, $may_save, $pool) = @_;
1622         $may_save = undef if $_no_auth_cache;
1623         print STDERR "Client certificate filename: ";
1624         STDERR->flush;
1625         chomp(my $filename = <STDIN>);
1626         $cred->cert_file($filename);
1627         $cred->may_save($may_save);
1628         $SVN::_Core::SVN_NO_ERROR;
1631 sub ssl_client_cert_pw {
1632         my ($cred, $realm, $may_save, $pool) = @_;
1633         $may_save = undef if $_no_auth_cache;
1634         $cred->password(_read_password("Password: ", $realm));
1635         $cred->may_save($may_save);
1636         $SVN::_Core::SVN_NO_ERROR;
1639 sub username {
1640         my ($cred, $realm, $may_save, $pool) = @_;
1641         $may_save = undef if $_no_auth_cache;
1642         if (defined $realm && length $realm) {
1643                 print STDERR "Authentication realm: $realm\n";
1644         }
1645         my $username;
1646         if (defined $_username) {
1647                 $username = $_username;
1648         } else {
1649                 print STDERR "Username: ";
1650                 STDERR->flush;
1651                 chomp($username = <STDIN>);
1652         }
1653         $cred->username($username);
1654         $cred->may_save($may_save);
1655         $SVN::_Core::SVN_NO_ERROR;
1658 sub _read_password {
1659         my ($prompt, $realm) = @_;
1660         print STDERR $prompt;
1661         STDERR->flush;
1662         require Term::ReadKey;
1663         Term::ReadKey::ReadMode('noecho');
1664         my $password = '';
1665         while (defined(my $key = Term::ReadKey::ReadKey(0))) {
1666                 last if $key =~ /[\012\015]/; # \n\r
1667                 $password .= $key;
1668         }
1669         Term::ReadKey::ReadMode('restore');
1670         print STDERR "\n";
1671         STDERR->flush;
1672         $password;
1675 package main;
1678         my $kill_stupid_warnings = $SVN::Node::none.$SVN::Node::file.
1679                                 $SVN::Node::dir.$SVN::Node::unknown.
1680                                 $SVN::Node::none.$SVN::Node::file.
1681                                 $SVN::Node::dir.$SVN::Node::unknown.
1682                                 $SVN::Auth::SSL::CNMISMATCH.
1683                                 $SVN::Auth::SSL::NOTYETVALID.
1684                                 $SVN::Auth::SSL::EXPIRED.
1685                                 $SVN::Auth::SSL::UNKNOWNCA.
1686                                 $SVN::Auth::SSL::OTHER;
1689 package SVN::Git::Fetcher;
1690 use vars qw/@ISA/;
1691 use strict;
1692 use warnings;
1693 use Carp qw/croak/;
1694 use IO::File qw//;
1695 use Digest::MD5;
1697 # file baton members: path, mode_a, mode_b, pool, fh, blob, base
1698 sub new {
1699         my ($class, $git_svn) = @_;
1700         my $self = SVN::Delta::Editor->new;
1701         bless $self, $class;
1702         $self->{c} = $git_svn->{last_commit} if exists $git_svn->{last_commit};
1703         $self->{empty} = {};
1704         $self->{dir_prop} = {};
1705         $self->{file_prop} = {};
1706         $self->{absent_dir} = {};
1707         $self->{absent_file} = {};
1708         $self->{gii} = $git_svn->tmp_index_do(sub { Git::IndexInfo->new });
1709         $self;
1712 sub set_path_strip {
1713         my ($self, $path) = @_;
1714         $self->{path_strip} = qr/^\Q$path\E\/?/;
1717 sub open_root {
1718         { path => '' };
1721 sub open_directory {
1722         my ($self, $path, $pb, $rev) = @_;
1723         { path => $path };
1726 sub git_path {
1727         my ($self, $path) = @_;
1728         if ($self->{path_strip}) {
1729                 $path =~ s!$self->{path_strip}!! or
1730                   die "Failed to strip path '$path' ($self->{path_strip})\n";
1731         }
1732         $path;
1735 sub delete_entry {
1736         my ($self, $path, $rev, $pb) = @_;
1738         my $gpath = $self->git_path($path);
1739         return undef if ($gpath eq '');
1741         # remove entire directories.
1742         if (command('ls-tree', $self->{c}, '--', $gpath) =~ /^040000 tree/) {
1743                 my ($ls, $ctx) = command_output_pipe(qw/ls-tree
1744                                                      -r --name-only -z/,
1745                                                      $self->{c}, '--', $gpath);
1746                 local $/ = "\0";
1747                 while (<$ls>) {
1748                         chomp;
1749                         $self->{gii}->remove($_);
1750                         print "\tD\t$_\n" unless $self->{q};
1751                 }
1752                 print "\tD\t$gpath/\n" unless $self->{q};
1753                 command_close_pipe($ls, $ctx);
1754                 $self->{empty}->{$path} = 0
1755         } else {
1756                 $self->{gii}->remove($gpath);
1757                 print "\tD\t$gpath\n" unless $self->{q};
1758         }
1759         undef;
1762 sub open_file {
1763         my ($self, $path, $pb, $rev) = @_;
1764         my $gpath = $self->git_path($path);
1765         my ($mode, $blob) = (command('ls-tree', $self->{c}, '--', $gpath)
1766                              =~ /^(\d{6}) blob ([a-f\d]{40})\t/);
1767         unless (defined $mode && defined $blob) {
1768                 die "$path was not found in commit $self->{c} (r$rev)\n";
1769         }
1770         { path => $path, mode_a => $mode, mode_b => $mode, blob => $blob,
1771           pool => SVN::Pool->new, action => 'M' };
1774 sub add_file {
1775         my ($self, $path, $pb, $cp_path, $cp_rev) = @_;
1776         my ($dir, $file) = ($path =~ m#^(.*?)/?([^/]+)$#);
1777         delete $self->{empty}->{$dir};
1778         { path => $path, mode_a => 100644, mode_b => 100644,
1779           pool => SVN::Pool->new, action => 'A' };
1782 sub add_directory {
1783         my ($self, $path, $cp_path, $cp_rev) = @_;
1784         my ($dir, $file) = ($path =~ m#^(.*?)/?([^/]+)$#);
1785         delete $self->{empty}->{$dir};
1786         $self->{empty}->{$path} = 1;
1787         { path => $path };
1790 sub change_dir_prop {
1791         my ($self, $db, $prop, $value) = @_;
1792         $self->{dir_prop}->{$db->{path}} ||= {};
1793         $self->{dir_prop}->{$db->{path}}->{$prop} = $value;
1794         undef;
1797 sub absent_directory {
1798         my ($self, $path, $pb) = @_;
1799         $self->{absent_dir}->{$pb->{path}} ||= [];
1800         push @{$self->{absent_dir}->{$pb->{path}}}, $path;
1801         undef;
1804 sub absent_file {
1805         my ($self, $path, $pb) = @_;
1806         $self->{absent_file}->{$pb->{path}} ||= [];
1807         push @{$self->{absent_file}->{$pb->{path}}}, $path;
1808         undef;
1811 sub change_file_prop {
1812         my ($self, $fb, $prop, $value) = @_;
1813         if ($prop eq 'svn:executable') {
1814                 if ($fb->{mode_b} != 120000) {
1815                         $fb->{mode_b} = defined $value ? 100755 : 100644;
1816                 }
1817         } elsif ($prop eq 'svn:special') {
1818                 $fb->{mode_b} = defined $value ? 120000 : 100644;
1819         } else {
1820                 $self->{file_prop}->{$fb->{path}} ||= {};
1821                 $self->{file_prop}->{$fb->{path}}->{$prop} = $value;
1822         }
1823         undef;
1826 sub apply_textdelta {
1827         my ($self, $fb, $exp) = @_;
1828         my $fh = IO::File->new_tmpfile;
1829         $fh->autoflush(1);
1830         # $fh gets auto-closed() by SVN::TxDelta::apply(),
1831         # (but $base does not,) so dup() it for reading in close_file
1832         open my $dup, '<&', $fh or croak $!;
1833         my $base = IO::File->new_tmpfile;
1834         $base->autoflush(1);
1835         if ($fb->{blob}) {
1836                 defined (my $pid = fork) or croak $!;
1837                 if (!$pid) {
1838                         open STDOUT, '>&', $base or croak $!;
1839                         print STDOUT 'link ' if ($fb->{mode_a} == 120000);
1840                         exec qw/git-cat-file blob/, $fb->{blob} or croak $!;
1841                 }
1842                 waitpid $pid, 0;
1843                 croak $? if $?;
1845                 if (defined $exp) {
1846                         seek $base, 0, 0 or croak $!;
1847                         my $md5 = Digest::MD5->new;
1848                         $md5->addfile($base);
1849                         my $got = $md5->hexdigest;
1850                         die "Checksum mismatch: $fb->{path} $fb->{blob}\n",
1851                             "expected: $exp\n",
1852                             "     got: $got\n" if ($got ne $exp);
1853                 }
1854         }
1855         seek $base, 0, 0 or croak $!;
1856         $fb->{fh} = $dup;
1857         $fb->{base} = $base;
1858         [ SVN::TxDelta::apply($base, $fh, undef, $fb->{path}, $fb->{pool}) ];
1861 sub close_file {
1862         my ($self, $fb, $exp) = @_;
1863         my $hash;
1864         my $path = $self->git_path($fb->{path});
1865         if (my $fh = $fb->{fh}) {
1866                 seek($fh, 0, 0) or croak $!;
1867                 my $md5 = Digest::MD5->new;
1868                 $md5->addfile($fh);
1869                 my $got = $md5->hexdigest;
1870                 die "Checksum mismatch: $path\n",
1871                     "expected: $exp\n    got: $got\n" if ($got ne $exp);
1872                 seek($fh, 0, 0) or croak $!;
1873                 if ($fb->{mode_b} == 120000) {
1874                         read($fh, my $buf, 5) == 5 or croak $!;
1875                         $buf eq 'link ' or die "$path has mode 120000",
1876                                                "but is not a link\n";
1877                 }
1878                 defined(my $pid = open my $out,'-|') or die "Can't fork: $!\n";
1879                 if (!$pid) {
1880                         open STDIN, '<&', $fh or croak $!;
1881                         exec qw/git-hash-object -w --stdin/ or croak $!;
1882                 }
1883                 chomp($hash = do { local $/; <$out> });
1884                 close $out or croak $!;
1885                 close $fh or croak $!;
1886                 $hash =~ /^[a-f\d]{40}$/ or die "not a sha1: $hash\n";
1887                 close $fb->{base} or croak $!;
1888         } else {
1889                 $hash = $fb->{blob} or die "no blob information\n";
1890         }
1891         $fb->{pool}->clear;
1892         $self->{gii}->update($fb->{mode_b}, $hash, $path) or croak $!;
1893         print "\t$fb->{action}\t$path\n" if $fb->{action} && ! $self->{q};
1894         undef;
1897 sub abort_edit {
1898         my $self = shift;
1899         $self->{nr} = $self->{gii}->{nr};
1900         delete $self->{gii};
1901         $self->SUPER::abort_edit(@_);
1904 sub close_edit {
1905         my $self = shift;
1906         $self->{git_commit_ok} = 1;
1907         $self->{nr} = $self->{gii}->{nr};
1908         delete $self->{gii};
1909         $self->SUPER::close_edit(@_);
1912 package SVN::Git::Editor;
1913 use vars qw/@ISA $_rmdir $_cp_similarity $_find_copies_harder $_rename_limit/;
1914 use strict;
1915 use warnings;
1916 use Carp qw/croak/;
1917 use IO::File;
1918 use Digest::MD5;
1920 sub new {
1921         my ($class, $opts) = @_;
1922         foreach (qw/svn_path r ra tree_a tree_b log editor_cb/) {
1923                 die "$_ required!\n" unless (defined $opts->{$_});
1924         }
1926         my $pool = SVN::Pool->new;
1927         my $mods = generate_diff($opts->{tree_a}, $opts->{tree_b});
1928         my $types = check_diff_paths($opts->{ra}, $opts->{svn_path},
1929                                      $opts->{r}, $mods);
1931         # $opts->{ra} functions should not be used after this:
1932         my @ce  = $opts->{ra}->get_commit_editor($opts->{log},
1933                                                 $opts->{editor_cb}, $pool);
1934         my $self = SVN::Delta::Editor->new(@ce, $pool);
1935         bless $self, $class;
1936         foreach (qw/svn_path r tree_a tree_b/) {
1937                 $self->{$_} = $opts->{$_};
1938         }
1939         $self->{url} = $opts->{ra}->{url};
1940         $self->{mods} = $mods;
1941         $self->{types} = $types;
1942         $self->{pool} = $pool;
1943         $self->{bat} = { '' => $self->open_root($self->{r}, $self->{pool}) };
1944         $self->{rm} = { };
1945         $self->{path_prefix} = length $self->{svn_path} ?
1946                                "$self->{svn_path}/" : '';
1947         return $self;
1950 sub generate_diff {
1951         my ($tree_a, $tree_b) = @_;
1952         my @diff_tree = qw(diff-tree -z -r);
1953         if ($_cp_similarity) {
1954                 push @diff_tree, "-C$_cp_similarity";
1955         } else {
1956                 push @diff_tree, '-C';
1957         }
1958         push @diff_tree, '--find-copies-harder' if $_find_copies_harder;
1959         push @diff_tree, "-l$_rename_limit" if defined $_rename_limit;
1960         push @diff_tree, $tree_a, $tree_b;
1961         my ($diff_fh, $ctx) = command_output_pipe(@diff_tree);
1962         local $/ = "\0";
1963         my $state = 'meta';
1964         my @mods;
1965         while (<$diff_fh>) {
1966                 chomp $_; # this gets rid of the trailing "\0"
1967                 if ($state eq 'meta' && /^:(\d{6})\s(\d{6})\s
1968                                         $::sha1\s($::sha1)\s
1969                                         ([MTCRAD])\d*$/xo) {
1970                         push @mods, {   mode_a => $1, mode_b => $2,
1971                                         sha1_b => $3, chg => $4 };
1972                         if ($4 =~ /^(?:C|R)$/) {
1973                                 $state = 'file_a';
1974                         } else {
1975                                 $state = 'file_b';
1976                         }
1977                 } elsif ($state eq 'file_a') {
1978                         my $x = $mods[$#mods] or croak "Empty array\n";
1979                         if ($x->{chg} !~ /^(?:C|R)$/) {
1980                                 croak "Error parsing $_, $x->{chg}\n";
1981                         }
1982                         $x->{file_a} = $_;
1983                         $state = 'file_b';
1984                 } elsif ($state eq 'file_b') {
1985                         my $x = $mods[$#mods] or croak "Empty array\n";
1986                         if (exists $x->{file_a} && $x->{chg} !~ /^(?:C|R)$/) {
1987                                 croak "Error parsing $_, $x->{chg}\n";
1988                         }
1989                         if (!exists $x->{file_a} && $x->{chg} =~ /^(?:C|R)$/) {
1990                                 croak "Error parsing $_, $x->{chg}\n";
1991                         }
1992                         $x->{file_b} = $_;
1993                         $state = 'meta';
1994                 } else {
1995                         croak "Error parsing $_\n";
1996                 }
1997         }
1998         command_close_pipe($diff_fh, $ctx);
1999         \@mods;
2002 sub check_diff_paths {
2003         my ($ra, $pfx, $rev, $mods) = @_;
2004         my %types;
2005         $pfx .= '/' if length $pfx;
2007         sub type_diff_paths {
2008                 my ($ra, $types, $path, $rev) = @_;
2009                 my @p = split m#/+#, $path;
2010                 my $c = shift @p;
2011                 unless (defined $types->{$c}) {
2012                         $types->{$c} = $ra->check_path($c, $rev);
2013                 }
2014                 while (@p) {
2015                         $c .= '/' . shift @p;
2016                         next if defined $types->{$c};
2017                         $types->{$c} = $ra->check_path($c, $rev);
2018                 }
2019         }
2021         foreach my $m (@$mods) {
2022                 foreach my $f (qw/file_a file_b/) {
2023                         next unless defined $m->{$f};
2024                         my ($dir) = ($m->{$f} =~ m#^(.*?)/?(?:[^/]+)$#);
2025                         if (length $pfx.$dir && ! defined $types{$dir}) {
2026                                 type_diff_paths($ra, \%types, $pfx.$dir, $rev);
2027                         }
2028                 }
2029         }
2030         \%types;
2033 sub split_path {
2034         return ($_[0] =~ m#^(.*?)/?([^/]+)$#);
2037 sub repo_path {
2038         my ($self, $path) = @_;
2039         $self->{path_prefix}.(defined $path ? $path : '');
2042 sub url_path {
2043         my ($self, $path) = @_;
2044         $self->{url} . '/' . $self->repo_path($path);
2047 sub rmdirs {
2048         my ($self) = @_;
2049         my $rm = $self->{rm};
2050         delete $rm->{''}; # we never delete the url we're tracking
2051         return unless %$rm;
2053         foreach (keys %$rm) {
2054                 my @d = split m#/#, $_;
2055                 my $c = shift @d;
2056                 $rm->{$c} = 1;
2057                 while (@d) {
2058                         $c .= '/' . shift @d;
2059                         $rm->{$c} = 1;
2060                 }
2061         }
2062         delete $rm->{$self->{svn_path}};
2063         delete $rm->{''}; # we never delete the url we're tracking
2064         return unless %$rm;
2066         my ($fh, $ctx) = command_output_pipe(qw/ls-tree --name-only -r -z/,
2067                                              $self->{tree_b});
2068         local $/ = "\0";
2069         while (<$fh>) {
2070                 chomp;
2071                 my @dn = split m#/#, $_;
2072                 while (pop @dn) {
2073                         delete $rm->{join '/', @dn};
2074                 }
2075                 unless (%$rm) {
2076                         close $fh;
2077                         return;
2078                 }
2079         }
2080         command_close_pipe($fh, $ctx);
2082         my ($r, $p, $bat) = ($self->{r}, $self->{pool}, $self->{bat});
2083         foreach my $d (sort { $b =~ tr#/#/# <=> $a =~ tr#/#/# } keys %$rm) {
2084                 $self->close_directory($bat->{$d}, $p);
2085                 my ($dn) = ($d =~ m#^(.*?)/?(?:[^/]+)$#);
2086                 print "\tD+\t$d/\n" unless $::_q;
2087                 $self->SUPER::delete_entry($d, $r, $bat->{$dn}, $p);
2088                 delete $bat->{$d};
2089         }
2092 sub open_or_add_dir {
2093         my ($self, $full_path, $baton) = @_;
2094         my $t = $self->{types}->{$full_path};
2095         if (!defined $t) {
2096                 die "$full_path not known in r$self->{r} or we have a bug!\n";
2097         }
2098         if ($t == $SVN::Node::none) {
2099                 return $self->add_directory($full_path, $baton,
2100                                                 undef, -1, $self->{pool});
2101         } elsif ($t == $SVN::Node::dir) {
2102                 return $self->open_directory($full_path, $baton,
2103                                                 $self->{r}, $self->{pool});
2104         }
2105         print STDERR "$full_path already exists in repository at ",
2106                 "r$self->{r} and it is not a directory (",
2107                 ($t == $SVN::Node::file ? 'file' : 'unknown'),"/$t)\n";
2108         exit 1;
2111 sub ensure_path {
2112         my ($self, $path) = @_;
2113         my $bat = $self->{bat};
2114         my $repo_path = $self->repo_path($path);
2115         return $bat->{''} unless (length $repo_path);
2116         my @p = split m#/+#, $repo_path;
2117         my $c = shift @p;
2118         $bat->{$c} ||= $self->open_or_add_dir($c, $bat->{''});
2119         while (@p) {
2120                 my $c0 = $c;
2121                 $c .= '/' . shift @p;
2122                 $bat->{$c} ||= $self->open_or_add_dir($c, $bat->{$c0});
2123         }
2124         return $bat->{$c};
2127 sub A {
2128         my ($self, $m) = @_;
2129         my ($dir, $file) = split_path($m->{file_b});
2130         my $pbat = $self->ensure_path($dir);
2131         my $fbat = $self->add_file($self->repo_path($m->{file_b}), $pbat,
2132                                         undef, -1);
2133         print "\tA\t$m->{file_b}\n" unless $::_q;
2134         $self->chg_file($fbat, $m);
2135         $self->close_file($fbat,undef,$self->{pool});
2138 sub C {
2139         my ($self, $m) = @_;
2140         my ($dir, $file) = split_path($m->{file_b});
2141         my $pbat = $self->ensure_path($dir);
2142         my $fbat = $self->add_file($self->repo_path($m->{file_b}), $pbat,
2143                                 $self->url_path($m->{file_a}), $self->{r});
2144         print "\tC\t$m->{file_a} => $m->{file_b}\n" unless $::_q;
2145         $self->chg_file($fbat, $m);
2146         $self->close_file($fbat,undef,$self->{pool});
2149 sub delete_entry {
2150         my ($self, $path, $pbat) = @_;
2151         my $rpath = $self->repo_path($path);
2152         my ($dir, $file) = split_path($rpath);
2153         $self->{rm}->{$dir} = 1;
2154         $self->SUPER::delete_entry($rpath, $self->{r}, $pbat, $self->{pool});
2157 sub R {
2158         my ($self, $m) = @_;
2159         my ($dir, $file) = split_path($m->{file_b});
2160         my $pbat = $self->ensure_path($dir);
2161         my $fbat = $self->add_file($self->repo_path($m->{file_b}), $pbat,
2162                                 $self->url_path($m->{file_a}), $self->{r});
2163         print "\tR\t$m->{file_a} => $m->{file_b}\n" unless $::_q;
2164         $self->chg_file($fbat, $m);
2165         $self->close_file($fbat,undef,$self->{pool});
2167         ($dir, $file) = split_path($m->{file_a});
2168         $pbat = $self->ensure_path($dir);
2169         $self->delete_entry($m->{file_a}, $pbat);
2172 sub M {
2173         my ($self, $m) = @_;
2174         my ($dir, $file) = split_path($m->{file_b});
2175         my $pbat = $self->ensure_path($dir);
2176         my $fbat = $self->open_file($self->repo_path($m->{file_b}),
2177                                 $pbat,$self->{r},$self->{pool});
2178         print "\t$m->{chg}\t$m->{file_b}\n" unless $::_q;
2179         $self->chg_file($fbat, $m);
2180         $self->close_file($fbat,undef,$self->{pool});
2183 sub T { shift->M(@_) }
2185 sub change_file_prop {
2186         my ($self, $fbat, $pname, $pval) = @_;
2187         $self->SUPER::change_file_prop($fbat, $pname, $pval, $self->{pool});
2190 sub chg_file {
2191         my ($self, $fbat, $m) = @_;
2192         if ($m->{mode_b} =~ /755$/ && $m->{mode_a} !~ /755$/) {
2193                 $self->change_file_prop($fbat,'svn:executable','*');
2194         } elsif ($m->{mode_b} !~ /755$/ && $m->{mode_a} =~ /755$/) {
2195                 $self->change_file_prop($fbat,'svn:executable',undef);
2196         }
2197         my $fh = IO::File->new_tmpfile or croak $!;
2198         if ($m->{mode_b} =~ /^120/) {
2199                 print $fh 'link ' or croak $!;
2200                 $self->change_file_prop($fbat,'svn:special','*');
2201         } elsif ($m->{mode_a} =~ /^120/ && $m->{mode_b} !~ /^120/) {
2202                 $self->change_file_prop($fbat,'svn:special',undef);
2203         }
2204         defined(my $pid = fork) or croak $!;
2205         if (!$pid) {
2206                 open STDOUT, '>&', $fh or croak $!;
2207                 exec qw/git-cat-file blob/, $m->{sha1_b} or croak $!;
2208         }
2209         waitpid $pid, 0;
2210         croak $? if $?;
2211         $fh->flush == 0 or croak $!;
2212         seek $fh, 0, 0 or croak $!;
2214         my $md5 = Digest::MD5->new;
2215         $md5->addfile($fh) or croak $!;
2216         seek $fh, 0, 0 or croak $!;
2218         my $exp = $md5->hexdigest;
2219         my $pool = SVN::Pool->new;
2220         my $atd = $self->apply_textdelta($fbat, undef, $pool);
2221         my $got = SVN::TxDelta::send_stream($fh, @$atd, $pool);
2222         die "Checksum mismatch\nexpected: $exp\ngot: $got\n" if ($got ne $exp);
2223         $pool->clear;
2225         close $fh or croak $!;
2228 sub D {
2229         my ($self, $m) = @_;
2230         my ($dir, $file) = split_path($m->{file_b});
2231         my $pbat = $self->ensure_path($dir);
2232         print "\tD\t$m->{file_b}\n" unless $::_q;
2233         $self->delete_entry($m->{file_b}, $pbat);
2236 sub close_edit {
2237         my ($self) = @_;
2238         my ($p,$bat) = ($self->{pool}, $self->{bat});
2239         foreach (sort { $b =~ tr#/#/# <=> $a =~ tr#/#/# } keys %$bat) {
2240                 $self->close_directory($bat->{$_}, $p);
2241         }
2242         $self->SUPER::close_edit($p);
2243         $p->clear;
2246 sub abort_edit {
2247         my ($self) = @_;
2248         $self->SUPER::abort_edit($self->{pool});
2251 sub DESTROY {
2252         my $self = shift;
2253         $self->SUPER::DESTROY(@_);
2254         $self->{pool}->clear;
2257 # this drives the editor
2258 sub apply_diff {
2259         my ($self) = @_;
2260         my $mods = $self->{mods};
2261         my %o = ( D => 1, R => 0, C => -1, A => 3, M => 3, T => 3 );
2262         foreach my $m (sort { $o{$a->{chg}} <=> $o{$b->{chg}} } @$mods) {
2263                 my $f = $m->{chg};
2264                 if (defined $o{$f}) {
2265                         $self->$f($m);
2266                 } else {
2267                         fatal("Invalid change type: $f\n");
2268                 }
2269         }
2270         $self->rmdirs if $_rmdir;
2271         if (@$mods == 0) {
2272                 $self->abort_edit;
2273         } else {
2274                 $self->close_edit;
2275         }
2276         return scalar @$mods;
2279 package Git::SVN::Ra;
2280 use vars qw/@ISA $config_dir/;
2281 use strict;
2282 use warnings;
2283 my ($can_do_switch);
2284 my $RA;
2286 BEGIN {
2287         # enforce temporary pool usage for some simple functions
2288         my $e;
2289         foreach (qw/get_latest_revnum rev_proplist get_file
2290                     check_path get_dir get_uuid get_repos_root/) {
2291                 $e .= "sub $_ {
2292                         my \$self = shift;
2293                         my \$pool = SVN::Pool->new;
2294                         my \@ret = \$self->SUPER::$_(\@_,\$pool);
2295                         \$pool->clear;
2296                         wantarray ? \@ret : \$ret[0]; }\n";
2297         }
2298         eval $e;
2301 sub new {
2302         my ($class, $url) = @_;
2303         $url =~ s!/+$!!;
2304         return $RA if ($RA && $RA->{url} eq $url);
2306         SVN::_Core::svn_config_ensure($config_dir, undef);
2307         my ($baton, $callbacks) = SVN::Core::auth_open_helper([
2308             SVN::Client::get_simple_provider(),
2309             SVN::Client::get_ssl_server_trust_file_provider(),
2310             SVN::Client::get_simple_prompt_provider(
2311               \&Git::SVN::Prompt::simple, 2),
2312             SVN::Client::get_ssl_client_cert_prompt_provider(
2313               \&Git::SVN::Prompt::ssl_client_cert, 2),
2314             SVN::Client::get_ssl_client_cert_pw_prompt_provider(
2315               \&Git::SVN::Prompt::ssl_client_cert_pw, 2),
2316             SVN::Client::get_username_provider(),
2317             SVN::Client::get_ssl_server_trust_prompt_provider(
2318               \&Git::SVN::Prompt::ssl_server_trust),
2319             SVN::Client::get_username_prompt_provider(
2320               \&Git::SVN::Prompt::username, 2),
2321           ]);
2322         my $config = SVN::Core::config_get_config($config_dir);
2323         my $self = SVN::Ra->new(url => $url, auth => $baton,
2324                               config => $config,
2325                               pool => SVN::Pool->new,
2326                               auth_provider_callbacks => $callbacks);
2327         $self->{svn_path} = $url;
2328         $self->{repos_root} = $self->get_repos_root;
2329         $self->{svn_path} =~ s#^\Q$self->{repos_root}\E/*##;
2330         $RA = bless $self, $class;
2333 sub DESTROY {
2334         # do not call the real DESTROY since we store ourselves in $RA
2337 sub get_log {
2338         my ($self, @args) = @_;
2339         my $pool = SVN::Pool->new;
2340         splice(@args, 3, 1) if ($SVN::Core::VERSION le '1.2.0');
2341         my $ret = $self->SUPER::get_log(@args, $pool);
2342         $pool->clear;
2343         $ret;
2346 sub get_commit_editor {
2347         my ($self, $log, $cb, $pool) = @_;
2348         my @lock = $SVN::Core::VERSION ge '1.2.0' ? (undef, 0) : ();
2349         $self->SUPER::get_commit_editor($log, $cb, @lock, $pool);
2352 sub uuid {
2353         my ($self) = @_;
2354         $self->{uuid} ||= $self->get_uuid;
2357 sub gs_do_update {
2358         my ($self, $rev_a, $rev_b, $gs, $editor) = @_;
2359         my $new = ($rev_a == $rev_b);
2360         my $path = $gs->{path};
2362         my $ta = $self->check_path($path, $rev_a);
2363         my $tb = $new ? $ta : $self->check_path($path, $rev_b);
2364         return 1 if ($tb != $SVN::Node::dir && $ta != $SVN::Node::dir);
2365         if ($ta == $SVN::Node::none) {
2366                 $rev_a = $rev_b;
2367                 $new = 1;
2368         }
2370         my $pool = SVN::Pool->new;
2371         $editor->set_path_strip($path);
2372         my (@pc) = split m#/#, $path;
2373         my $reporter = $self->do_update($rev_b, (@pc ? shift @pc : ''),
2374                                         1, $editor, $pool);
2375         my @lock = $SVN::Core::VERSION ge '1.2.0' ? (undef) : ();
2377         # Since we can't rely on svn_ra_reparent being available, we'll
2378         # just have to do some magic with set_path to make it so
2379         # we only want a partial path.
2380         my $sp = '';
2381         my $final = join('/', @pc);
2382         while (@pc) {
2383                 $reporter->set_path($sp, $rev_b, 0, @lock, $pool);
2384                 $sp .= '/' if length $sp;
2385                 $sp .= shift @pc;
2386         }
2387         die "BUG: '$sp' != '$final'\n" if ($sp ne $final);
2389         $reporter->set_path($sp, $rev_a, $new, @lock, $pool);
2391         $reporter->finish_report($pool);
2392         $pool->clear;
2393         $editor->{git_commit_ok};
2396 # this requires SVN 1.4.3 or later (do_switch didn't work before 1.4.3, and
2397 # svn_ra_reparent didn't work before 1.4)
2398 sub gs_do_switch {
2399         my ($self, $rev_a, $rev_b, $gs, $url_b, $editor) = @_;
2400         my $path = $gs->{path};
2401         my $pool = SVN::Pool->new;
2403         my $full_url = $self->{url};
2404         my $old_url = $full_url;
2405         $full_url .= "/$path" if length $path;
2406         my ($ra, $reparented);
2407         if ($old_url ne $full_url) {
2408                 if ($old_url !~ m#^svn(\+ssh)?://#) {
2409                         SVN::_Ra::svn_ra_reparent($self->{session}, $full_url,
2410                                                   $pool);
2411                         $self->{url} = $full_url;
2412                         $reparented = 1;
2413                 } else {
2414                         $ra = Git::SVN::Ra->new($full_url);
2415                 }
2416         }
2417         $ra ||= $self;
2418         my $reporter = $ra->do_switch($rev_b, '', 1, $url_b, $editor, $pool);
2419         my @lock = $SVN::Core::VERSION ge '1.2.0' ? (undef) : ();
2420         $reporter->set_path('', $rev_a, 0, @lock, $pool);
2421         $reporter->finish_report($pool);
2423         if ($reparented) {
2424                 SVN::_Ra::svn_ra_reparent($self->{session}, $old_url, $pool);
2425                 $self->{url} = $old_url;
2426         }
2428         $pool->clear;
2429         $editor->{git_commit_ok};
2432 sub gs_fetch_loop_common {
2433         my ($self, $base, $head, @gs) = @_;
2434         my $inc = 1000;
2435         my ($min, $max) = ($base, $head < $base + $inc ? $head : $base + $inc);
2437         my %common;
2438         foreach my $gs (@gs) {
2439                 if (my $last_commit = $gs->last_commit) {
2440                         $gs->assert_index_clean($last_commit);
2441                 }
2442                 my @tmp = split m#/#, $gs->{path};
2443                 my $p = '';
2444                 foreach (@tmp) {
2445                         $p .= length($p) ? "/$_" : $_;
2446                         $common{$p} ||= 0;
2447                         $common{$p}++;
2448                 }
2449         }
2450         my $longest_path = '';
2451         foreach (sort {length $b <=> length $a} keys %common) {
2452                 if ($common{$_} == @gs) {
2453                         $longest_path = $_;
2454                         last;
2455                 }
2456         }
2457         while (1) {
2458                 my %revs;
2459                 my $err;
2460                 my $err_handler = $SVN::Error::handler;
2461                 $SVN::Error::handler = sub {
2462                         ($err) = @_;
2463                         skip_unknown_revs($err);
2464                 };
2465                 sub _cb {
2466                         my ($paths, $r, $author, $date, $log) = @_;
2467                         [ dup_changed_paths($paths),
2468                           { author => $author, date => $date, log => $log } ];
2469                 }
2470                 $self->get_log([$longest_path], $min, $max, 0, 1, 1,
2471                                sub { $revs{$_[1]} = _cb(@_) });
2472                 if ($err && $max >= $head) {
2473                         print STDERR "Path '$longest_path' ",
2474                                      "was probably deleted:\n",
2475                                      $err->expanded_message,
2476                                      "\nWill attempt to follow ",
2477                                      "revisions r$min .. r$max ",
2478                                      "committed before the deletion\n";
2479                         my $hi = $max;
2480                         while (--$hi >= $min) {
2481                                 my $ok;
2482                                 $self->get_log([$longest_path], $min, $hi,
2483                                                0, 1, 1, sub {
2484                                                $ok ||= $_[1];
2485                                                $revs{$_[1]} = _cb(@_) });
2486                                 if ($ok) {
2487                                         print STDERR "r$min .. r$ok OK\n";
2488                                         last;
2489                                 }
2490                         }
2491                 }
2492                 $SVN::Error::handler = $err_handler;
2494                 foreach my $r (sort {$a <=> $b} keys %revs) {
2495                         my ($paths, $logged) = @{$revs{$r}};
2496                         foreach my $gs (@gs) {
2497                                 if ($gs->rev_db_max >= $r) {
2498                                         next;
2499                                 }
2500                                 next unless $gs->match_paths($paths, $r);
2501                                 $gs->{logged_rev_props} = $logged;
2502                                 my $log_entry = $gs->do_fetch($paths, $r);
2503                                 if ($log_entry) {
2504                                         $gs->do_git_commit($log_entry);
2505                                 }
2506                         }
2507                 }
2508                 # pre-fill the .rev_db since it'll eventually get filled in
2509                 # with '0' x40 if something new gets committed
2510                 foreach my $gs (@gs) {
2511                         next if defined $gs->rev_db_get($max);
2512                         $gs->rev_db_set($max, 0 x40);
2513                 }
2514                 last if $max >= $head;
2515                 $min = $max + 1;
2516                 $max += $inc;
2517                 $max = $head if ($max > $head);
2518         }
2521 sub minimize_url {
2522         my ($self) = @_;
2523         return $self->{url} if ($self->{url} eq $self->{repos_root});
2524         my $url = $self->{repos_root};
2525         my @components = split(m!/!, $self->{svn_path});
2526         my $c = '';
2527         do {
2528                 $url .= "/$c" if length $c;
2529                 eval { (ref $self)->new($url)->get_latest_revnum };
2530         } while ($@ && ($c = shift @components));
2531         $url;
2534 sub can_do_switch {
2535         my $self = shift;
2536         unless (defined $can_do_switch) {
2537                 my $pool = SVN::Pool->new;
2538                 my $rep = eval {
2539                         $self->do_switch(1, '', 0, $self->{url},
2540                                          SVN::Delta::Editor->new, $pool);
2541                 };
2542                 if ($@) {
2543                         $can_do_switch = 0;
2544                 } else {
2545                         $rep->abort_report($pool);
2546                         $can_do_switch = 1;
2547                 }
2548                 $pool->clear;
2549         }
2550         $can_do_switch;
2553 sub skip_unknown_revs {
2554         my ($err) = @_;
2555         my $errno = $err->apr_err();
2556         # Maybe the branch we're tracking didn't
2557         # exist when the repo started, so it's
2558         # not an error if it doesn't, just continue
2559         #
2560         # Wonderfully consistent library, eh?
2561         # 160013 - svn:// and file://
2562         # 175002 - http(s)://
2563         # 175007 - http(s):// (this repo required authorization, too...)
2564         #   More codes may be discovered later...
2565         if ($errno == 175007 || $errno == 175002 || $errno == 160013) {
2566                 return;
2567         }
2568         die "Error from SVN, ($errno): ", $err->expanded_message,"\n";
2571 # svn_log_changed_path_t objects passed to get_log are likely to be
2572 # overwritten even if only the refs are copied to an external variable,
2573 # so we should dup the structures in their entirety.  Using an externally
2574 # passed pool (instead of our temporary and quickly cleared pool in
2575 # Git::SVN::Ra) does not help matters at all...
2576 sub dup_changed_paths {
2577         my ($paths) = @_;
2578         return undef unless $paths;
2579         my %ret;
2580         foreach my $p (keys %$paths) {
2581                 my $i = $paths->{$p};
2582                 my %s = map { $_ => $i->$_ }
2583                               qw/copyfrom_path copyfrom_rev action/;
2584                 $ret{$p} = \%s;
2585         }
2586         \%ret;
2589 package Git::SVN::Log;
2590 use strict;
2591 use warnings;
2592 use POSIX qw/strftime/;
2593 use vars qw/$TZ $limit $color $pager $non_recursive $verbose $oneline
2594             %rusers $show_commit $incremental/;
2595 my $l_fmt;
2597 sub cmt_showable {
2598         my ($c) = @_;
2599         return 1 if defined $c->{r};
2600         if ($c->{l} && $c->{l}->[-1] eq "...\n" &&
2601                                 $c->{a_raw} =~ /\@([a-f\d\-]+)>$/) {
2602                 my @log = command(qw/cat-file commit/, $c->{c});
2603                 shift @log while ($log[0] ne "\n");
2604                 shift @log;
2605                 @{$c->{l}} = grep !/^git-svn-id: /, @log;
2607                 (undef, $c->{r}, undef) = ::extract_metadata(
2608                                 (grep(/^git-svn-id: /, @log))[-1]);
2609         }
2610         return defined $c->{r};
2613 sub log_use_color {
2614         return 1 if $color;
2615         my ($dc, $dcvar);
2616         $dcvar = 'color.diff';
2617         $dc = `git-config --get $dcvar`;
2618         if ($dc eq '') {
2619                 # nothing at all; fallback to "diff.color"
2620                 $dcvar = 'diff.color';
2621                 $dc = `git-config --get $dcvar`;
2622         }
2623         chomp($dc);
2624         if ($dc eq 'auto') {
2625                 my $pc;
2626                 $pc = `git-config --get color.pager`;
2627                 if ($pc eq '') {
2628                         # does not have it -- fallback to pager.color
2629                         $pc = `git-config --bool --get pager.color`;
2630                 }
2631                 else {
2632                         $pc = `git-config --bool --get color.pager`;
2633                         if ($?) {
2634                                 $pc = 'false';
2635                         }
2636                 }
2637                 chomp($pc);
2638                 if (-t *STDOUT || (defined $pager && $pc eq 'true')) {
2639                         return ($ENV{TERM} && $ENV{TERM} ne 'dumb');
2640                 }
2641                 return 0;
2642         }
2643         return 0 if $dc eq 'never';
2644         return 1 if $dc eq 'always';
2645         chomp($dc = `git-config --bool --get $dcvar`);
2646         return ($dc eq 'true');
2649 sub git_svn_log_cmd {
2650         my ($r_min, $r_max) = @_;
2651         my $gs = Git::SVN->_new;
2652         my @cmd = (qw/log --abbrev-commit --pretty=raw --default/,
2653                    $gs->refname);
2654         push @cmd, '-r' unless $non_recursive;
2655         push @cmd, qw/--raw --name-status/ if $verbose;
2656         push @cmd, '--color' if log_use_color();
2657         return @cmd unless defined $r_max;
2658         if ($r_max == $r_min) {
2659                 push @cmd, '--max-count=1';
2660                 if (my $c = $gs->rev_db_get($r_max)) {
2661                         push @cmd, $c;
2662                 }
2663         } else {
2664                 my ($c_min, $c_max);
2665                 $c_max = $gs->rev_db_get($r_max);
2666                 $c_min = $gs->rev_db_get($r_min);
2667                 if (defined $c_min && defined $c_max) {
2668                         if ($r_max > $r_max) {
2669                                 push @cmd, "$c_min..$c_max";
2670                         } else {
2671                                 push @cmd, "$c_max..$c_min";
2672                         }
2673                 } elsif ($r_max > $r_min) {
2674                         push @cmd, $c_max;
2675                 } else {
2676                         push @cmd, $c_min;
2677                 }
2678         }
2679         return @cmd;
2682 # adapted from pager.c
2683 sub config_pager {
2684         $pager ||= $ENV{GIT_PAGER} || $ENV{PAGER};
2685         if (!defined $pager) {
2686                 $pager = 'less';
2687         } elsif (length $pager == 0 || $pager eq 'cat') {
2688                 $pager = undef;
2689         }
2692 sub run_pager {
2693         return unless -t *STDOUT;
2694         pipe my $rfd, my $wfd or return;
2695         defined(my $pid = fork) or ::fatal "Can't fork: $!\n";
2696         if (!$pid) {
2697                 open STDOUT, '>&', $wfd or
2698                                      ::fatal "Can't redirect to stdout: $!\n";
2699                 return;
2700         }
2701         open STDIN, '<&', $rfd or ::fatal "Can't redirect stdin: $!\n";
2702         $ENV{LESS} ||= 'FRSX';
2703         exec $pager or ::fatal "Can't run pager: $! ($pager)\n";
2706 sub tz_to_s_offset {
2707         my ($tz) = @_;
2708         $tz =~ s/(\d\d)$//;
2709         return ($1 * 60) + ($tz * 3600);
2712 sub get_author_info {
2713         my ($dest, $author, $t, $tz) = @_;
2714         $author =~ s/(?:^\s*|\s*$)//g;
2715         $dest->{a_raw} = $author;
2716         my $au;
2717         if ($::_authors) {
2718                 $au = $rusers{$author} || undef;
2719         }
2720         if (!$au) {
2721                 ($au) = ($author =~ /<([^>]+)\@[^>]+>$/);
2722         }
2723         $dest->{t} = $t;
2724         $dest->{tz} = $tz;
2725         $dest->{a} = $au;
2726         # Date::Parse isn't in the standard Perl distro :(
2727         if ($tz =~ s/^\+//) {
2728                 $t += tz_to_s_offset($tz);
2729         } elsif ($tz =~ s/^\-//) {
2730                 $t -= tz_to_s_offset($tz);
2731         }
2732         $dest->{t_utc} = $t;
2735 sub process_commit {
2736         my ($c, $r_min, $r_max, $defer) = @_;
2737         if (defined $r_min && defined $r_max) {
2738                 if ($r_min == $c->{r} && $r_min == $r_max) {
2739                         show_commit($c);
2740                         return 0;
2741                 }
2742                 return 1 if $r_min == $r_max;
2743                 if ($r_min < $r_max) {
2744                         # we need to reverse the print order
2745                         return 0 if (defined $limit && --$limit < 0);
2746                         push @$defer, $c;
2747                         return 1;
2748                 }
2749                 if ($r_min != $r_max) {
2750                         return 1 if ($r_min < $c->{r});
2751                         return 1 if ($r_max > $c->{r});
2752                 }
2753         }
2754         return 0 if (defined $limit && --$limit < 0);
2755         show_commit($c);
2756         return 1;
2759 sub show_commit {
2760         my $c = shift;
2761         if ($oneline) {
2762                 my $x = "\n";
2763                 if (my $l = $c->{l}) {
2764                         while ($l->[0] =~ /^\s*$/) { shift @$l }
2765                         $x = $l->[0];
2766                 }
2767                 $l_fmt ||= 'A' . length($c->{r});
2768                 print 'r',pack($l_fmt, $c->{r}),' | ';
2769                 print "$c->{c} | " if $show_commit;
2770                 print $x;
2771         } else {
2772                 show_commit_normal($c);
2773         }
2776 sub show_commit_changed_paths {
2777         my ($c) = @_;
2778         return unless $c->{changed};
2779         print "Changed paths:\n", @{$c->{changed}};
2782 sub show_commit_normal {
2783         my ($c) = @_;
2784         print '-' x72, "\nr$c->{r} | ";
2785         print "$c->{c} | " if $show_commit;
2786         print "$c->{a} | ", strftime("%Y-%m-%d %H:%M:%S %z (%a, %d %b %Y)",
2787                                  localtime($c->{t_utc})), ' | ';
2788         my $nr_line = 0;
2790         if (my $l = $c->{l}) {
2791                 while ($l->[$#$l] eq "\n" && $#$l > 0
2792                                           && $l->[($#$l - 1)] eq "\n") {
2793                         pop @$l;
2794                 }
2795                 $nr_line = scalar @$l;
2796                 if (!$nr_line) {
2797                         print "1 line\n\n\n";
2798                 } else {
2799                         if ($nr_line == 1) {
2800                                 $nr_line = '1 line';
2801                         } else {
2802                                 $nr_line .= ' lines';
2803                         }
2804                         print $nr_line, "\n";
2805                         show_commit_changed_paths($c);
2806                         print "\n";
2807                         print $_ foreach @$l;
2808                 }
2809         } else {
2810                 print "1 line\n";
2811                 show_commit_changed_paths($c);
2812                 print "\n";
2814         }
2815         foreach my $x (qw/raw diff/) {
2816                 if ($c->{$x}) {
2817                         print "\n";
2818                         print $_ foreach @{$c->{$x}}
2819                 }
2820         }
2823 sub cmd_show_log {
2824         my (@args) = @_;
2825         my ($r_min, $r_max);
2826         my $r_last = -1; # prevent dupes
2827         if (defined $TZ) {
2828                 $ENV{TZ} = $TZ;
2829         } else {
2830                 delete $ENV{TZ};
2831         }
2832         if (defined $::_revision) {
2833                 if ($::_revision =~ /^(\d+):(\d+)$/) {
2834                         ($r_min, $r_max) = ($1, $2);
2835                 } elsif ($::_revision =~ /^\d+$/) {
2836                         $r_min = $r_max = $::_revision;
2837                 } else {
2838                         ::fatal "-r$::_revision is not supported, use ",
2839                                 "standard \'git log\' arguments instead\n";
2840                 }
2841         }
2843         config_pager();
2844         @args = (git_svn_log_cmd($r_min, $r_max), @args);
2845         my $log = command_output_pipe(@args);
2846         run_pager();
2847         my (@k, $c, $d);
2848         my $esc_color = qr/(?:\033\[(?:(?:\d+;)*\d*)?m)*/;
2849         while (<$log>) {
2850                 if (/^${esc_color}commit ($::sha1_short)/o) {
2851                         my $cmt = $1;
2852                         if ($c && cmt_showable($c) && $c->{r} != $r_last) {
2853                                 $r_last = $c->{r};
2854                                 process_commit($c, $r_min, $r_max, \@k) or
2855                                                                 goto out;
2856                         }
2857                         $d = undef;
2858                         $c = { c => $cmt };
2859                 } elsif (/^${esc_color}author (.+) (\d+) ([\-\+]?\d+)$/o) {
2860                         get_author_info($c, $1, $2, $3);
2861                 } elsif (/^${esc_color}(?:tree|parent|committer) /o) {
2862                         # ignore
2863                 } elsif (/^${esc_color}:\d{6} \d{6} $::sha1_short/o) {
2864                         push @{$c->{raw}}, $_;
2865                 } elsif (/^${esc_color}[ACRMDT]\t/) {
2866                         # we could add $SVN->{svn_path} here, but that requires
2867                         # remote access at the moment (repo_path_split)...
2868                         s#^(${esc_color})([ACRMDT])\t#$1   $2 #o;
2869                         push @{$c->{changed}}, $_;
2870                 } elsif (/^${esc_color}diff /o) {
2871                         $d = 1;
2872                         push @{$c->{diff}}, $_;
2873                 } elsif ($d) {
2874                         push @{$c->{diff}}, $_;
2875                 } elsif (/^${esc_color}    (git-svn-id:.+)$/o) {
2876                         ($c->{url}, $c->{r}, undef) = ::extract_metadata($1);
2877                 } elsif (s/^${esc_color}    //o) {
2878                         push @{$c->{l}}, $_;
2879                 }
2880         }
2881         if ($c && defined $c->{r} && $c->{r} != $r_last) {
2882                 $r_last = $c->{r};
2883                 process_commit($c, $r_min, $r_max, \@k);
2884         }
2885         if (@k) {
2886                 my $swap = $r_max;
2887                 $r_max = $r_min;
2888                 $r_min = $swap;
2889                 process_commit($_, $r_min, $r_max) foreach reverse @k;
2890         }
2891 out:
2892         close $log;
2893         print '-' x72,"\n" unless $incremental || $oneline;
2896 package Git::SVN::Migration;
2897 # these version numbers do NOT correspond to actual version numbers
2898 # of git nor git-svn.  They are just relative.
2900 # v0 layout: .git/$id/info/url, refs/heads/$id-HEAD
2902 # v1 layout: .git/$id/info/url, refs/remotes/$id
2904 # v2 layout: .git/svn/$id/info/url, refs/remotes/$id
2906 # v3 layout: .git/svn/$id, refs/remotes/$id
2907 #            - info/url may remain for backwards compatibility
2908 #            - this is what we migrate up to this layout automatically,
2909 #            - this will be used by git svn init on single branches
2911 # v4 layout: .git/svn/$repo_id/$id, refs/remotes/$repo_id/$id
2912 #            - this is only created for newly multi-init-ed
2913 #              repositories.  Similar in spirit to the
2914 #              --use-separate-remotes option in git-clone (now default)
2915 #            - we do not automatically migrate to this (following
2916 #              the example set by core git)
2917 use strict;
2918 use warnings;
2919 use Carp qw/croak/;
2920 use File::Path qw/mkpath/;
2921 use File::Basename qw/dirname basename/;
2922 use vars qw/$_minimize/;
2924 sub migrate_from_v0 {
2925         my $git_dir = $ENV{GIT_DIR};
2926         return undef unless -d $git_dir;
2927         my ($fh, $ctx) = command_output_pipe(qw/rev-parse --symbolic --all/);
2928         my $migrated = 0;
2929         while (<$fh>) {
2930                 chomp;
2931                 my ($id, $orig_ref) = ($_, $_);
2932                 next unless $id =~ s#^refs/heads/(.+)-HEAD$#$1#;
2933                 next unless -f "$git_dir/$id/info/url";
2934                 my $new_ref = "refs/remotes/$id";
2935                 if (::verify_ref("$new_ref^0")) {
2936                         print STDERR "W: $orig_ref is probably an old ",
2937                                      "branch used by an ancient version of ",
2938                                      "git-svn.\n",
2939                                      "However, $new_ref also exists.\n",
2940                                      "We will not be able ",
2941                                      "to use this branch until this ",
2942                                      "ambiguity is resolved.\n";
2943                         next;
2944                 }
2945                 print STDERR "Migrating from v0 layout...\n" if !$migrated;
2946                 print STDERR "Renaming ref: $orig_ref => $new_ref\n";
2947                 command_noisy('update-ref', $new_ref, $orig_ref);
2948                 command_noisy('update-ref', '-d', $orig_ref, $orig_ref);
2949                 $migrated++;
2950         }
2951         command_close_pipe($fh, $ctx);
2952         print STDERR "Done migrating from v0 layout...\n" if $migrated;
2953         $migrated;
2956 sub migrate_from_v1 {
2957         my $git_dir = $ENV{GIT_DIR};
2958         my $migrated = 0;
2959         return $migrated unless -d $git_dir;
2960         my $svn_dir = "$git_dir/svn";
2962         # just in case somebody used 'svn' as their $id at some point...
2963         return $migrated if -d $svn_dir && ! -f "$svn_dir/info/url";
2965         print STDERR "Migrating from a git-svn v1 layout...\n";
2966         mkpath([$svn_dir]);
2967         print STDERR "Data from a previous version of git-svn exists, but\n\t",
2968                      "$svn_dir\n\t(required for this version ",
2969                      "($::VERSION) of git-svn) does not. exist\n";
2970         my ($fh, $ctx) = command_output_pipe(qw/rev-parse --symbolic --all/);
2971         while (<$fh>) {
2972                 my $x = $_;
2973                 next unless $x =~ s#^refs/remotes/##;
2974                 chomp $x;
2975                 next unless -f "$git_dir/$x/info/url";
2976                 my $u = eval { ::file_to_s("$git_dir/$x/info/url") };
2977                 next unless $u;
2978                 my $dn = dirname("$git_dir/svn/$x");
2979                 mkpath([$dn]) unless -d $dn;
2980                 if ($x eq 'svn') { # they used 'svn' as GIT_SVN_ID:
2981                         mkpath(["$git_dir/svn/svn"]);
2982                         print STDERR " - $git_dir/$x/info => ",
2983                                         "$git_dir/svn/$x/info\n";
2984                         rename "$git_dir/$x/info", "$git_dir/svn/$x/info" or
2985                                croak "$!: $x";
2986                         # don't worry too much about these, they probably
2987                         # don't exist with repos this old (save for index,
2988                         # and we can easily regenerate that)
2989                         foreach my $f (qw/unhandled.log index .rev_db/) {
2990                                 rename "$git_dir/$x/$f", "$git_dir/svn/$x/$f";
2991                         }
2992                 } else {
2993                         print STDERR " - $git_dir/$x => $git_dir/svn/$x\n";
2994                         rename "$git_dir/$x", "$git_dir/svn/$x" or
2995                                croak "$!: $x";
2996                 }
2997                 $migrated++;
2998         }
2999         command_close_pipe($fh, $ctx);
3000         print STDERR "Done migrating from a git-svn v1 layout\n";
3001         $migrated;
3004 sub read_old_urls {
3005         my ($l_map, $pfx, $path) = @_;
3006         my @dir;
3007         foreach (<$path/*>) {
3008                 if (-r "$_/info/url") {
3009                         $pfx .= '/' if $pfx && $pfx !~ m!/$!;
3010                         my $ref_id = $pfx . basename $_;
3011                         my $url = ::file_to_s("$_/info/url");
3012                         $l_map->{$ref_id} = $url;
3013                 } elsif (-d $_) {
3014                         push @dir, $_;
3015                 }
3016         }
3017         foreach (@dir) {
3018                 my $x = $_;
3019                 $x =~ s!^\Q$ENV{GIT_DIR}\E/svn/!!o;
3020                 read_old_urls($l_map, $x, $_);
3021         }
3024 sub migrate_from_v2 {
3025         my @cfg = command(qw/config -l/);
3026         return if grep /^svn-remote\..+\.url=/, @cfg;
3027         my %l_map;
3028         read_old_urls(\%l_map, '', "$ENV{GIT_DIR}/svn");
3029         my $migrated = 0;
3031         foreach my $ref_id (sort keys %l_map) {
3032                 eval { Git::SVN->init($l_map{$ref_id}, '', undef, $ref_id) };
3033                 if ($@) {
3034                         Git::SVN->init($l_map{$ref_id}, '', $ref_id, $ref_id);
3035                 }
3036                 $migrated++;
3037         }
3038         $migrated;
3041 sub minimize_connections {
3042         my $r = Git::SVN::read_all_remotes();
3043         my $new_urls = {};
3044         my $root_repos = {};
3045         foreach my $repo_id (keys %$r) {
3046                 my $url = $r->{$repo_id}->{url} or next;
3047                 my $fetch = $r->{$repo_id}->{fetch} or next;
3048                 my $ra = Git::SVN::Ra->new($url);
3050                 # skip existing cases where we already connect to the root
3051                 if (($ra->{url} eq $ra->{repos_root}) ||
3052                     (Git::SVN::sanitize_remote_name($ra->{repos_root}) eq
3053                      $repo_id)) {
3054                         $root_repos->{$ra->{url}} = $repo_id;
3055                         next;
3056                 }
3058                 my $root_ra = Git::SVN::Ra->new($ra->{repos_root});
3059                 my $root_path = $ra->{url};
3060                 $root_path =~ s#^\Q$ra->{repos_root}\E/*##;
3061                 foreach my $path (keys %$fetch) {
3062                         my $ref_id = $fetch->{$path};
3063                         my $gs = Git::SVN->new($ref_id, $repo_id, $path);
3065                         # make sure we can read when connecting to
3066                         # a higher level of a repository
3067                         my ($last_rev, undef) = $gs->last_rev_commit;
3068                         if (!defined $last_rev) {
3069                                 $last_rev = eval {
3070                                         $root_ra->get_latest_revnum;
3071                                 };
3072                                 next if $@;
3073                         }
3074                         my $new = $root_path;
3075                         $new .= length $path ? "/$path" : '';
3076                         eval {
3077                                 $root_ra->get_log([$new], $last_rev, $last_rev,
3078                                                   0, 0, 1, sub { });
3079                         };
3080                         next if $@;
3081                         $new_urls->{$ra->{repos_root}}->{$new} =
3082                                 { ref_id => $ref_id,
3083                                   old_repo_id => $repo_id,
3084                                   old_path => $path };
3085                 }
3086         }
3088         my @emptied;
3089         foreach my $url (keys %$new_urls) {
3090                 # see if we can re-use an existing [svn-remote "repo_id"]
3091                 # instead of creating a(n ugly) new section:
3092                 my $repo_id = $root_repos->{$url} ||
3093                               Git::SVN::sanitize_remote_name($url);
3095                 my $fetch = $new_urls->{$url};
3096                 foreach my $path (keys %$fetch) {
3097                         my $x = $fetch->{$path};
3098                         Git::SVN->init($url, $path, $repo_id, $x->{ref_id});
3099                         my $pfx = "svn-remote.$x->{old_repo_id}";
3101                         my $old_fetch = quotemeta("$x->{old_path}:".
3102                                                   "refs/remotes/$x->{ref_id}");
3103                         command_noisy(qw/config --unset/,
3104                                       "$pfx.fetch", '^'. $old_fetch . '$');
3105                         delete $r->{$x->{old_repo_id}}->
3106                                {fetch}->{$x->{old_path}};
3107                         if (!keys %{$r->{$x->{old_repo_id}}->{fetch}}) {
3108                                 command_noisy(qw/config --unset/,
3109                                               "$pfx.url");
3110                                 push @emptied, $x->{old_repo_id}
3111                         }
3112                 }
3113         }
3114         if (@emptied) {
3115                 my $file = $ENV{GIT_CONFIG} || $ENV{GIT_CONFIG_LOCAL} ||
3116                            "$ENV{GIT_DIR}/config";
3117                 print STDERR <<EOF;
3118 The following [svn-remote] sections in your config file ($file) are empty
3119 and can be safely removed:
3120 EOF
3121                 print STDERR "[svn-remote \"$_\"]\n" foreach @emptied;
3122         }
3125 sub migration_check {
3126         migrate_from_v0();
3127         migrate_from_v1();
3128         migrate_from_v2();
3129         minimize_connections() if $_minimize;
3132 package Git::IndexInfo;
3133 use strict;
3134 use warnings;
3135 use Git qw/command_input_pipe command_close_pipe/;
3137 sub new {
3138         my ($class) = @_;
3139         my ($gui, $ctx) = command_input_pipe(qw/update-index -z --index-info/);
3140         bless { gui => $gui, ctx => $ctx, nr => 0}, $class;
3143 sub remove {
3144         my ($self, $path) = @_;
3145         if (print { $self->{gui} } '0 ', 0 x 40, "\t", $path, "\0") {
3146                 return ++$self->{nr};
3147         }
3148         undef;
3151 sub update {
3152         my ($self, $mode, $hash, $path) = @_;
3153         if (print { $self->{gui} } $mode, ' ', $hash, "\t", $path, "\0") {
3154                 return ++$self->{nr};
3155         }
3156         undef;
3159 sub DESTROY {
3160         my ($self) = @_;
3161         command_close_pipe($self->{gui}, $self->{ctx});
3164 package Git::SVN::GlobSpec;
3165 use strict;
3166 use warnings;
3168 sub new {
3169         my ($class, $glob) = @_;
3170         warn "glob: $glob\n";
3171         my $re = $glob;
3172         $re =~ s!/+$!!g; # no need for trailing slashes
3173         my $nr = ($re =~ s!^(.*/?)\*(/?.*)$!\(\[^/\]+\)!g);
3174         my ($left, $right) = ($1, $2);
3175         if ($nr > 1) {
3176                 warn "Only one '*' wildcard expansion ",
3177                      "is supported (got $nr): '$glob'\n";
3178         } elsif ($nr == 0) {
3179                 warn "One '*' is needed for glob: '$glob'\n";
3180         }
3181         $re = quotemeta($left) . $re . quotemeta($right);
3182         $left =~ s!/+$!!g;
3183         $right =~ s!^/+!!g;
3184         bless { left => $left, right => $right,
3185                 regex => qr/$re/, glob => $glob }, $class;
3188 sub full_path {
3189         my ($self, $path) = @_;
3190         return (length $self->{left} ? "$self->{left}/" : '') .
3191                $path . (length $self->{right} ? "/$self->{right}" : '');
3194 __END__
3196 Data structures:
3199 $remotes = { # returned by read_all_remotes()
3200         'svn' => {
3201                 # svn-remote.svn.url=https://svn.musicpd.org
3202                 url => 'https://svn.musicpd.org',
3203                 # svn-remote.svn.fetch=mpd/trunk:trunk
3204                 fetch => {
3205                         'mpd/trunk' => 'trunk',
3206                 },
3207                 # svn-remote.svn.tags=mpd/tags/*:tags/*
3208                 tags => {
3209                         path => {
3210                                 left => 'mpd/tags',
3211                                 right => '',
3212                                 regex => qr!mpd/tags/([^/]+)$!,
3213                                 glob => 'tags/*',
3214                         },
3215                         ref => {
3216                                 left => 'tags',
3217                                 right => '',
3218                                 regex => qr!tags/([^/]+)$!,
3219                                 glob => 'tags/*',
3220                         },
3221                 }
3222         }
3223 };
3225 $log_entry hashref as returned by libsvn_log_entry()
3227         log => 'whitespace-formatted log entry
3228 ',                                              # trailing newline is preserved
3229         revision => '8',                        # integer
3230         date => '2004-02-24T17:01:44.108345Z',  # commit date
3231         author => 'committer name'
3232 };
3235 # this is generated by generate_diff();
3236 @mods = array of diff-index line hashes, each element represents one line
3237         of diff-index output
3239 diff-index line ($m hash)
3241         mode_a => first column of diff-index output, no leading ':',
3242         mode_b => second column of diff-index output,
3243         sha1_b => sha1sum of the final blob,
3244         chg => change type [MCRADT],
3245         file_a => original file name of a file (iff chg is 'C' or 'R')
3246         file_b => new/current file name of a file (any chg)
3250 # retval of read_url_paths{,_all}();
3251 $l_map = {
3252         # repository root url
3253         'https://svn.musicpd.org' => {
3254                 # repository path               # GIT_SVN_ID
3255                 'mpd/trunk'             =>      'trunk',
3256                 'mpd/tags/0.11.5'       =>      'tags/0.11.5',
3257         },
3260 Notes:
3261         I don't trust the each() function on unless I created %hash myself
3262         because the internal iterator may not have started at base.