Code

git-svn: prepare multi-init for wildcard support
[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 find_parent_branch {
1116         my ($self, $paths, $rev) = @_;
1117         return undef unless $_follow_parent;
1118         unless (defined $paths) {
1119                 my $err_handler = $SVN::Error::handler;
1120                 $SVN::Error::handler = \&Git::SVN::Ra::skip_unknown_revs;
1121                 $self->ra->get_log([$self->{path}], $rev, $rev, 0, 1, 1, sub {
1122                                    $paths =
1123                                       Git::SVN::Ra::dup_changed_paths($_[0]) });
1124                 $SVN::Error::handler = $err_handler;
1125         }
1126         return undef unless defined $paths;
1128         # look for a parent from another branch:
1129         my @b_path_components = split m#/#, $self->rel_path;
1130         my @a_path_components;
1131         my $i;
1132         while (@b_path_components) {
1133                 $i = $paths->{'/'.join('/', @b_path_components)};
1134                 last if $i;
1135                 unshift(@a_path_components, pop(@b_path_components));
1136         }
1137         goto not_found unless defined $i;
1138         my $branch_from = $i->{copyfrom_path} or goto not_found;
1139         if (@a_path_components) {
1140                 print STDERR "branch_from: $branch_from => ";
1141                 $branch_from .= '/'.join('/', @a_path_components);
1142                 print STDERR $branch_from, "\n";
1143         }
1144         my $r = $i->{copyfrom_rev};
1145         my $repos_root = $self->ra->{repos_root};
1146         my $url = $self->ra->{url};
1147         my $new_url = $repos_root . $branch_from;
1148         print STDERR  "Found possible branch point: ",
1149                       "$new_url => ", $self->full_url, ", $r\n";
1150         $branch_from =~ s#^/##;
1151         my $remotes = read_all_remotes();
1152         my $gs;
1153         foreach my $repo_id (keys %$remotes) {
1154                 my $u = $remotes->{$repo_id}->{url} or next;
1155                 next if $url ne $u;
1156                 my $fetch = $remotes->{$repo_id}->{fetch};
1157                 foreach my $f (keys %$fetch) {
1158                         next if $f ne $branch_from;
1159                         $gs = Git::SVN->new($fetch->{$f}, $repo_id, $f);
1160                         last;
1161                 }
1162                 last if $gs;
1163         }
1164         unless ($gs) {
1165                 my $ref_id = $self->{ref_id};
1166                 $ref_id =~ s/\@\d+$//;
1167                 $ref_id .= "\@$r";
1168                 # just grow a tail if we're not unique enough :x
1169                 $ref_id .= '-' while find_ref($ref_id);
1170                 print STDERR "Initializing parent: $ref_id\n";
1171                 $gs = Git::SVN->init($new_url, '', $ref_id, $ref_id, 1);
1172         }
1173         my ($r0, $parent) = $gs->find_rev_before($r, 1);
1174         if ($_follow_parent && (!defined $r0 || !defined $parent)) {
1175                 $gs->fetch(0, $r);
1176                 ($r0, $parent) = $gs->last_rev_commit;
1177         }
1178         if (defined $r0 && defined $parent) {
1179                 print STDERR "Found branch parent: ($self->{ref_id}) $parent\n";
1180                 $self->assert_index_clean($parent);
1181                 my $ed;
1182                 if ($self->ra->can_do_switch) {
1183                         print STDERR "Following parent with do_switch\n";
1184                         # do_switch works with svn/trunk >= r22312, but that
1185                         # is not included with SVN 1.4.3 (the latest version
1186                         # at the moment), so we can't rely on it
1187                         $self->{last_commit} = $parent;
1188                         $ed = SVN::Git::Fetcher->new($self);
1189                         $gs->ra->gs_do_switch($r0, $rev, $gs,
1190                                               $self->full_url, $ed)
1191                           or die "SVN connection failed somewhere...\n";
1192                 } else {
1193                         print STDERR "Following parent with do_update\n";
1194                         $ed = SVN::Git::Fetcher->new($self);
1195                         $self->ra->gs_do_update($rev, $rev, $self, $ed)
1196                           or die "SVN connection failed somewhere...\n";
1197                 }
1198                 print STDERR "Successfully followed parent\n";
1199                 return $self->make_log_entry($rev, [$parent], $ed);
1200         }
1201 not_found:
1202         print STDERR "Branch parent for path: '/",
1203                      $self->rel_path, "' @ r$rev not found:\n";
1204         return undef unless $paths;
1205         print STDERR "Changed paths:\n";
1206         foreach my $x (sort keys %$paths) {
1207                 my $p = $paths->{$x};
1208                 print STDERR "\t$p->{action}\t$x";
1209                 if ($p->{copyfrom_path}) {
1210                         print STDERR "(from $p->{copyfrom_path}: ",
1211                                      "$p->{copyfrom_rev})";
1212                 }
1213                 print STDERR "\n";
1214         }
1215         print STDERR '-'x72, "\n";
1216         return undef;
1219 sub do_fetch {
1220         my ($self, $paths, $rev) = @_;
1221         my $ed;
1222         my ($last_rev, @parents);
1223         if ($self->{last_commit}) {
1224                 $ed = SVN::Git::Fetcher->new($self);
1225                 $last_rev = $self->{last_rev};
1226                 $ed->{c} = $self->{last_commit};
1227                 @parents = ($self->{last_commit});
1228         } else {
1229                 $last_rev = $rev;
1230                 if (my $log_entry = $self->find_parent_branch($paths, $rev)) {
1231                         return $log_entry;
1232                 }
1233                 $ed = SVN::Git::Fetcher->new($self);
1234         }
1235         unless ($self->ra->gs_do_update($last_rev, $rev, $self, $ed)) {
1236                 die "SVN connection failed somewhere...\n";
1237         }
1238         $self->make_log_entry($rev, \@parents, $ed);
1241 sub get_untracked {
1242         my ($self, $ed) = @_;
1243         my @out;
1244         my $h = $ed->{empty};
1245         foreach (sort keys %$h) {
1246                 my $act = $h->{$_} ? '+empty_dir' : '-empty_dir';
1247                 push @out, "  $act: " . uri_encode($_);
1248                 warn "W: $act: $_\n";
1249         }
1250         foreach my $t (qw/dir_prop file_prop/) {
1251                 $h = $ed->{$t} or next;
1252                 foreach my $path (sort keys %$h) {
1253                         my $ppath = $path eq '' ? '.' : $path;
1254                         foreach my $prop (sort keys %{$h->{$path}}) {
1255                                 next if $SKIP_PROP{$prop};
1256                                 my $v = $h->{$path}->{$prop};
1257                                 my $t_ppath_prop = "$t: " .
1258                                                     uri_encode($ppath) . ' ' .
1259                                                     uri_encode($prop);
1260                                 if (defined $v) {
1261                                         push @out, "  +$t_ppath_prop " .
1262                                                    uri_encode($v);
1263                                 } else {
1264                                         push @out, "  -$t_ppath_prop";
1265                                 }
1266                         }
1267                 }
1268         }
1269         foreach my $t (qw/absent_file absent_directory/) {
1270                 $h = $ed->{$t} or next;
1271                 foreach my $parent (sort keys %$h) {
1272                         foreach my $path (sort @{$h->{$parent}}) {
1273                                 push @out, "  $t: " .
1274                                            uri_encode("$parent/$path");
1275                                 warn "W: $t: $parent/$path ",
1276                                      "Insufficient permissions?\n";
1277                         }
1278                 }
1279         }
1280         \@out;
1283 sub parse_svn_date {
1284         my $date = shift || return '+0000 1970-01-01 00:00:00';
1285         my ($Y,$m,$d,$H,$M,$S) = ($date =~ /^(\d{4})\-(\d\d)\-(\d\d)T
1286                                             (\d\d)\:(\d\d)\:(\d\d).\d+Z$/x) or
1287                                          croak "Unable to parse date: $date\n";
1288         "+0000 $Y-$m-$d $H:$M:$S";
1291 sub check_author {
1292         my ($author) = @_;
1293         if (!defined $author || length $author == 0) {
1294                 $author = '(no author)';
1295         }
1296         if (defined $::_authors && ! defined $::users{$author}) {
1297                 die "Author: $author not defined in $::_authors file\n";
1298         }
1299         $author;
1302 sub make_log_entry {
1303         my ($self, $rev, $parents, $ed) = @_;
1304         my $untracked = $self->get_untracked($ed);
1306         open my $un, '>>', "$self->{dir}/unhandled.log" or croak $!;
1307         print $un "r$rev\n" or croak $!;
1308         print $un $_, "\n" foreach @$untracked;
1309         my %log_entry = ( parents => $parents || [], revision => $rev,
1310                           log => '');
1311         my $rp = $self->ra->rev_proplist($rev);
1312         foreach (sort keys %$rp) {
1313                 my $v = $rp->{$_};
1314                 if (/^svn:(author|date|log)$/) {
1315                         $log_entry{$1} = $v;
1316                 } else {
1317                         print $un "  rev_prop: ", uri_encode($_), ' ',
1318                                   uri_encode($v), "\n";
1319                 }
1320         }
1321         close $un or croak $!;
1323         $log_entry{date} = parse_svn_date($log_entry{date});
1324         $log_entry{author} = check_author($log_entry{author});
1325         $log_entry{log} .= "\n";
1326         \%log_entry;
1329 sub fetch {
1330         my ($self, $min_rev, $max_rev, @parents) = @_;
1331         my ($last_rev, $last_commit) = $self->last_rev_commit;
1332         my ($base, $head) = $self->get_fetch_range($min_rev, $max_rev);
1333         return if ($base > $head);
1334         $self->ra->gs_fetch_loop_common($base, $head, $self);
1337 sub set_tree_cb {
1338         my ($self, $log_entry, $tree, $rev, $date, $author) = @_;
1339         # TODO: enable and test optimized commits:
1340         if (0 && $rev == ($self->{last_rev} + 1)) {
1341                 $log_entry->{revision} = $rev;
1342                 $log_entry->{author} = $author;
1343                 $self->do_git_commit($log_entry, "$rev=$tree");
1344         } else {
1345                 $self->{inject_parents} = { $rev => $tree };
1346                 $self->fetch(undef, undef);
1347         }
1350 sub set_tree {
1351         my ($self, $tree) = (shift, shift);
1352         my $log_entry = ::get_commit_entry($tree);
1353         unless ($self->{last_rev}) {
1354                 fatal("Must have an existing revision to commit\n");
1355         }
1356         my %ed_opts = ( r => $self->{last_rev},
1357                         log => $log_entry->{log},
1358                         ra => $self->ra,
1359                         tree_a => $self->{last_commit},
1360                         tree_b => $tree,
1361                         editor_cb => sub {
1362                                $self->set_tree_cb($log_entry, $tree, @_) },
1363                         svn_path => $self->{path} );
1364         if (!SVN::Git::Editor->new(\%ed_opts)->apply_diff) {
1365                 print "No changes\nr$self->{last_rev} = $tree\n";
1366         }
1369 sub rebuild {
1370         my ($self) = @_;
1371         print "Rebuilding $self->{db_path} ...\n";
1372         my ($rev_list, $ctx) = command_output_pipe("rev-list", $self->refname);
1373         my $latest;
1374         my $full_url = $self->full_url;
1375         my $svn_uuid;
1376         while (<$rev_list>) {
1377                 chomp;
1378                 my $c = $_;
1379                 die "Non-SHA1: $c\n" unless $c =~ /^$::sha1$/o;
1380                 my ($url, $rev, $uuid) = ::cmt_metadata($c);
1382                 # ignore merges (from set-tree)
1383                 next if (!defined $rev || !$uuid);
1385                 # if we merged or otherwise started elsewhere, this is
1386                 # how we break out of it
1387                 if ((defined $svn_uuid && ($uuid ne $svn_uuid)) ||
1388                     ($full_url && $url && ($url ne $full_url))) {
1389                         next;
1390                 }
1391                 $latest ||= $rev;
1392                 $svn_uuid ||= $uuid;
1394                 $self->rev_db_set($rev, $c);
1395                 print "r$rev = $c\n";
1396         }
1397         command_close_pipe($rev_list, $ctx);
1398         print "Done rebuilding $self->{db_path}\n";
1401 # rev_db:
1402 # Tie::File seems to be prone to offset errors if revisions get sparse,
1403 # it's not that fast, either.  Tie::File is also not in Perl 5.6.  So
1404 # one of my favorite modules is out :<  Next up would be one of the DBM
1405 # modules, but I'm not sure which is most portable...  So I'll just
1406 # go with something that's plain-text, but still capable of
1407 # being randomly accessed.  So here's my ultra-simple fixed-width
1408 # database.  All records are 40 characters + "\n", so it's easy to seek
1409 # to a revision: (41 * rev) is the byte offset.
1410 # A record of 40 0s denotes an empty revision.
1411 # And yes, it's still pretty fast (faster than Tie::File).
1412 # These files are disposable unless --no-metadata is set
1414 sub rev_db_set {
1415         my ($self, $rev, $commit, $update_ref) = @_;
1416         length $commit == 40 or croak "arg3 must be a full SHA1 hexsum\n";
1417         my ($db, $db_lock) = ($self->{db_path}, "$self->{db_path}.lock");
1418         my $sig;
1419         if ($update_ref) {
1420                 $SIG{INT} = $SIG{HUP} = $SIG{TERM} = $SIG{ALRM} = $SIG{PIPE} =
1421                             $SIG{USR1} = $SIG{USR2} = sub { $sig = $_[0] };
1422         }
1423         $LOCKFILES{$db_lock} = 1;
1424         if ($_no_metadata) {
1425                 copy($db, $db_lock) or die "rev_db_set(@_): ",
1426                                            "Failed to copy: ",
1427                                            "$db => $db_lock ($!)\n";
1428         } else {
1429                 rename $db, $db_lock or die "rev_db_set(@_): ",
1430                                             "Failed to rename: ",
1431                                             "$db => $db_lock ($!)\n";
1432         }
1433         open my $fh, '+<', $db_lock or croak $!;
1434         my $offset = $rev * 41;
1435         # assume that append is the common case:
1436         seek $fh, 0, 2 or croak $!;
1437         my $pos = tell $fh;
1438         if ($pos < $offset) {
1439                 for (1 .. (($offset - $pos) / 41)) {
1440                         print $fh (('0' x 40),"\n") or croak $!;
1441                 }
1442         }
1443         seek $fh, $offset, 0 or croak $!;
1444         print $fh $commit,"\n" or croak $!;
1445         close $fh or croak $!;
1446         if ($update_ref) {
1447                 command_noisy('update-ref', '-m', "r$rev",
1448                               $self->refname, $commit);
1449         }
1450         rename $db_lock, $db or die "rev_db_set(@_): ", "Failed to rename: ",
1451                                     "$db_lock => $db ($!)\n";
1452         delete $LOCKFILES{$db_lock};
1453         if ($update_ref) {
1454                 $SIG{INT} = $SIG{HUP} = $SIG{TERM} = $SIG{ALRM} = $SIG{PIPE} =
1455                             $SIG{USR1} = $SIG{USR2} = 'DEFAULT';
1456                 kill $sig, $$ if defined $sig;
1457         }
1460 sub rev_db_max {
1461         my ($self) = @_;
1462         my @stat = stat $self->{db_path} or
1463                         die "Couldn't stat $self->{db_path}: $!\n";
1464         ($stat[7] % 41) == 0 or
1465                         die "$self->{db_path} inconsistent size:$stat[7]\n";
1466         my $max = $stat[7] / 41;
1467         (($max > 0) ? $max - 1 : 0);
1470 sub rev_db_get {
1471         my ($self, $rev) = @_;
1472         my $ret;
1473         my $offset = $rev * 41;
1474         open my $fh, '<', $self->{db_path} or croak $!;
1475         if (sysseek($fh, $offset, 0) == $offset) {
1476                 my $read = sysread($fh, $ret, 40);
1477                 $ret = undef if ($read != 40 || $ret eq ('0'x40));
1478         }
1479         close $fh or croak $!;
1480         $ret;
1483 sub find_rev_before {
1484         my ($self, $rev, $eq_ok) = @_;
1485         --$rev unless $eq_ok;
1486         while ($rev > 0) {
1487                 if (my $c = $self->rev_db_get($rev)) {
1488                         return ($rev, $c);
1489                 }
1490                 --$rev;
1491         }
1492         return (undef, undef);
1495 sub _new {
1496         my ($class, $repo_id, $ref_id, $path) = @_;
1497         unless (defined $repo_id && length $repo_id) {
1498                 $repo_id = $Git::SVN::default_repo_id;
1499         }
1500         unless (defined $ref_id && length $ref_id) {
1501                 $_[2] = $ref_id = $Git::SVN::default_ref_id;
1502         }
1503         $_[1] = $repo_id = sanitize_remote_name($repo_id);
1504         my $dir = "$ENV{GIT_DIR}/svn/$ref_id";
1505         $_[3] = $path = '' unless (defined $path);
1506         mkpath([$dir]);
1507         unless (-f "$dir/.rev_db") {
1508                 open my $fh, '>>', "$dir/.rev_db" or croak $!;
1509                 close $fh or croak $!;
1510         }
1511         bless { ref_id => $ref_id, dir => $dir, index => "$dir/index",
1512                 path => $path,
1513                 db_path => "$dir/.rev_db", repo_id => $repo_id }, $class;
1516 sub uri_encode {
1517         my ($f) = @_;
1518         $f =~ s#([^a-zA-Z0-9\*!\:_\./\-])#uc sprintf("%%%02x",ord($1))#eg;
1519         $f
1522 package Git::SVN::Prompt;
1523 use strict;
1524 use warnings;
1525 require SVN::Core;
1526 use vars qw/$_no_auth_cache $_username/;
1528 sub simple {
1529         my ($cred, $realm, $default_username, $may_save, $pool) = @_;
1530         $may_save = undef if $_no_auth_cache;
1531         $default_username = $_username if defined $_username;
1532         if (defined $default_username && length $default_username) {
1533                 if (defined $realm && length $realm) {
1534                         print STDERR "Authentication realm: $realm\n";
1535                         STDERR->flush;
1536                 }
1537                 $cred->username($default_username);
1538         } else {
1539                 username($cred, $realm, $may_save, $pool);
1540         }
1541         $cred->password(_read_password("Password for '" .
1542                                        $cred->username . "': ", $realm));
1543         $cred->may_save($may_save);
1544         $SVN::_Core::SVN_NO_ERROR;
1547 sub ssl_server_trust {
1548         my ($cred, $realm, $failures, $cert_info, $may_save, $pool) = @_;
1549         $may_save = undef if $_no_auth_cache;
1550         print STDERR "Error validating server certificate for '$realm':\n";
1551         if ($failures & $SVN::Auth::SSL::UNKNOWNCA) {
1552                 print STDERR " - The certificate is not issued by a trusted ",
1553                       "authority. Use the\n",
1554                       "   fingerprint to validate the certificate manually!\n";
1555         }
1556         if ($failures & $SVN::Auth::SSL::CNMISMATCH) {
1557                 print STDERR " - The certificate hostname does not match.\n";
1558         }
1559         if ($failures & $SVN::Auth::SSL::NOTYETVALID) {
1560                 print STDERR " - The certificate is not yet valid.\n";
1561         }
1562         if ($failures & $SVN::Auth::SSL::EXPIRED) {
1563                 print STDERR " - The certificate has expired.\n";
1564         }
1565         if ($failures & $SVN::Auth::SSL::OTHER) {
1566                 print STDERR " - The certificate has an unknown error.\n";
1567         }
1568         printf STDERR
1569                 "Certificate information:\n".
1570                 " - Hostname: %s\n".
1571                 " - Valid: from %s until %s\n".
1572                 " - Issuer: %s\n".
1573                 " - Fingerprint: %s\n",
1574                 map $cert_info->$_, qw(hostname valid_from valid_until
1575                                        issuer_dname fingerprint);
1576         my $choice;
1577 prompt:
1578         print STDERR $may_save ?
1579               "(R)eject, accept (t)emporarily or accept (p)ermanently? " :
1580               "(R)eject or accept (t)emporarily? ";
1581         STDERR->flush;
1582         $choice = lc(substr(<STDIN> || 'R', 0, 1));
1583         if ($choice =~ /^t$/i) {
1584                 $cred->may_save(undef);
1585         } elsif ($choice =~ /^r$/i) {
1586                 return -1;
1587         } elsif ($may_save && $choice =~ /^p$/i) {
1588                 $cred->may_save($may_save);
1589         } else {
1590                 goto prompt;
1591         }
1592         $cred->accepted_failures($failures);
1593         $SVN::_Core::SVN_NO_ERROR;
1596 sub ssl_client_cert {
1597         my ($cred, $realm, $may_save, $pool) = @_;
1598         $may_save = undef if $_no_auth_cache;
1599         print STDERR "Client certificate filename: ";
1600         STDERR->flush;
1601         chomp(my $filename = <STDIN>);
1602         $cred->cert_file($filename);
1603         $cred->may_save($may_save);
1604         $SVN::_Core::SVN_NO_ERROR;
1607 sub ssl_client_cert_pw {
1608         my ($cred, $realm, $may_save, $pool) = @_;
1609         $may_save = undef if $_no_auth_cache;
1610         $cred->password(_read_password("Password: ", $realm));
1611         $cred->may_save($may_save);
1612         $SVN::_Core::SVN_NO_ERROR;
1615 sub username {
1616         my ($cred, $realm, $may_save, $pool) = @_;
1617         $may_save = undef if $_no_auth_cache;
1618         if (defined $realm && length $realm) {
1619                 print STDERR "Authentication realm: $realm\n";
1620         }
1621         my $username;
1622         if (defined $_username) {
1623                 $username = $_username;
1624         } else {
1625                 print STDERR "Username: ";
1626                 STDERR->flush;
1627                 chomp($username = <STDIN>);
1628         }
1629         $cred->username($username);
1630         $cred->may_save($may_save);
1631         $SVN::_Core::SVN_NO_ERROR;
1634 sub _read_password {
1635         my ($prompt, $realm) = @_;
1636         print STDERR $prompt;
1637         STDERR->flush;
1638         require Term::ReadKey;
1639         Term::ReadKey::ReadMode('noecho');
1640         my $password = '';
1641         while (defined(my $key = Term::ReadKey::ReadKey(0))) {
1642                 last if $key =~ /[\012\015]/; # \n\r
1643                 $password .= $key;
1644         }
1645         Term::ReadKey::ReadMode('restore');
1646         print STDERR "\n";
1647         STDERR->flush;
1648         $password;
1651 package main;
1654         my $kill_stupid_warnings = $SVN::Node::none.$SVN::Node::file.
1655                                 $SVN::Node::dir.$SVN::Node::unknown.
1656                                 $SVN::Node::none.$SVN::Node::file.
1657                                 $SVN::Node::dir.$SVN::Node::unknown.
1658                                 $SVN::Auth::SSL::CNMISMATCH.
1659                                 $SVN::Auth::SSL::NOTYETVALID.
1660                                 $SVN::Auth::SSL::EXPIRED.
1661                                 $SVN::Auth::SSL::UNKNOWNCA.
1662                                 $SVN::Auth::SSL::OTHER;
1665 package SVN::Git::Fetcher;
1666 use vars qw/@ISA/;
1667 use strict;
1668 use warnings;
1669 use Carp qw/croak/;
1670 use IO::File qw//;
1671 use Digest::MD5;
1673 # file baton members: path, mode_a, mode_b, pool, fh, blob, base
1674 sub new {
1675         my ($class, $git_svn) = @_;
1676         my $self = SVN::Delta::Editor->new;
1677         bless $self, $class;
1678         $self->{c} = $git_svn->{last_commit} if exists $git_svn->{last_commit};
1679         $self->{empty} = {};
1680         $self->{dir_prop} = {};
1681         $self->{file_prop} = {};
1682         $self->{absent_dir} = {};
1683         $self->{absent_file} = {};
1684         $self->{gii} = $git_svn->tmp_index_do(sub { Git::IndexInfo->new });
1685         $self;
1688 sub set_path_strip {
1689         my ($self, $path) = @_;
1690         $self->{path_strip} = qr/^\Q$path\E\/?/;
1693 sub open_root {
1694         { path => '' };
1697 sub open_directory {
1698         my ($self, $path, $pb, $rev) = @_;
1699         { path => $path };
1702 sub git_path {
1703         my ($self, $path) = @_;
1704         if ($self->{path_strip}) {
1705                 $path =~ s!$self->{path_strip}!! or
1706                   die "Failed to strip path '$path' ($self->{path_strip})\n";
1707         }
1708         $path;
1711 sub delete_entry {
1712         my ($self, $path, $rev, $pb) = @_;
1714         my $gpath = $self->git_path($path);
1715         return undef if ($gpath eq '');
1717         # remove entire directories.
1718         if (command('ls-tree', $self->{c}, '--', $gpath) =~ /^040000 tree/) {
1719                 my ($ls, $ctx) = command_output_pipe(qw/ls-tree
1720                                                      -r --name-only -z/,
1721                                                      $self->{c}, '--', $gpath);
1722                 local $/ = "\0";
1723                 while (<$ls>) {
1724                         chomp;
1725                         $self->{gii}->remove($_);
1726                         print "\tD\t$_\n" unless $self->{q};
1727                 }
1728                 print "\tD\t$gpath/\n" unless $self->{q};
1729                 command_close_pipe($ls, $ctx);
1730                 $self->{empty}->{$path} = 0
1731         } else {
1732                 $self->{gii}->remove($gpath);
1733                 print "\tD\t$gpath\n" unless $self->{q};
1734         }
1735         undef;
1738 sub open_file {
1739         my ($self, $path, $pb, $rev) = @_;
1740         my $gpath = $self->git_path($path);
1741         my ($mode, $blob) = (command('ls-tree', $self->{c}, '--', $gpath)
1742                              =~ /^(\d{6}) blob ([a-f\d]{40})\t/);
1743         unless (defined $mode && defined $blob) {
1744                 die "$path was not found in commit $self->{c} (r$rev)\n";
1745         }
1746         { path => $path, mode_a => $mode, mode_b => $mode, blob => $blob,
1747           pool => SVN::Pool->new, action => 'M' };
1750 sub add_file {
1751         my ($self, $path, $pb, $cp_path, $cp_rev) = @_;
1752         my ($dir, $file) = ($path =~ m#^(.*?)/?([^/]+)$#);
1753         delete $self->{empty}->{$dir};
1754         { path => $path, mode_a => 100644, mode_b => 100644,
1755           pool => SVN::Pool->new, action => 'A' };
1758 sub add_directory {
1759         my ($self, $path, $cp_path, $cp_rev) = @_;
1760         my ($dir, $file) = ($path =~ m#^(.*?)/?([^/]+)$#);
1761         delete $self->{empty}->{$dir};
1762         $self->{empty}->{$path} = 1;
1763         { path => $path };
1766 sub change_dir_prop {
1767         my ($self, $db, $prop, $value) = @_;
1768         $self->{dir_prop}->{$db->{path}} ||= {};
1769         $self->{dir_prop}->{$db->{path}}->{$prop} = $value;
1770         undef;
1773 sub absent_directory {
1774         my ($self, $path, $pb) = @_;
1775         $self->{absent_dir}->{$pb->{path}} ||= [];
1776         push @{$self->{absent_dir}->{$pb->{path}}}, $path;
1777         undef;
1780 sub absent_file {
1781         my ($self, $path, $pb) = @_;
1782         $self->{absent_file}->{$pb->{path}} ||= [];
1783         push @{$self->{absent_file}->{$pb->{path}}}, $path;
1784         undef;
1787 sub change_file_prop {
1788         my ($self, $fb, $prop, $value) = @_;
1789         if ($prop eq 'svn:executable') {
1790                 if ($fb->{mode_b} != 120000) {
1791                         $fb->{mode_b} = defined $value ? 100755 : 100644;
1792                 }
1793         } elsif ($prop eq 'svn:special') {
1794                 $fb->{mode_b} = defined $value ? 120000 : 100644;
1795         } else {
1796                 $self->{file_prop}->{$fb->{path}} ||= {};
1797                 $self->{file_prop}->{$fb->{path}}->{$prop} = $value;
1798         }
1799         undef;
1802 sub apply_textdelta {
1803         my ($self, $fb, $exp) = @_;
1804         my $fh = IO::File->new_tmpfile;
1805         $fh->autoflush(1);
1806         # $fh gets auto-closed() by SVN::TxDelta::apply(),
1807         # (but $base does not,) so dup() it for reading in close_file
1808         open my $dup, '<&', $fh or croak $!;
1809         my $base = IO::File->new_tmpfile;
1810         $base->autoflush(1);
1811         if ($fb->{blob}) {
1812                 defined (my $pid = fork) or croak $!;
1813                 if (!$pid) {
1814                         open STDOUT, '>&', $base or croak $!;
1815                         print STDOUT 'link ' if ($fb->{mode_a} == 120000);
1816                         exec qw/git-cat-file blob/, $fb->{blob} or croak $!;
1817                 }
1818                 waitpid $pid, 0;
1819                 croak $? if $?;
1821                 if (defined $exp) {
1822                         seek $base, 0, 0 or croak $!;
1823                         my $md5 = Digest::MD5->new;
1824                         $md5->addfile($base);
1825                         my $got = $md5->hexdigest;
1826                         die "Checksum mismatch: $fb->{path} $fb->{blob}\n",
1827                             "expected: $exp\n",
1828                             "     got: $got\n" if ($got ne $exp);
1829                 }
1830         }
1831         seek $base, 0, 0 or croak $!;
1832         $fb->{fh} = $dup;
1833         $fb->{base} = $base;
1834         [ SVN::TxDelta::apply($base, $fh, undef, $fb->{path}, $fb->{pool}) ];
1837 sub close_file {
1838         my ($self, $fb, $exp) = @_;
1839         my $hash;
1840         my $path = $self->git_path($fb->{path});
1841         if (my $fh = $fb->{fh}) {
1842                 seek($fh, 0, 0) or croak $!;
1843                 my $md5 = Digest::MD5->new;
1844                 $md5->addfile($fh);
1845                 my $got = $md5->hexdigest;
1846                 die "Checksum mismatch: $path\n",
1847                     "expected: $exp\n    got: $got\n" if ($got ne $exp);
1848                 seek($fh, 0, 0) or croak $!;
1849                 if ($fb->{mode_b} == 120000) {
1850                         read($fh, my $buf, 5) == 5 or croak $!;
1851                         $buf eq 'link ' or die "$path has mode 120000",
1852                                                "but is not a link\n";
1853                 }
1854                 defined(my $pid = open my $out,'-|') or die "Can't fork: $!\n";
1855                 if (!$pid) {
1856                         open STDIN, '<&', $fh or croak $!;
1857                         exec qw/git-hash-object -w --stdin/ or croak $!;
1858                 }
1859                 chomp($hash = do { local $/; <$out> });
1860                 close $out or croak $!;
1861                 close $fh or croak $!;
1862                 $hash =~ /^[a-f\d]{40}$/ or die "not a sha1: $hash\n";
1863                 close $fb->{base} or croak $!;
1864         } else {
1865                 $hash = $fb->{blob} or die "no blob information\n";
1866         }
1867         $fb->{pool}->clear;
1868         $self->{gii}->update($fb->{mode_b}, $hash, $path) or croak $!;
1869         print "\t$fb->{action}\t$path\n" if $fb->{action} && ! $self->{q};
1870         undef;
1873 sub abort_edit {
1874         my $self = shift;
1875         $self->{nr} = $self->{gii}->{nr};
1876         delete $self->{gii};
1877         $self->SUPER::abort_edit(@_);
1880 sub close_edit {
1881         my $self = shift;
1882         $self->{git_commit_ok} = 1;
1883         $self->{nr} = $self->{gii}->{nr};
1884         delete $self->{gii};
1885         $self->SUPER::close_edit(@_);
1888 package SVN::Git::Editor;
1889 use vars qw/@ISA $_rmdir $_cp_similarity $_find_copies_harder $_rename_limit/;
1890 use strict;
1891 use warnings;
1892 use Carp qw/croak/;
1893 use IO::File;
1894 use Digest::MD5;
1896 sub new {
1897         my ($class, $opts) = @_;
1898         foreach (qw/svn_path r ra tree_a tree_b log editor_cb/) {
1899                 die "$_ required!\n" unless (defined $opts->{$_});
1900         }
1902         my $pool = SVN::Pool->new;
1903         my $mods = generate_diff($opts->{tree_a}, $opts->{tree_b});
1904         my $types = check_diff_paths($opts->{ra}, $opts->{svn_path},
1905                                      $opts->{r}, $mods);
1907         # $opts->{ra} functions should not be used after this:
1908         my @ce  = $opts->{ra}->get_commit_editor($opts->{log},
1909                                                 $opts->{editor_cb}, $pool);
1910         my $self = SVN::Delta::Editor->new(@ce, $pool);
1911         bless $self, $class;
1912         foreach (qw/svn_path r tree_a tree_b/) {
1913                 $self->{$_} = $opts->{$_};
1914         }
1915         $self->{url} = $opts->{ra}->{url};
1916         $self->{mods} = $mods;
1917         $self->{types} = $types;
1918         $self->{pool} = $pool;
1919         $self->{bat} = { '' => $self->open_root($self->{r}, $self->{pool}) };
1920         $self->{rm} = { };
1921         $self->{path_prefix} = length $self->{svn_path} ?
1922                                "$self->{svn_path}/" : '';
1923         return $self;
1926 sub generate_diff {
1927         my ($tree_a, $tree_b) = @_;
1928         my @diff_tree = qw(diff-tree -z -r);
1929         if ($_cp_similarity) {
1930                 push @diff_tree, "-C$_cp_similarity";
1931         } else {
1932                 push @diff_tree, '-C';
1933         }
1934         push @diff_tree, '--find-copies-harder' if $_find_copies_harder;
1935         push @diff_tree, "-l$_rename_limit" if defined $_rename_limit;
1936         push @diff_tree, $tree_a, $tree_b;
1937         my ($diff_fh, $ctx) = command_output_pipe(@diff_tree);
1938         local $/ = "\0";
1939         my $state = 'meta';
1940         my @mods;
1941         while (<$diff_fh>) {
1942                 chomp $_; # this gets rid of the trailing "\0"
1943                 if ($state eq 'meta' && /^:(\d{6})\s(\d{6})\s
1944                                         $::sha1\s($::sha1)\s
1945                                         ([MTCRAD])\d*$/xo) {
1946                         push @mods, {   mode_a => $1, mode_b => $2,
1947                                         sha1_b => $3, chg => $4 };
1948                         if ($4 =~ /^(?:C|R)$/) {
1949                                 $state = 'file_a';
1950                         } else {
1951                                 $state = 'file_b';
1952                         }
1953                 } elsif ($state eq 'file_a') {
1954                         my $x = $mods[$#mods] or croak "Empty array\n";
1955                         if ($x->{chg} !~ /^(?:C|R)$/) {
1956                                 croak "Error parsing $_, $x->{chg}\n";
1957                         }
1958                         $x->{file_a} = $_;
1959                         $state = 'file_b';
1960                 } elsif ($state eq 'file_b') {
1961                         my $x = $mods[$#mods] or croak "Empty array\n";
1962                         if (exists $x->{file_a} && $x->{chg} !~ /^(?:C|R)$/) {
1963                                 croak "Error parsing $_, $x->{chg}\n";
1964                         }
1965                         if (!exists $x->{file_a} && $x->{chg} =~ /^(?:C|R)$/) {
1966                                 croak "Error parsing $_, $x->{chg}\n";
1967                         }
1968                         $x->{file_b} = $_;
1969                         $state = 'meta';
1970                 } else {
1971                         croak "Error parsing $_\n";
1972                 }
1973         }
1974         command_close_pipe($diff_fh, $ctx);
1975         \@mods;
1978 sub check_diff_paths {
1979         my ($ra, $pfx, $rev, $mods) = @_;
1980         my %types;
1981         $pfx .= '/' if length $pfx;
1983         sub type_diff_paths {
1984                 my ($ra, $types, $path, $rev) = @_;
1985                 my @p = split m#/+#, $path;
1986                 my $c = shift @p;
1987                 unless (defined $types->{$c}) {
1988                         $types->{$c} = $ra->check_path($c, $rev);
1989                 }
1990                 while (@p) {
1991                         $c .= '/' . shift @p;
1992                         next if defined $types->{$c};
1993                         $types->{$c} = $ra->check_path($c, $rev);
1994                 }
1995         }
1997         foreach my $m (@$mods) {
1998                 foreach my $f (qw/file_a file_b/) {
1999                         next unless defined $m->{$f};
2000                         my ($dir) = ($m->{$f} =~ m#^(.*?)/?(?:[^/]+)$#);
2001                         if (length $pfx.$dir && ! defined $types{$dir}) {
2002                                 type_diff_paths($ra, \%types, $pfx.$dir, $rev);
2003                         }
2004                 }
2005         }
2006         \%types;
2009 sub split_path {
2010         return ($_[0] =~ m#^(.*?)/?([^/]+)$#);
2013 sub repo_path {
2014         my ($self, $path) = @_;
2015         $self->{path_prefix}.(defined $path ? $path : '');
2018 sub url_path {
2019         my ($self, $path) = @_;
2020         $self->{url} . '/' . $self->repo_path($path);
2023 sub rmdirs {
2024         my ($self) = @_;
2025         my $rm = $self->{rm};
2026         delete $rm->{''}; # we never delete the url we're tracking
2027         return unless %$rm;
2029         foreach (keys %$rm) {
2030                 my @d = split m#/#, $_;
2031                 my $c = shift @d;
2032                 $rm->{$c} = 1;
2033                 while (@d) {
2034                         $c .= '/' . shift @d;
2035                         $rm->{$c} = 1;
2036                 }
2037         }
2038         delete $rm->{$self->{svn_path}};
2039         delete $rm->{''}; # we never delete the url we're tracking
2040         return unless %$rm;
2042         my ($fh, $ctx) = command_output_pipe(qw/ls-tree --name-only -r -z/,
2043                                              $self->{tree_b});
2044         local $/ = "\0";
2045         while (<$fh>) {
2046                 chomp;
2047                 my @dn = split m#/#, $_;
2048                 while (pop @dn) {
2049                         delete $rm->{join '/', @dn};
2050                 }
2051                 unless (%$rm) {
2052                         close $fh;
2053                         return;
2054                 }
2055         }
2056         command_close_pipe($fh, $ctx);
2058         my ($r, $p, $bat) = ($self->{r}, $self->{pool}, $self->{bat});
2059         foreach my $d (sort { $b =~ tr#/#/# <=> $a =~ tr#/#/# } keys %$rm) {
2060                 $self->close_directory($bat->{$d}, $p);
2061                 my ($dn) = ($d =~ m#^(.*?)/?(?:[^/]+)$#);
2062                 print "\tD+\t$d/\n" unless $::_q;
2063                 $self->SUPER::delete_entry($d, $r, $bat->{$dn}, $p);
2064                 delete $bat->{$d};
2065         }
2068 sub open_or_add_dir {
2069         my ($self, $full_path, $baton) = @_;
2070         my $t = $self->{types}->{$full_path};
2071         if (!defined $t) {
2072                 die "$full_path not known in r$self->{r} or we have a bug!\n";
2073         }
2074         if ($t == $SVN::Node::none) {
2075                 return $self->add_directory($full_path, $baton,
2076                                                 undef, -1, $self->{pool});
2077         } elsif ($t == $SVN::Node::dir) {
2078                 return $self->open_directory($full_path, $baton,
2079                                                 $self->{r}, $self->{pool});
2080         }
2081         print STDERR "$full_path already exists in repository at ",
2082                 "r$self->{r} and it is not a directory (",
2083                 ($t == $SVN::Node::file ? 'file' : 'unknown'),"/$t)\n";
2084         exit 1;
2087 sub ensure_path {
2088         my ($self, $path) = @_;
2089         my $bat = $self->{bat};
2090         my $repo_path = $self->repo_path($path);
2091         return $bat->{''} unless (length $repo_path);
2092         my @p = split m#/+#, $repo_path;
2093         my $c = shift @p;
2094         $bat->{$c} ||= $self->open_or_add_dir($c, $bat->{''});
2095         while (@p) {
2096                 my $c0 = $c;
2097                 $c .= '/' . shift @p;
2098                 $bat->{$c} ||= $self->open_or_add_dir($c, $bat->{$c0});
2099         }
2100         return $bat->{$c};
2103 sub A {
2104         my ($self, $m) = @_;
2105         my ($dir, $file) = split_path($m->{file_b});
2106         my $pbat = $self->ensure_path($dir);
2107         my $fbat = $self->add_file($self->repo_path($m->{file_b}), $pbat,
2108                                         undef, -1);
2109         print "\tA\t$m->{file_b}\n" unless $::_q;
2110         $self->chg_file($fbat, $m);
2111         $self->close_file($fbat,undef,$self->{pool});
2114 sub C {
2115         my ($self, $m) = @_;
2116         my ($dir, $file) = split_path($m->{file_b});
2117         my $pbat = $self->ensure_path($dir);
2118         my $fbat = $self->add_file($self->repo_path($m->{file_b}), $pbat,
2119                                 $self->url_path($m->{file_a}), $self->{r});
2120         print "\tC\t$m->{file_a} => $m->{file_b}\n" unless $::_q;
2121         $self->chg_file($fbat, $m);
2122         $self->close_file($fbat,undef,$self->{pool});
2125 sub delete_entry {
2126         my ($self, $path, $pbat) = @_;
2127         my $rpath = $self->repo_path($path);
2128         my ($dir, $file) = split_path($rpath);
2129         $self->{rm}->{$dir} = 1;
2130         $self->SUPER::delete_entry($rpath, $self->{r}, $pbat, $self->{pool});
2133 sub R {
2134         my ($self, $m) = @_;
2135         my ($dir, $file) = split_path($m->{file_b});
2136         my $pbat = $self->ensure_path($dir);
2137         my $fbat = $self->add_file($self->repo_path($m->{file_b}), $pbat,
2138                                 $self->url_path($m->{file_a}), $self->{r});
2139         print "\tR\t$m->{file_a} => $m->{file_b}\n" unless $::_q;
2140         $self->chg_file($fbat, $m);
2141         $self->close_file($fbat,undef,$self->{pool});
2143         ($dir, $file) = split_path($m->{file_a});
2144         $pbat = $self->ensure_path($dir);
2145         $self->delete_entry($m->{file_a}, $pbat);
2148 sub M {
2149         my ($self, $m) = @_;
2150         my ($dir, $file) = split_path($m->{file_b});
2151         my $pbat = $self->ensure_path($dir);
2152         my $fbat = $self->open_file($self->repo_path($m->{file_b}),
2153                                 $pbat,$self->{r},$self->{pool});
2154         print "\t$m->{chg}\t$m->{file_b}\n" unless $::_q;
2155         $self->chg_file($fbat, $m);
2156         $self->close_file($fbat,undef,$self->{pool});
2159 sub T { shift->M(@_) }
2161 sub change_file_prop {
2162         my ($self, $fbat, $pname, $pval) = @_;
2163         $self->SUPER::change_file_prop($fbat, $pname, $pval, $self->{pool});
2166 sub chg_file {
2167         my ($self, $fbat, $m) = @_;
2168         if ($m->{mode_b} =~ /755$/ && $m->{mode_a} !~ /755$/) {
2169                 $self->change_file_prop($fbat,'svn:executable','*');
2170         } elsif ($m->{mode_b} !~ /755$/ && $m->{mode_a} =~ /755$/) {
2171                 $self->change_file_prop($fbat,'svn:executable',undef);
2172         }
2173         my $fh = IO::File->new_tmpfile or croak $!;
2174         if ($m->{mode_b} =~ /^120/) {
2175                 print $fh 'link ' or croak $!;
2176                 $self->change_file_prop($fbat,'svn:special','*');
2177         } elsif ($m->{mode_a} =~ /^120/ && $m->{mode_b} !~ /^120/) {
2178                 $self->change_file_prop($fbat,'svn:special',undef);
2179         }
2180         defined(my $pid = fork) or croak $!;
2181         if (!$pid) {
2182                 open STDOUT, '>&', $fh or croak $!;
2183                 exec qw/git-cat-file blob/, $m->{sha1_b} or croak $!;
2184         }
2185         waitpid $pid, 0;
2186         croak $? if $?;
2187         $fh->flush == 0 or croak $!;
2188         seek $fh, 0, 0 or croak $!;
2190         my $md5 = Digest::MD5->new;
2191         $md5->addfile($fh) or croak $!;
2192         seek $fh, 0, 0 or croak $!;
2194         my $exp = $md5->hexdigest;
2195         my $pool = SVN::Pool->new;
2196         my $atd = $self->apply_textdelta($fbat, undef, $pool);
2197         my $got = SVN::TxDelta::send_stream($fh, @$atd, $pool);
2198         die "Checksum mismatch\nexpected: $exp\ngot: $got\n" if ($got ne $exp);
2199         $pool->clear;
2201         close $fh or croak $!;
2204 sub D {
2205         my ($self, $m) = @_;
2206         my ($dir, $file) = split_path($m->{file_b});
2207         my $pbat = $self->ensure_path($dir);
2208         print "\tD\t$m->{file_b}\n" unless $::_q;
2209         $self->delete_entry($m->{file_b}, $pbat);
2212 sub close_edit {
2213         my ($self) = @_;
2214         my ($p,$bat) = ($self->{pool}, $self->{bat});
2215         foreach (sort { $b =~ tr#/#/# <=> $a =~ tr#/#/# } keys %$bat) {
2216                 $self->close_directory($bat->{$_}, $p);
2217         }
2218         $self->SUPER::close_edit($p);
2219         $p->clear;
2222 sub abort_edit {
2223         my ($self) = @_;
2224         $self->SUPER::abort_edit($self->{pool});
2227 sub DESTROY {
2228         my $self = shift;
2229         $self->SUPER::DESTROY(@_);
2230         $self->{pool}->clear;
2233 # this drives the editor
2234 sub apply_diff {
2235         my ($self) = @_;
2236         my $mods = $self->{mods};
2237         my %o = ( D => 1, R => 0, C => -1, A => 3, M => 3, T => 3 );
2238         foreach my $m (sort { $o{$a->{chg}} <=> $o{$b->{chg}} } @$mods) {
2239                 my $f = $m->{chg};
2240                 if (defined $o{$f}) {
2241                         $self->$f($m);
2242                 } else {
2243                         fatal("Invalid change type: $f\n");
2244                 }
2245         }
2246         $self->rmdirs if $_rmdir;
2247         if (@$mods == 0) {
2248                 $self->abort_edit;
2249         } else {
2250                 $self->close_edit;
2251         }
2252         return scalar @$mods;
2255 package Git::SVN::Ra;
2256 use vars qw/@ISA $config_dir/;
2257 use strict;
2258 use warnings;
2259 my ($can_do_switch);
2260 my $RA;
2262 BEGIN {
2263         # enforce temporary pool usage for some simple functions
2264         my $e;
2265         foreach (qw/get_latest_revnum rev_proplist get_file
2266                     check_path get_dir get_uuid get_repos_root/) {
2267                 $e .= "sub $_ {
2268                         my \$self = shift;
2269                         my \$pool = SVN::Pool->new;
2270                         my \@ret = \$self->SUPER::$_(\@_,\$pool);
2271                         \$pool->clear;
2272                         wantarray ? \@ret : \$ret[0]; }\n";
2273         }
2274         eval $e;
2277 sub new {
2278         my ($class, $url) = @_;
2279         $url =~ s!/+$!!;
2280         return $RA if ($RA && $RA->{url} eq $url);
2282         SVN::_Core::svn_config_ensure($config_dir, undef);
2283         my ($baton, $callbacks) = SVN::Core::auth_open_helper([
2284             SVN::Client::get_simple_provider(),
2285             SVN::Client::get_ssl_server_trust_file_provider(),
2286             SVN::Client::get_simple_prompt_provider(
2287               \&Git::SVN::Prompt::simple, 2),
2288             SVN::Client::get_ssl_client_cert_prompt_provider(
2289               \&Git::SVN::Prompt::ssl_client_cert, 2),
2290             SVN::Client::get_ssl_client_cert_pw_prompt_provider(
2291               \&Git::SVN::Prompt::ssl_client_cert_pw, 2),
2292             SVN::Client::get_username_provider(),
2293             SVN::Client::get_ssl_server_trust_prompt_provider(
2294               \&Git::SVN::Prompt::ssl_server_trust),
2295             SVN::Client::get_username_prompt_provider(
2296               \&Git::SVN::Prompt::username, 2),
2297           ]);
2298         my $config = SVN::Core::config_get_config($config_dir);
2299         my $self = SVN::Ra->new(url => $url, auth => $baton,
2300                               config => $config,
2301                               pool => SVN::Pool->new,
2302                               auth_provider_callbacks => $callbacks);
2303         $self->{svn_path} = $url;
2304         $self->{repos_root} = $self->get_repos_root;
2305         $self->{svn_path} =~ s#^\Q$self->{repos_root}\E/*##;
2306         $RA = bless $self, $class;
2309 sub DESTROY {
2310         # do not call the real DESTROY since we store ourselves in $RA
2313 sub get_log {
2314         my ($self, @args) = @_;
2315         my $pool = SVN::Pool->new;
2316         splice(@args, 3, 1) if ($SVN::Core::VERSION le '1.2.0');
2317         my $ret = $self->SUPER::get_log(@args, $pool);
2318         $pool->clear;
2319         $ret;
2322 sub get_commit_editor {
2323         my ($self, $log, $cb, $pool) = @_;
2324         my @lock = $SVN::Core::VERSION ge '1.2.0' ? (undef, 0) : ();
2325         $self->SUPER::get_commit_editor($log, $cb, @lock, $pool);
2328 sub uuid {
2329         my ($self) = @_;
2330         $self->{uuid} ||= $self->get_uuid;
2333 sub gs_do_update {
2334         my ($self, $rev_a, $rev_b, $gs, $editor) = @_;
2335         my $new = ($rev_a == $rev_b);
2336         my $path = $gs->{path};
2338         my $ta = $self->check_path($path, $rev_a);
2339         my $tb = $new ? $ta : $self->check_path($path, $rev_b);
2340         return 1 if ($tb != $SVN::Node::dir && $ta != $SVN::Node::dir);
2341         if ($ta == $SVN::Node::none) {
2342                 $rev_a = $rev_b;
2343                 $new = 1;
2344         }
2346         my $pool = SVN::Pool->new;
2347         $editor->set_path_strip($path);
2348         my (@pc) = split m#/#, $path;
2349         my $reporter = $self->do_update($rev_b, (@pc ? shift @pc : ''),
2350                                         1, $editor, $pool);
2351         my @lock = $SVN::Core::VERSION ge '1.2.0' ? (undef) : ();
2353         # Since we can't rely on svn_ra_reparent being available, we'll
2354         # just have to do some magic with set_path to make it so
2355         # we only want a partial path.
2356         my $sp = '';
2357         my $final = join('/', @pc);
2358         while (@pc) {
2359                 $reporter->set_path($sp, $rev_b, 0, @lock, $pool);
2360                 $sp .= '/' if length $sp;
2361                 $sp .= shift @pc;
2362         }
2363         die "BUG: '$sp' != '$final'\n" if ($sp ne $final);
2365         $reporter->set_path($sp, $rev_a, $new, @lock, $pool);
2367         $reporter->finish_report($pool);
2368         $pool->clear;
2369         $editor->{git_commit_ok};
2372 # this requires SVN 1.4.3 or later (do_switch didn't work before 1.4.3, and
2373 # svn_ra_reparent didn't work before 1.4)
2374 sub gs_do_switch {
2375         my ($self, $rev_a, $rev_b, $gs, $url_b, $editor) = @_;
2376         my $path = $gs->{path};
2377         my $pool = SVN::Pool->new;
2379         my $full_url = $self->{url};
2380         my $old_url = $full_url;
2381         $full_url .= "/$path" if length $path;
2382         my ($ra, $reparented);
2383         if ($old_url ne $full_url) {
2384                 if ($old_url !~ m#^svn(\+ssh)?://#) {
2385                         SVN::_Ra::svn_ra_reparent($self->{session}, $full_url,
2386                                                   $pool);
2387                         $self->{url} = $full_url;
2388                         $reparented = 1;
2389                 } else {
2390                         $ra = Git::SVN::Ra->new($full_url);
2391                 }
2392         }
2393         $ra ||= $self;
2394         my $reporter = $ra->do_switch($rev_b, '', 1, $url_b, $editor, $pool);
2395         my @lock = $SVN::Core::VERSION ge '1.2.0' ? (undef) : ();
2396         $reporter->set_path('', $rev_a, 0, @lock, $pool);
2397         $reporter->finish_report($pool);
2399         if ($reparented) {
2400                 SVN::_Ra::svn_ra_reparent($self->{session}, $old_url, $pool);
2401                 $self->{url} = $old_url;
2402         }
2404         $pool->clear;
2405         $editor->{git_commit_ok};
2408 sub gs_fetch_loop_common {
2409         my ($self, $base, $head, @gs) = @_;
2410         my $inc = 1000;
2411         my ($min, $max) = ($base, $head < $base + $inc ? $head : $base + $inc);
2412         foreach my $gs (@gs) {
2413                 if (my $last_commit = $gs->last_commit) {
2414                         $gs->assert_index_clean($last_commit);
2415                 }
2416         }
2417         while (1) {
2418                 my %revs;
2419                 my $err;
2420                 my $err_handler = $SVN::Error::handler;
2421                 $SVN::Error::handler = sub {
2422                         ($err) = @_;
2423                         skip_unknown_revs($err);
2424                 };
2425                 foreach my $gs (@gs) {
2426                         my $min_r = $min;
2427                         my $rdb_max = $gs->rev_db_max;
2428                         next if $rdb_max >= $max;
2429                         $min_r = $rdb_max + 1 if ($rdb_max > $min_r);
2430                         $self->get_log([$gs->{path}], $min_r, $max,
2431                                        0, 1, 1, sub
2432                                        { my ($paths, $rev) = @_;
2433                                          push @{$revs{$rev}},
2434                                               [ $gs,
2435                                                 dup_changed_paths($paths) ] });
2437                         next unless ($err && $max >= $head);
2439                         print STDERR "Path '$gs->{path}' ",
2440                                      "was probably deleted:\n",
2441                                      $err->expanded_message,
2442                                      "\nWill attempt to follow ",
2443                                      "revisions r$min .. r$max ",
2444                                      "committed before the deletion\n";
2445                         my $hi = $max;
2446                         while (--$hi >= $min) {
2447                                 my $ok;
2448                                 $self->get_log([$gs->{path}], $min, $hi,
2449                                                0, 1, 1, sub {
2450                                         my ($paths, $rev) = @_;
2451                                         $ok = $rev;
2452                                         push @{$revs{$rev}}, [ $gs,
2453                                            dup_changed_paths($_[0])]});
2454                                 if ($ok) {
2455                                         print STDERR "r$min .. r$ok OK\n";
2456                                         last;
2457                                 }
2458                         }
2459                 }
2460                 $SVN::Error::handler = $err_handler;
2461                 foreach my $r (sort {$a <=> $b} keys %revs) {
2462                         foreach (@{$revs{$r}}) {
2463                                 my ($gs, $paths) = @$_;
2464                                 my $lr = $gs->last_rev;
2465                                 next if defined $lr && $lr >= $r;
2466                                 next if defined $gs->rev_db_get($r);
2467                                 if (my $log_entry = $gs->do_fetch($paths, $r)) {
2468                                         $gs->do_git_commit($log_entry);
2469                                 }
2470                         }
2471                 }
2472                 # pre-fill the .rev_db since it'll eventually get filled in
2473                 # with '0' x40 if something new gets committed
2474                 foreach my $gs (@gs) {
2475                         next if defined $gs->rev_db_get($max);
2476                         $gs->rev_db_set($max, 0 x40);
2477                 }
2478                 last if $max >= $head;
2479                 $min = $max + 1;
2480                 $max += $inc;
2481                 $max = $head if ($max > $head);
2482         }
2485 sub minimize_url {
2486         my ($self) = @_;
2487         return $self->{url} if ($self->{url} eq $self->{repos_root});
2488         my $url = $self->{repos_root};
2489         my @components = split(m!/!, $self->{svn_path});
2490         my $c = '';
2491         do {
2492                 $url .= "/$c" if length $c;
2493                 eval { (ref $self)->new($url)->get_latest_revnum };
2494         } while ($@ && ($c = shift @components));
2495         $url;
2498 sub can_do_switch {
2499         my $self = shift;
2500         unless (defined $can_do_switch) {
2501                 my $pool = SVN::Pool->new;
2502                 my $rep = eval {
2503                         $self->do_switch(1, '', 0, $self->{url},
2504                                          SVN::Delta::Editor->new, $pool);
2505                 };
2506                 if ($@) {
2507                         $can_do_switch = 0;
2508                 } else {
2509                         $rep->abort_report($pool);
2510                         $can_do_switch = 1;
2511                 }
2512                 $pool->clear;
2513         }
2514         $can_do_switch;
2517 sub skip_unknown_revs {
2518         my ($err) = @_;
2519         my $errno = $err->apr_err();
2520         # Maybe the branch we're tracking didn't
2521         # exist when the repo started, so it's
2522         # not an error if it doesn't, just continue
2523         #
2524         # Wonderfully consistent library, eh?
2525         # 160013 - svn:// and file://
2526         # 175002 - http(s)://
2527         # 175007 - http(s):// (this repo required authorization, too...)
2528         #   More codes may be discovered later...
2529         if ($errno == 175007 || $errno == 175002 || $errno == 160013) {
2530                 return;
2531         }
2532         die "Error from SVN, ($errno): ", $err->expanded_message,"\n";
2535 # svn_log_changed_path_t objects passed to get_log are likely to be
2536 # overwritten even if only the refs are copied to an external variable,
2537 # so we should dup the structures in their entirety.  Using an externally
2538 # passed pool (instead of our temporary and quickly cleared pool in
2539 # Git::SVN::Ra) does not help matters at all...
2540 sub dup_changed_paths {
2541         my ($paths) = @_;
2542         return undef unless $paths;
2543         my %ret;
2544         foreach my $p (keys %$paths) {
2545                 my $i = $paths->{$p};
2546                 my %s = map { $_ => $i->$_ }
2547                               qw/copyfrom_path copyfrom_rev action/;
2548                 $ret{$p} = \%s;
2549         }
2550         \%ret;
2553 package Git::SVN::Log;
2554 use strict;
2555 use warnings;
2556 use POSIX qw/strftime/;
2557 use vars qw/$TZ $limit $color $pager $non_recursive $verbose $oneline
2558             %rusers $show_commit $incremental/;
2559 my $l_fmt;
2561 sub cmt_showable {
2562         my ($c) = @_;
2563         return 1 if defined $c->{r};
2564         if ($c->{l} && $c->{l}->[-1] eq "...\n" &&
2565                                 $c->{a_raw} =~ /\@([a-f\d\-]+)>$/) {
2566                 my @log = command(qw/cat-file commit/, $c->{c});
2567                 shift @log while ($log[0] ne "\n");
2568                 shift @log;
2569                 @{$c->{l}} = grep !/^git-svn-id: /, @log;
2571                 (undef, $c->{r}, undef) = ::extract_metadata(
2572                                 (grep(/^git-svn-id: /, @log))[-1]);
2573         }
2574         return defined $c->{r};
2577 sub log_use_color {
2578         return 1 if $color;
2579         my ($dc, $dcvar);
2580         $dcvar = 'color.diff';
2581         $dc = `git-config --get $dcvar`;
2582         if ($dc eq '') {
2583                 # nothing at all; fallback to "diff.color"
2584                 $dcvar = 'diff.color';
2585                 $dc = `git-config --get $dcvar`;
2586         }
2587         chomp($dc);
2588         if ($dc eq 'auto') {
2589                 my $pc;
2590                 $pc = `git-config --get color.pager`;
2591                 if ($pc eq '') {
2592                         # does not have it -- fallback to pager.color
2593                         $pc = `git-config --bool --get pager.color`;
2594                 }
2595                 else {
2596                         $pc = `git-config --bool --get color.pager`;
2597                         if ($?) {
2598                                 $pc = 'false';
2599                         }
2600                 }
2601                 chomp($pc);
2602                 if (-t *STDOUT || (defined $pager && $pc eq 'true')) {
2603                         return ($ENV{TERM} && $ENV{TERM} ne 'dumb');
2604                 }
2605                 return 0;
2606         }
2607         return 0 if $dc eq 'never';
2608         return 1 if $dc eq 'always';
2609         chomp($dc = `git-config --bool --get $dcvar`);
2610         return ($dc eq 'true');
2613 sub git_svn_log_cmd {
2614         my ($r_min, $r_max) = @_;
2615         my $gs = Git::SVN->_new;
2616         my @cmd = (qw/log --abbrev-commit --pretty=raw --default/,
2617                    $gs->refname);
2618         push @cmd, '-r' unless $non_recursive;
2619         push @cmd, qw/--raw --name-status/ if $verbose;
2620         push @cmd, '--color' if log_use_color();
2621         return @cmd unless defined $r_max;
2622         if ($r_max == $r_min) {
2623                 push @cmd, '--max-count=1';
2624                 if (my $c = $gs->rev_db_get($r_max)) {
2625                         push @cmd, $c;
2626                 }
2627         } else {
2628                 my ($c_min, $c_max);
2629                 $c_max = $gs->rev_db_get($r_max);
2630                 $c_min = $gs->rev_db_get($r_min);
2631                 if (defined $c_min && defined $c_max) {
2632                         if ($r_max > $r_max) {
2633                                 push @cmd, "$c_min..$c_max";
2634                         } else {
2635                                 push @cmd, "$c_max..$c_min";
2636                         }
2637                 } elsif ($r_max > $r_min) {
2638                         push @cmd, $c_max;
2639                 } else {
2640                         push @cmd, $c_min;
2641                 }
2642         }
2643         return @cmd;
2646 # adapted from pager.c
2647 sub config_pager {
2648         $pager ||= $ENV{GIT_PAGER} || $ENV{PAGER};
2649         if (!defined $pager) {
2650                 $pager = 'less';
2651         } elsif (length $pager == 0 || $pager eq 'cat') {
2652                 $pager = undef;
2653         }
2656 sub run_pager {
2657         return unless -t *STDOUT;
2658         pipe my $rfd, my $wfd or return;
2659         defined(my $pid = fork) or ::fatal "Can't fork: $!\n";
2660         if (!$pid) {
2661                 open STDOUT, '>&', $wfd or
2662                                      ::fatal "Can't redirect to stdout: $!\n";
2663                 return;
2664         }
2665         open STDIN, '<&', $rfd or ::fatal "Can't redirect stdin: $!\n";
2666         $ENV{LESS} ||= 'FRSX';
2667         exec $pager or ::fatal "Can't run pager: $! ($pager)\n";
2670 sub tz_to_s_offset {
2671         my ($tz) = @_;
2672         $tz =~ s/(\d\d)$//;
2673         return ($1 * 60) + ($tz * 3600);
2676 sub get_author_info {
2677         my ($dest, $author, $t, $tz) = @_;
2678         $author =~ s/(?:^\s*|\s*$)//g;
2679         $dest->{a_raw} = $author;
2680         my $au;
2681         if ($::_authors) {
2682                 $au = $rusers{$author} || undef;
2683         }
2684         if (!$au) {
2685                 ($au) = ($author =~ /<([^>]+)\@[^>]+>$/);
2686         }
2687         $dest->{t} = $t;
2688         $dest->{tz} = $tz;
2689         $dest->{a} = $au;
2690         # Date::Parse isn't in the standard Perl distro :(
2691         if ($tz =~ s/^\+//) {
2692                 $t += tz_to_s_offset($tz);
2693         } elsif ($tz =~ s/^\-//) {
2694                 $t -= tz_to_s_offset($tz);
2695         }
2696         $dest->{t_utc} = $t;
2699 sub process_commit {
2700         my ($c, $r_min, $r_max, $defer) = @_;
2701         if (defined $r_min && defined $r_max) {
2702                 if ($r_min == $c->{r} && $r_min == $r_max) {
2703                         show_commit($c);
2704                         return 0;
2705                 }
2706                 return 1 if $r_min == $r_max;
2707                 if ($r_min < $r_max) {
2708                         # we need to reverse the print order
2709                         return 0 if (defined $limit && --$limit < 0);
2710                         push @$defer, $c;
2711                         return 1;
2712                 }
2713                 if ($r_min != $r_max) {
2714                         return 1 if ($r_min < $c->{r});
2715                         return 1 if ($r_max > $c->{r});
2716                 }
2717         }
2718         return 0 if (defined $limit && --$limit < 0);
2719         show_commit($c);
2720         return 1;
2723 sub show_commit {
2724         my $c = shift;
2725         if ($oneline) {
2726                 my $x = "\n";
2727                 if (my $l = $c->{l}) {
2728                         while ($l->[0] =~ /^\s*$/) { shift @$l }
2729                         $x = $l->[0];
2730                 }
2731                 $l_fmt ||= 'A' . length($c->{r});
2732                 print 'r',pack($l_fmt, $c->{r}),' | ';
2733                 print "$c->{c} | " if $show_commit;
2734                 print $x;
2735         } else {
2736                 show_commit_normal($c);
2737         }
2740 sub show_commit_changed_paths {
2741         my ($c) = @_;
2742         return unless $c->{changed};
2743         print "Changed paths:\n", @{$c->{changed}};
2746 sub show_commit_normal {
2747         my ($c) = @_;
2748         print '-' x72, "\nr$c->{r} | ";
2749         print "$c->{c} | " if $show_commit;
2750         print "$c->{a} | ", strftime("%Y-%m-%d %H:%M:%S %z (%a, %d %b %Y)",
2751                                  localtime($c->{t_utc})), ' | ';
2752         my $nr_line = 0;
2754         if (my $l = $c->{l}) {
2755                 while ($l->[$#$l] eq "\n" && $#$l > 0
2756                                           && $l->[($#$l - 1)] eq "\n") {
2757                         pop @$l;
2758                 }
2759                 $nr_line = scalar @$l;
2760                 if (!$nr_line) {
2761                         print "1 line\n\n\n";
2762                 } else {
2763                         if ($nr_line == 1) {
2764                                 $nr_line = '1 line';
2765                         } else {
2766                                 $nr_line .= ' lines';
2767                         }
2768                         print $nr_line, "\n";
2769                         show_commit_changed_paths($c);
2770                         print "\n";
2771                         print $_ foreach @$l;
2772                 }
2773         } else {
2774                 print "1 line\n";
2775                 show_commit_changed_paths($c);
2776                 print "\n";
2778         }
2779         foreach my $x (qw/raw diff/) {
2780                 if ($c->{$x}) {
2781                         print "\n";
2782                         print $_ foreach @{$c->{$x}}
2783                 }
2784         }
2787 sub cmd_show_log {
2788         my (@args) = @_;
2789         my ($r_min, $r_max);
2790         my $r_last = -1; # prevent dupes
2791         if (defined $TZ) {
2792                 $ENV{TZ} = $TZ;
2793         } else {
2794                 delete $ENV{TZ};
2795         }
2796         if (defined $::_revision) {
2797                 if ($::_revision =~ /^(\d+):(\d+)$/) {
2798                         ($r_min, $r_max) = ($1, $2);
2799                 } elsif ($::_revision =~ /^\d+$/) {
2800                         $r_min = $r_max = $::_revision;
2801                 } else {
2802                         ::fatal "-r$::_revision is not supported, use ",
2803                                 "standard \'git log\' arguments instead\n";
2804                 }
2805         }
2807         config_pager();
2808         @args = (git_svn_log_cmd($r_min, $r_max), @args);
2809         my $log = command_output_pipe(@args);
2810         run_pager();
2811         my (@k, $c, $d);
2812         my $esc_color = qr/(?:\033\[(?:(?:\d+;)*\d*)?m)*/;
2813         while (<$log>) {
2814                 if (/^${esc_color}commit ($::sha1_short)/o) {
2815                         my $cmt = $1;
2816                         if ($c && cmt_showable($c) && $c->{r} != $r_last) {
2817                                 $r_last = $c->{r};
2818                                 process_commit($c, $r_min, $r_max, \@k) or
2819                                                                 goto out;
2820                         }
2821                         $d = undef;
2822                         $c = { c => $cmt };
2823                 } elsif (/^${esc_color}author (.+) (\d+) ([\-\+]?\d+)$/o) {
2824                         get_author_info($c, $1, $2, $3);
2825                 } elsif (/^${esc_color}(?:tree|parent|committer) /o) {
2826                         # ignore
2827                 } elsif (/^${esc_color}:\d{6} \d{6} $::sha1_short/o) {
2828                         push @{$c->{raw}}, $_;
2829                 } elsif (/^${esc_color}[ACRMDT]\t/) {
2830                         # we could add $SVN->{svn_path} here, but that requires
2831                         # remote access at the moment (repo_path_split)...
2832                         s#^(${esc_color})([ACRMDT])\t#$1   $2 #o;
2833                         push @{$c->{changed}}, $_;
2834                 } elsif (/^${esc_color}diff /o) {
2835                         $d = 1;
2836                         push @{$c->{diff}}, $_;
2837                 } elsif ($d) {
2838                         push @{$c->{diff}}, $_;
2839                 } elsif (/^${esc_color}    (git-svn-id:.+)$/o) {
2840                         ($c->{url}, $c->{r}, undef) = ::extract_metadata($1);
2841                 } elsif (s/^${esc_color}    //o) {
2842                         push @{$c->{l}}, $_;
2843                 }
2844         }
2845         if ($c && defined $c->{r} && $c->{r} != $r_last) {
2846                 $r_last = $c->{r};
2847                 process_commit($c, $r_min, $r_max, \@k);
2848         }
2849         if (@k) {
2850                 my $swap = $r_max;
2851                 $r_max = $r_min;
2852                 $r_min = $swap;
2853                 process_commit($_, $r_min, $r_max) foreach reverse @k;
2854         }
2855 out:
2856         close $log;
2857         print '-' x72,"\n" unless $incremental || $oneline;
2860 package Git::SVN::Migration;
2861 # these version numbers do NOT correspond to actual version numbers
2862 # of git nor git-svn.  They are just relative.
2864 # v0 layout: .git/$id/info/url, refs/heads/$id-HEAD
2866 # v1 layout: .git/$id/info/url, refs/remotes/$id
2868 # v2 layout: .git/svn/$id/info/url, refs/remotes/$id
2870 # v3 layout: .git/svn/$id, refs/remotes/$id
2871 #            - info/url may remain for backwards compatibility
2872 #            - this is what we migrate up to this layout automatically,
2873 #            - this will be used by git svn init on single branches
2875 # v4 layout: .git/svn/$repo_id/$id, refs/remotes/$repo_id/$id
2876 #            - this is only created for newly multi-init-ed
2877 #              repositories.  Similar in spirit to the
2878 #              --use-separate-remotes option in git-clone (now default)
2879 #            - we do not automatically migrate to this (following
2880 #              the example set by core git)
2881 use strict;
2882 use warnings;
2883 use Carp qw/croak/;
2884 use File::Path qw/mkpath/;
2885 use File::Basename qw/dirname basename/;
2886 use vars qw/$_minimize/;
2888 sub migrate_from_v0 {
2889         my $git_dir = $ENV{GIT_DIR};
2890         return undef unless -d $git_dir;
2891         my ($fh, $ctx) = command_output_pipe(qw/rev-parse --symbolic --all/);
2892         my $migrated = 0;
2893         while (<$fh>) {
2894                 chomp;
2895                 my ($id, $orig_ref) = ($_, $_);
2896                 next unless $id =~ s#^refs/heads/(.+)-HEAD$#$1#;
2897                 next unless -f "$git_dir/$id/info/url";
2898                 my $new_ref = "refs/remotes/$id";
2899                 if (::verify_ref("$new_ref^0")) {
2900                         print STDERR "W: $orig_ref is probably an old ",
2901                                      "branch used by an ancient version of ",
2902                                      "git-svn.\n",
2903                                      "However, $new_ref also exists.\n",
2904                                      "We will not be able ",
2905                                      "to use this branch until this ",
2906                                      "ambiguity is resolved.\n";
2907                         next;
2908                 }
2909                 print STDERR "Migrating from v0 layout...\n" if !$migrated;
2910                 print STDERR "Renaming ref: $orig_ref => $new_ref\n";
2911                 command_noisy('update-ref', $new_ref, $orig_ref);
2912                 command_noisy('update-ref', '-d', $orig_ref, $orig_ref);
2913                 $migrated++;
2914         }
2915         command_close_pipe($fh, $ctx);
2916         print STDERR "Done migrating from v0 layout...\n" if $migrated;
2917         $migrated;
2920 sub migrate_from_v1 {
2921         my $git_dir = $ENV{GIT_DIR};
2922         my $migrated = 0;
2923         return $migrated unless -d $git_dir;
2924         my $svn_dir = "$git_dir/svn";
2926         # just in case somebody used 'svn' as their $id at some point...
2927         return $migrated if -d $svn_dir && ! -f "$svn_dir/info/url";
2929         print STDERR "Migrating from a git-svn v1 layout...\n";
2930         mkpath([$svn_dir]);
2931         print STDERR "Data from a previous version of git-svn exists, but\n\t",
2932                      "$svn_dir\n\t(required for this version ",
2933                      "($::VERSION) of git-svn) does not. exist\n";
2934         my ($fh, $ctx) = command_output_pipe(qw/rev-parse --symbolic --all/);
2935         while (<$fh>) {
2936                 my $x = $_;
2937                 next unless $x =~ s#^refs/remotes/##;
2938                 chomp $x;
2939                 next unless -f "$git_dir/$x/info/url";
2940                 my $u = eval { ::file_to_s("$git_dir/$x/info/url") };
2941                 next unless $u;
2942                 my $dn = dirname("$git_dir/svn/$x");
2943                 mkpath([$dn]) unless -d $dn;
2944                 if ($x eq 'svn') { # they used 'svn' as GIT_SVN_ID:
2945                         mkpath(["$git_dir/svn/svn"]);
2946                         print STDERR " - $git_dir/$x/info => ",
2947                                         "$git_dir/svn/$x/info\n";
2948                         rename "$git_dir/$x/info", "$git_dir/svn/$x/info" or
2949                                croak "$!: $x";
2950                         # don't worry too much about these, they probably
2951                         # don't exist with repos this old (save for index,
2952                         # and we can easily regenerate that)
2953                         foreach my $f (qw/unhandled.log index .rev_db/) {
2954                                 rename "$git_dir/$x/$f", "$git_dir/svn/$x/$f";
2955                         }
2956                 } else {
2957                         print STDERR " - $git_dir/$x => $git_dir/svn/$x\n";
2958                         rename "$git_dir/$x", "$git_dir/svn/$x" or
2959                                croak "$!: $x";
2960                 }
2961                 $migrated++;
2962         }
2963         command_close_pipe($fh, $ctx);
2964         print STDERR "Done migrating from a git-svn v1 layout\n";
2965         $migrated;
2968 sub read_old_urls {
2969         my ($l_map, $pfx, $path) = @_;
2970         my @dir;
2971         foreach (<$path/*>) {
2972                 if (-r "$_/info/url") {
2973                         $pfx .= '/' if $pfx && $pfx !~ m!/$!;
2974                         my $ref_id = $pfx . basename $_;
2975                         my $url = ::file_to_s("$_/info/url");
2976                         $l_map->{$ref_id} = $url;
2977                 } elsif (-d $_) {
2978                         push @dir, $_;
2979                 }
2980         }
2981         foreach (@dir) {
2982                 my $x = $_;
2983                 $x =~ s!^\Q$ENV{GIT_DIR}\E/svn/!!o;
2984                 read_old_urls($l_map, $x, $_);
2985         }
2988 sub migrate_from_v2 {
2989         my @cfg = command(qw/config -l/);
2990         return if grep /^svn-remote\..+\.url=/, @cfg;
2991         my %l_map;
2992         read_old_urls(\%l_map, '', "$ENV{GIT_DIR}/svn");
2993         my $migrated = 0;
2995         foreach my $ref_id (sort keys %l_map) {
2996                 eval { Git::SVN->init($l_map{$ref_id}, '', undef, $ref_id) };
2997                 if ($@) {
2998                         Git::SVN->init($l_map{$ref_id}, '', $ref_id, $ref_id);
2999                 }
3000                 $migrated++;
3001         }
3002         $migrated;
3005 sub minimize_connections {
3006         my $r = Git::SVN::read_all_remotes();
3007         my $new_urls = {};
3008         my $root_repos = {};
3009         foreach my $repo_id (keys %$r) {
3010                 my $url = $r->{$repo_id}->{url} or next;
3011                 my $fetch = $r->{$repo_id}->{fetch} or next;
3012                 my $ra = Git::SVN::Ra->new($url);
3014                 # skip existing cases where we already connect to the root
3015                 if (($ra->{url} eq $ra->{repos_root}) ||
3016                     (Git::SVN::sanitize_remote_name($ra->{repos_root}) eq
3017                      $repo_id)) {
3018                         $root_repos->{$ra->{url}} = $repo_id;
3019                         next;
3020                 }
3022                 my $root_ra = Git::SVN::Ra->new($ra->{repos_root});
3023                 my $root_path = $ra->{url};
3024                 $root_path =~ s#^\Q$ra->{repos_root}\E/*##;
3025                 foreach my $path (keys %$fetch) {
3026                         my $ref_id = $fetch->{$path};
3027                         my $gs = Git::SVN->new($ref_id, $repo_id, $path);
3029                         # make sure we can read when connecting to
3030                         # a higher level of a repository
3031                         my ($last_rev, undef) = $gs->last_rev_commit;
3032                         if (!defined $last_rev) {
3033                                 $last_rev = eval {
3034                                         $root_ra->get_latest_revnum;
3035                                 };
3036                                 next if $@;
3037                         }
3038                         my $new = $root_path;
3039                         $new .= length $path ? "/$path" : '';
3040                         eval {
3041                                 $root_ra->get_log([$new], $last_rev, $last_rev,
3042                                                   0, 0, 1, sub { });
3043                         };
3044                         next if $@;
3045                         $new_urls->{$ra->{repos_root}}->{$new} =
3046                                 { ref_id => $ref_id,
3047                                   old_repo_id => $repo_id,
3048                                   old_path => $path };
3049                 }
3050         }
3052         my @emptied;
3053         foreach my $url (keys %$new_urls) {
3054                 # see if we can re-use an existing [svn-remote "repo_id"]
3055                 # instead of creating a(n ugly) new section:
3056                 my $repo_id = $root_repos->{$url} ||
3057                               Git::SVN::sanitize_remote_name($url);
3059                 my $fetch = $new_urls->{$url};
3060                 foreach my $path (keys %$fetch) {
3061                         my $x = $fetch->{$path};
3062                         Git::SVN->init($url, $path, $repo_id, $x->{ref_id});
3063                         my $pfx = "svn-remote.$x->{old_repo_id}";
3065                         my $old_fetch = quotemeta("$x->{old_path}:".
3066                                                   "refs/remotes/$x->{ref_id}");
3067                         command_noisy(qw/config --unset/,
3068                                       "$pfx.fetch", '^'. $old_fetch . '$');
3069                         delete $r->{$x->{old_repo_id}}->
3070                                {fetch}->{$x->{old_path}};
3071                         if (!keys %{$r->{$x->{old_repo_id}}->{fetch}}) {
3072                                 command_noisy(qw/config --unset/,
3073                                               "$pfx.url");
3074                                 push @emptied, $x->{old_repo_id}
3075                         }
3076                 }
3077         }
3078         if (@emptied) {
3079                 my $file = $ENV{GIT_CONFIG} || $ENV{GIT_CONFIG_LOCAL} ||
3080                            "$ENV{GIT_DIR}/config";
3081                 print STDERR <<EOF;
3082 The following [svn-remote] sections in your config file ($file) are empty
3083 and can be safely removed:
3084 EOF
3085                 print STDERR "[svn-remote \"$_\"]\n" foreach @emptied;
3086         }
3089 sub migration_check {
3090         migrate_from_v0();
3091         migrate_from_v1();
3092         migrate_from_v2();
3093         minimize_connections() if $_minimize;
3096 package Git::IndexInfo;
3097 use strict;
3098 use warnings;
3099 use Git qw/command_input_pipe command_close_pipe/;
3101 sub new {
3102         my ($class) = @_;
3103         my ($gui, $ctx) = command_input_pipe(qw/update-index -z --index-info/);
3104         bless { gui => $gui, ctx => $ctx, nr => 0}, $class;
3107 sub remove {
3108         my ($self, $path) = @_;
3109         if (print { $self->{gui} } '0 ', 0 x 40, "\t", $path, "\0") {
3110                 return ++$self->{nr};
3111         }
3112         undef;
3115 sub update {
3116         my ($self, $mode, $hash, $path) = @_;
3117         if (print { $self->{gui} } $mode, ' ', $hash, "\t", $path, "\0") {
3118                 return ++$self->{nr};
3119         }
3120         undef;
3123 sub DESTROY {
3124         my ($self) = @_;
3125         command_close_pipe($self->{gui}, $self->{ctx});
3128 package Git::SVN::GlobSpec;
3129 use strict;
3130 use warnings;
3132 sub new {
3133         my ($class, $glob) = @_;
3134         warn "glob: $glob\n";
3135         my $re = $glob;
3136         $re =~ s!/+$!!g; # no need for trailing slashes
3137         my $nr = ($re =~ s!^(.*/?)\*(/?.*)$!\(\[^/\]+\)!g);
3138         my ($left, $right) = ($1, $2);
3139         if ($nr > 1) {
3140                 warn "Only one '*' wildcard expansion ",
3141                      "is supported (got $nr): '$glob'\n";
3142         } elsif ($nr == 0) {
3143                 warn "One '*' is needed for glob: '$glob'\n";
3144         }
3145         $re = quotemeta($left) . $re . quotemeta($right);
3146         $left =~ s!/+$!!g;
3147         $right =~ s!^/+!!g;
3148         bless { left => $left, right => $right,
3149                 regex => qr/$re/, glob => $glob }, $class;
3152 sub full_path {
3153         my ($self, $path) = @_;
3154         return (length $self->{left} ? "$self->{left}/" : '') .
3155                $path . (length $self->{right} ? "/$self->{right}" : '');
3158 __END__
3160 Data structures:
3163 $remotes = { # returned by read_all_remotes()
3164         'svn' => {
3165                 # svn-remote.svn.url=https://svn.musicpd.org
3166                 url => 'https://svn.musicpd.org',
3167                 # svn-remote.svn.fetch=mpd/trunk:trunk
3168                 fetch => {
3169                         'mpd/trunk' => 'trunk',
3170                 },
3171                 # svn-remote.svn.tags=mpd/tags/*:tags/*
3172                 tags => {
3173                         path => {
3174                                 left => 'mpd/tags',
3175                                 right => '',
3176                                 regex => qr!mpd/tags/([^/]+)$!,
3177                                 glob => 'tags/*',
3178                         },
3179                         ref => {
3180                                 left => 'tags',
3181                                 right => '',
3182                                 regex => qr!tags/([^/]+)$!,
3183                                 glob => 'tags/*',
3184                         },
3185                 }
3186         }
3187 };
3189 $log_entry hashref as returned by libsvn_log_entry()
3191         log => 'whitespace-formatted log entry
3192 ',                                              # trailing newline is preserved
3193         revision => '8',                        # integer
3194         date => '2004-02-24T17:01:44.108345Z',  # commit date
3195         author => 'committer name'
3196 };
3199 # this is generated by generate_diff();
3200 @mods = array of diff-index line hashes, each element represents one line
3201         of diff-index output
3203 diff-index line ($m hash)
3205         mode_a => first column of diff-index output, no leading ':',
3206         mode_b => second column of diff-index output,
3207         sha1_b => sha1sum of the final blob,
3208         chg => change type [MCRADT],
3209         file_a => original file name of a file (iff chg is 'C' or 'R')
3210         file_b => new/current file name of a file (any chg)
3214 # retval of read_url_paths{,_all}();
3215 $l_map = {
3216         # repository root url
3217         'https://svn.musicpd.org' => {
3218                 # repository path               # GIT_SVN_ID
3219                 'mpd/trunk'             =>      'trunk',
3220                 'mpd/tags/0.11.5'       =>      'tags/0.11.5',
3221         },
3224 Notes:
3225         I don't trust the each() function on unless I created %hash myself
3226         because the internal iterator may not have started at base.