Code

git-svn: enable --minimize to simplify the config and connections
[git.git] / git-svn.perl
1 #!/usr/bin/env perl
2 # Copyright (C) 2006, Eric Wong <normalperson@yhbt.net>
3 # License: GPL v2 or later
4 use warnings;
5 use strict;
6 use vars qw/    $AUTHOR $VERSION
7                 $SVN_URL
8                 $GIT_SVN_INDEX $GIT_SVN
9                 $GIT_DIR $GIT_SVN_DIR $REVDB
10                 $_follow_parent $sha1 $sha1_short $_revision
11                 $_cp_remote $_upgrade $_rmdir $_q $_cp_similarity
12                 $_find_copies_harder $_l $_authors %users/;
13 $AUTHOR = 'Eric Wong <normalperson@yhbt.net>';
14 $VERSION = '@@GIT_VERSION@@';
16 $ENV{GIT_DIR} ||= '.git';
17 $Git::SVN::default_repo_id = $ENV{GIT_SVN_ID} || 'git-svn';
19 my $LC_ALL = $ENV{LC_ALL};
20 $Git::SVN::Log::TZ = $ENV{TZ};
21 # make sure the svn binary gives consistent output between locales and TZs:
22 $ENV{TZ} = 'UTC';
23 $ENV{LC_ALL} = 'C';
24 $| = 1; # unbuffer STDOUT
26 sub fatal (@) { print STDERR @_; exit 1 }
27 require SVN::Core; # use()-ing this causes segfaults for me... *shrug*
28 require SVN::Ra;
29 require SVN::Delta;
30 if ($SVN::Core::VERSION lt '1.1.0') {
31         fatal "Need SVN::Core 1.1.0 or better (got $SVN::Core::VERSION)\n";
32 }
33 push @Git::SVN::Ra::ISA, 'SVN::Ra';
34 push @SVN::Git::Editor::ISA, 'SVN::Delta::Editor';
35 push @SVN::Git::Fetcher::ISA, 'SVN::Delta::Editor';
36 use Carp qw/croak/;
37 use IO::File qw//;
38 use File::Basename qw/dirname basename/;
39 use File::Path qw/mkpath/;
40 use Getopt::Long qw/:config gnu_getopt no_ignore_case auto_abbrev pass_through/;
41 use IPC::Open3;
42 use Git;
44 BEGIN {
45         my $s;
46         foreach (qw/command command_oneline command_noisy command_output_pipe
47                     command_input_pipe command_close_pipe/) {
48                 $s .= "*SVN::Git::Editor::$_ = *SVN::Git::Fetcher::$_ = ".
49                       "*Git::SVN::Migration::$_ = ".
50                       "*Git::SVN::Log::$_ = *Git::SVN::$_ = *$_ = *Git::$_; ";
51         }
52         eval $s;
53 }
55 my ($SVN);
57 my $_optimize_commits = 1 unless $ENV{GIT_SVN_NO_OPTIMIZE_COMMITS};
58 $sha1 = qr/[a-f\d]{40}/;
59 $sha1_short = qr/[a-f\d]{4,40}/;
60 my ($_stdin, $_help, $_edit,
61         $_repack, $_repack_nr, $_repack_flags,
62         $_message, $_file, $_no_metadata,
63         $_template, $_shared,
64         $_version, $_upgrade,
65         $_merge, $_strategy, $_dry_run,
66         $_prefix);
68 my %remote_opts = ( 'username=s' => \$Git::SVN::Prompt::_username,
69                     'config-dir=s' => \$Git::SVN::Ra::config_dir,
70                     'no-auth-cache' => \$Git::SVN::Prompt::_no_auth_cache );
71 my %fc_opts = ( 'follow-parent|follow' => \$_follow_parent,
72                 'authors-file|A=s' => \$_authors,
73                 'repack:i' => \$_repack,
74                 'no-metadata' => \$_no_metadata,
75                 'quiet|q' => \$_q,
76                 'repack-flags|repack-args|repack-opts=s' => \$_repack_flags,
77                 %remote_opts );
79 my ($_trunk, $_tags, $_branches);
80 my %multi_opts = ( 'trunk|T=s' => \$_trunk,
81                 'tags|t=s' => \$_tags,
82                 'branches|b=s' => \$_branches );
83 my %init_opts = ( 'template=s' => \$_template, 'shared' => \$_shared );
84 my %cmt_opts = ( 'edit|e' => \$_edit,
85                 'rmdir' => \$_rmdir,
86                 'find-copies-harder' => \$_find_copies_harder,
87                 'l=i' => \$_l,
88                 'copy-similarity|C=i'=> \$_cp_similarity
89 );
91 my %cmd = (
92         fetch => [ \&cmd_fetch, "Download new revisions from SVN",
93                         { 'revision|r=s' => \$_revision, %fc_opts } ],
94         init => [ \&cmd_init, "Initialize a repo for tracking" .
95                           " (requires URL argument)",
96                           \%init_opts ],
97         dcommit => [ \&cmd_dcommit,
98                      'Commit several diffs to merge with upstream',
99                         { 'merge|m|M' => \$_merge,
100                           'strategy|s=s' => \$_strategy,
101                           'dry-run|n' => \$_dry_run,
102                         %cmt_opts, %fc_opts } ],
103         'set-tree' => [ \&cmd_set_tree,
104                         "Set an SVN repository to a git tree-ish",
105                         { 'stdin|' => \$_stdin, %cmt_opts, %fc_opts, } ],
106         'show-ignore' => [ \&cmd_show_ignore, "Show svn:ignore listings",
107                         { 'revision|r=i' => \$_revision } ],
108         rebuild => [ \&cmd_rebuild, "Rebuild git-svn metadata (after git clone)",
109                         { 'copy-remote|remote=s' => \$_cp_remote,
110                           'upgrade' => \$_upgrade } ],
111         'multi-init' => [ \&cmd_multi_init,
112                         'Initialize multiple trees (like git-svnimport)',
113                         { %multi_opts, %init_opts, %remote_opts,
114                          'revision|r=i' => \$_revision,
115                          'prefix=s' => \$_prefix,
116                         } ],
117         'multi-fetch' => [ \&cmd_multi_fetch,
118                         'Fetch multiple trees (like git-svnimport)',
119                         \%fc_opts ],
120         'migrate' => [ sub { },
121                        # no-op, we automatically run this anyways,
122                        'Migrate configuration/metadata/layout from
123                         previous versions of git-svn',
124                         \%remote_opts ],
125         'log' => [ \&Git::SVN::Log::cmd_show_log, 'Show commit logs',
126                         { 'limit=i' => \$Git::SVN::Log::limit,
127                           'revision|r=s' => \$_revision,
128                           'verbose|v' => \$Git::SVN::Log::verbose,
129                           'incremental' => \$Git::SVN::Log::incremental,
130                           'oneline' => \$Git::SVN::Log::oneline,
131                           'show-commit' => \$Git::SVN::Log::show_commit,
132                           'non-recursive' => \$Git::SVN::Log::non_recursive,
133                           'authors-file|A=s' => \$_authors,
134                           'color' => \$Git::SVN::Log::color,
135                           'pager=s' => \$Git::SVN::Log::pager,
136                         } ],
137         'commit-diff' => [ \&cmd_commit_diff,
138                            'Commit a diff between two trees',
139                         { 'message|m=s' => \$_message,
140                           'file|F=s' => \$_file,
141                           'revision|r=s' => \$_revision,
142                         %cmt_opts } ],
143 );
145 my $cmd;
146 for (my $i = 0; $i < @ARGV; $i++) {
147         if (defined $cmd{$ARGV[$i]}) {
148                 $cmd = $ARGV[$i];
149                 splice @ARGV, $i, 1;
150                 last;
151         }
152 };
154 my %opts = %{$cmd{$cmd}->[2]} if (defined $cmd);
156 read_repo_config(\%opts);
157 my $rv = GetOptions(%opts, 'help|H|h' => \$_help,
158                                 'version|V' => \$_version,
159                                 'minimize-connections' =>
160                                   \$Git::SVN::Migration::_minimize,
161                                 'id|i=s' => \$Git::SVN::default_repo_id);
162 exit 1 if (!$rv && $cmd ne 'log');
164 usage(0) if $_help;
165 version() if $_version;
166 usage(1) unless defined $cmd;
167 load_authors() if $_authors;
168 unless ($cmd =~ /^(?:init|rebuild|multi-init|commit-diff)$/) {
169         Git::SVN::Migration::migration_check();
171 $cmd{$cmd}->[0]->(@ARGV);
172 exit 0;
174 ####################### primary functions ######################
175 sub usage {
176         my $exit = shift || 0;
177         my $fd = $exit ? \*STDERR : \*STDOUT;
178         print $fd <<"";
179 git-svn - bidirectional operations between a single Subversion tree and git
180 Usage: $0 <command> [options] [arguments]\n
182         print $fd "Available commands:\n" unless $cmd;
184         foreach (sort keys %cmd) {
185                 next if $cmd && $cmd ne $_;
186                 print $fd '  ',pack('A17',$_),$cmd{$_}->[1],"\n";
187                 foreach (keys %{$cmd{$_}->[2]}) {
188                         # prints out arguments as they should be passed:
189                         my $x = s#[:=]s$## ? '<arg>' : s#[:=]i$## ? '<num>' : '';
190                         print $fd ' ' x 21, join(', ', map { length $_ > 1 ?
191                                                         "--$_" : "-$_" }
192                                                 split /\|/,$_)," $x\n";
193                 }
194         }
195         print $fd <<"";
196 \nGIT_SVN_ID may be set in the environment or via the --id/-i switch to an
197 arbitrary identifier if you're tracking multiple SVN branches/repositories in
198 one git repository and want to keep them separate.  See git-svn(1) for more
199 information.
201         exit $exit;
204 sub version {
205         print "git-svn version $VERSION (svn $SVN::Core::VERSION)\n";
206         exit 0;
209 sub cmd_rebuild {
210         my $url = shift;
211         my $gs = $url ? Git::SVN->init($url)
212                       : eval { Git::SVN->new };
213         $gs ||= Git::SVN->_new;
214         if (!verify_ref($gs->refname.'^0')) {
215                 $gs->copy_remote_ref;
216         }
218         my ($rev_list, $ctx) = command_output_pipe("rev-list", $gs->refname);
219         my $latest;
220         my $svn_uuid;
221         while (<$rev_list>) {
222                 chomp;
223                 my $c = $_;
224                 fatal "Non-SHA1: $c\n" unless $c =~ /^$sha1$/o;
225                 my ($url, $rev, $uuid) = cmt_metadata($c);
227                 # ignore merges (from set-tree)
228                 next if (!defined $rev || !$uuid);
230                 # if we merged or otherwise started elsewhere, this is
231                 # how we break out of it
232                 if ((defined $svn_uuid && ($uuid ne $svn_uuid)) ||
233                     ($gs->{url} && $url && ($url ne $gs->{url}))) {
234                         next;
235                 }
237                 unless (defined $latest) {
238                         if (!$gs->{url} && !$url) {
239                                 fatal "SVN repository location required\n";
240                         }
241                         $gs = Git::SVN->init($url);
242                         $latest = $rev;
243                 }
244                 $gs->rev_db_set($rev, $c);
245                 print "r$rev = $c\n";
246         }
247         command_close_pipe($rev_list, $ctx);
250 sub do_git_init_db {
251         unless (-d $ENV{GIT_DIR}) {
252                 my @init_db = ('init');
253                 push @init_db, "--template=$_template" if defined $_template;
254                 push @init_db, "--shared" if defined $_shared;
255                 command_noisy(@init_db);
256         }
259 sub cmd_init {
260         my $url = shift or die "SVN repository location required " .
261                                 "as a command-line argument\n";
262         if (my $repo_path = shift) {
263                 unless (-d $repo_path) {
264                         mkpath([$repo_path]);
265                 }
266                 chdir $repo_path or croak $!;
267                 $ENV{GIT_DIR} = $repo_path . "/.git";
268         }
269         do_git_init_db();
271         Git::SVN->init($url);
274 sub cmd_fetch {
275         my $gs = Git::SVN->new;
276         $gs->fetch(@_);
277         if ($gs->{last_commit} && !verify_ref('refs/heads/master^0')) {
278                 command_noisy(qw(update-ref refs/heads/master),
279                               $gs->{last_commit});
280         }
283 sub cmd_set_tree {
284         my (@commits) = @_;
285         if ($_stdin || !@commits) {
286                 print "Reading from stdin...\n";
287                 @commits = ();
288                 while (<STDIN>) {
289                         if (/\b($sha1_short)\b/o) {
290                                 unshift @commits, $1;
291                         }
292                 }
293         }
294         my @revs;
295         foreach my $c (@commits) {
296                 my @tmp = command('rev-parse',$c);
297                 if (scalar @tmp == 1) {
298                         push @revs, $tmp[0];
299                 } elsif (scalar @tmp > 1) {
300                         push @revs, reverse(command('rev-list',@tmp));
301                 } else {
302                         fatal "Failed to rev-parse $c\n";
303                 }
304         }
305         my $gs = Git::SVN->new;
306         my ($r_last, $cmt_last) = $gs->last_rev_commit;
307         $gs->fetch;
308         if ($r_last != $gs->{last_rev}) {
309                 fatal "There are new revisions that were fetched ",
310                       "and need to be merged (or acknowledged) ",
311                       "before committing.\nlast rev: $r_last\n",
312                       " current: $gs->{last_rev}\n";
313         }
314         $gs->set_tree($_) foreach @revs;
315         print "Done committing ",scalar @revs," revisions to SVN\n";
318 sub cmd_dcommit {
319         my $head = shift;
320         my $gs = Git::SVN->new;
321         $head ||= 'HEAD';
322         my @refs = command(qw/rev-list --no-merges/, $gs->refname."..$head");
323         my $last_rev;
324         foreach my $d (reverse @refs) {
325                 if (!verify_ref("$d~1")) {
326                         fatal "Commit $d\n",
327                               "has no parent commit, and therefore ",
328                               "nothing to diff against.\n",
329                               "You should be working from a repository ",
330                               "originally created by git-svn\n";
331                 }
332                 unless (defined $last_rev) {
333                         (undef, $last_rev, undef) = cmt_metadata("$d~1");
334                         unless (defined $last_rev) {
335                                 fatal "Unable to extract revision information ",
336                                       "from commit $d~1\n";
337                         }
338                 }
339                 if ($_dry_run) {
340                         print "diff-tree $d~1 $d\n";
341                 } else {
342                         my $log = get_commit_entry($d)->{log};
343                         my $ra = $gs->ra;
344                         my $pool = SVN::Pool->new;
345                         my %ed_opts = ( r => $last_rev,
346                                         ra => $ra->dup,
347                                         svn_path => $ra->{svn_path} );
348                         my $ed = SVN::Git::Editor->new(\%ed_opts,
349                                          $ra->get_commit_editor($log,
350                                          sub { print "Committed r$_[0]\n";
351                                                $last_rev = $_[0]; }),
352                                          $pool);
353                         my $mods = $ed->apply_diff("$d~1", $d);
354                         if (@$mods == 0) {
355                                 print "No changes\n$d~1 == $d\n";
356                         }
357                 }
358         }
359         return if $_dry_run;
360         $gs->fetch;
361         # we always want to rebase against the current HEAD, not any
362         # head that was passed to us
363         my @diff = command('diff-tree', 'HEAD', $gs->refname, '--');
364         my @finish;
365         if (@diff) {
366                 @finish = qw/rebase/;
367                 push @finish, qw/--merge/ if $_merge;
368                 push @finish, "--strategy=$_strategy" if $_strategy;
369                 print STDERR "W: HEAD and ", $gs->refname, " differ, ",
370                              "using @finish:\n", "@diff";
371         } else {
372                 print "No changes between current HEAD and ",
373                       $gs->refname, "\nResetting to the latest ",
374                       $gs->refname, "\n";
375                 @finish = qw/reset --mixed/;
376         }
377         command_noisy(@finish, $gs->refname);
380 sub cmd_show_ignore {
381         my $gs = Git::SVN->new;
382         my $r = (defined $_revision ? $_revision : $gs->ra->get_latest_revnum);
383         $gs->traverse_ignore(\*STDOUT, '', $r);
386 sub cmd_multi_init {
387         my $url = shift;
388         unless (defined $_trunk || defined $_branches || defined $_tags) {
389                 usage(1);
390         }
391         do_git_init_db();
392         $_prefix = '' unless defined $_prefix;
393         $url =~ s#/+$## if defined $url;
394         if (defined $_trunk) {
395                 my $trunk_ref = $_prefix . 'trunk';
396                 # try both old-style and new-style lookups:
397                 my $gs_trunk = eval { Git::SVN->new($trunk_ref) };
398                 unless ($gs_trunk) {
399                         my ($trunk_url, $trunk_path) =
400                                               complete_svn_url($url, $_trunk);
401                         $gs_trunk = Git::SVN->init($trunk_url, $trunk_path,
402                                                    undef, $trunk_ref);
403                 }
404         }
405         return unless defined $_branches || defined $_tags;
406         my $ra = $url ? Git::SVN::Ra->new($url) : undef;
407         complete_url_ls_init($ra, $_branches, '--branches/-b', $_prefix);
408         complete_url_ls_init($ra, $_tags, '--tags/-t', $_prefix . 'tags/');
411 sub cmd_multi_fetch {
412         my @gs;
413         foreach (command(qw/config -l/)) {
414                 next unless m!^svn-remote\.(.+)\.fetch=
415                               \s*(.*)\s*:\s*refs/remotes/(.+)\s*$!x;
416                 my ($repo_id, $path, $ref_id) = ($1, $2, $3);
417                 push @gs, Git::SVN->new($ref_id, $repo_id, $path);
418         }
419         foreach (@gs) {
420                 $_->fetch;
421         }
424 # this command is special because it requires no metadata
425 sub cmd_commit_diff {
426         my ($ta, $tb, $url) = @_;
427         my $usage = "Usage: $0 commit-diff -r<revision> ".
428                     "<tree-ish> <tree-ish> [<URL>]\n";
429         fatal($usage) if (!defined $ta || !defined $tb);
430         if (!defined $url) {
431                 my $gs = eval { Git::SVN->new };
432                 if (!$gs) {
433                         fatal("Needed URL or usable git-svn --id in ",
434                               "the command-line\n", $usage);
435                 }
436                 $url = $gs->{url};
437         }
438         unless (defined $_revision) {
439                 fatal("-r|--revision is a required argument\n", $usage);
440         }
441         if (defined $_message && defined $_file) {
442                 fatal("Both --message/-m and --file/-F specified ",
443                       "for the commit message.\n",
444                       "I have no idea what you mean\n");
445         }
446         if (defined $_file) {
447                 $_message = file_to_s($_file);
448         } else {
449                 $_message ||= get_commit_entry($tb)->{log};
450         }
451         my $ra ||= Git::SVN::Ra->new($url);
452         my $r = $_revision;
453         if ($r eq 'HEAD') {
454                 $r = $ra->get_latest_revnum;
455         } elsif ($r !~ /^\d+$/) {
456                 die "revision argument: $r not understood by git-svn\n";
457         }
458         my $pool = SVN::Pool->new;
459         my %ed_opts = ( r => $r,
460                         ra => $ra->dup,
461                         svn_path => $ra->{svn_path} );
462         my $ed = SVN::Git::Editor->new(\%ed_opts,
463                                        $ra->get_commit_editor($_message,
464                                          sub { print "Committed r$_[0]\n" }),
465                                        $pool);
466         my $mods = $ed->apply_diff($ta, $tb);
467         if (@$mods == 0) {
468                 print "No changes\n$ta == $tb\n";
469         }
470         $pool->clear;
473 ########################### utility functions #########################
475 sub complete_svn_url {
476         my ($url, $path) = @_;
477         $path =~ s#/+$##;
478         if ($path !~ m#^[a-z\+]+://#) {
479                 if (!defined $url || $url !~ m#^[a-z\+]+://#) {
480                         fatal("E: '$path' is not a complete URL ",
481                               "and a separate URL is not specified\n");
482                 }
483                 return ($url, $path);
484         }
485         return ($path, '');
488 sub complete_url_ls_init {
489         my ($ra, $repo_path, $switch, $pfx) = @_;
490         unless ($repo_path) {
491                 print STDERR "W: $switch not specified\n";
492                 return;
493         }
494         $repo_path =~ s#/+$##;
495         if ($repo_path =~ m#^[a-z\+]+://#) {
496                 $ra = Git::SVN::Ra->new($repo_path);
497                 $repo_path = '';
498         } else {
499                 $repo_path =~ s#^/+##;
500                 unless ($ra) {
501                         fatal("E: '$repo_path' is not a complete URL ",
502                               "and a separate URL is not specified\n");
503                 }
504         }
505         my $r = defined $_revision ? $_revision : $ra->get_latest_revnum;
506         my ($dirent, undef, undef) = $ra->get_dir($repo_path, $r);
507         my $url = $ra->{url};
508         foreach my $d (sort keys %$dirent) {
509                 next if ($dirent->{$d}->kind != $SVN::Node::dir);
510                 my $path =  "$repo_path/$d";
511                 my $ref = "$pfx$d";
512                 my $gs = eval { Git::SVN->new($ref) };
513                 # don't try to init already existing refs
514                 unless ($gs) {
515                         print "init $url/$path => $ref\n";
516                         Git::SVN->init($url, $path, undef, $ref);
517                 }
518         }
521 sub verify_ref {
522         my ($ref) = @_;
523         eval { command_oneline([ 'rev-parse', '--verify', $ref ],
524                                { STDERR => 0 }); };
527 sub get_tree_from_treeish {
528         my ($treeish) = @_;
529         # $treeish can be a symbolic ref, too:
530         my $type = command_oneline(qw/cat-file -t/, $treeish);
531         my $expected;
532         while ($type eq 'tag') {
533                 ($treeish, $type) = command(qw/cat-file tag/, $treeish);
534         }
535         if ($type eq 'commit') {
536                 $expected = (grep /^tree /, command(qw/cat-file commit/,
537                                                     $treeish))[0];
538                 ($expected) = ($expected =~ /^tree ($sha1)$/o);
539                 die "Unable to get tree from $treeish\n" unless $expected;
540         } elsif ($type eq 'tree') {
541                 $expected = $treeish;
542         } else {
543                 die "$treeish is a $type, expected tree, tag or commit\n";
544         }
545         return $expected;
548 sub get_commit_entry {
549         my ($treeish) = shift;
550         my %log_entry = ( log => '', tree => get_tree_from_treeish($treeish) );
551         my $commit_editmsg = "$ENV{GIT_DIR}/COMMIT_EDITMSG";
552         my $commit_msg = "$ENV{GIT_DIR}/COMMIT_MSG";
553         open my $log_fh, '>', $commit_editmsg or croak $!;
555         my $type = command_oneline(qw/cat-file -t/, $treeish);
556         if ($type eq 'commit' || $type eq 'tag') {
557                 my ($msg_fh, $ctx) = command_output_pipe('cat-file',
558                                                          $type, $treeish);
559                 my $in_msg = 0;
560                 while (<$msg_fh>) {
561                         if (!$in_msg) {
562                                 $in_msg = 1 if (/^\s*$/);
563                         } elsif (/^git-svn-id: /) {
564                                 # skip this for now, we regenerate the
565                                 # correct one on re-fetch anyways
566                                 # TODO: set *:merge properties or like...
567                         } else {
568                                 print $log_fh $_ or croak $!;
569                         }
570                 }
571                 command_close_pipe($msg_fh, $ctx);
572         }
573         close $log_fh or croak $!;
575         if ($_edit || ($type eq 'tree')) {
576                 my $editor = $ENV{VISUAL} || $ENV{EDITOR} || 'vi';
577                 # TODO: strip out spaces, comments, like git-commit.sh
578                 system($editor, $commit_editmsg);
579         }
580         rename $commit_editmsg, $commit_msg or croak $!;
581         open $log_fh, '<', $commit_msg or croak $!;
582         { local $/; chomp($log_entry{log} = <$log_fh>); }
583         close $log_fh or croak $!;
584         unlink $commit_msg;
585         \%log_entry;
588 sub s_to_file {
589         my ($str, $file, $mode) = @_;
590         open my $fd,'>',$file or croak $!;
591         print $fd $str,"\n" or croak $!;
592         close $fd or croak $!;
593         chmod ($mode &~ umask, $file) if (defined $mode);
596 sub file_to_s {
597         my $file = shift;
598         open my $fd,'<',$file or croak "$!: file: $file\n";
599         local $/;
600         my $ret = <$fd>;
601         close $fd or croak $!;
602         $ret =~ s/\s*$//s;
603         return $ret;
606 # '<svn username> = real-name <email address>' mapping based on git-svnimport:
607 sub load_authors {
608         open my $authors, '<', $_authors or die "Can't open $_authors $!\n";
609         my $log = $cmd eq 'log';
610         while (<$authors>) {
611                 chomp;
612                 next unless /^(\S+?|\(no author\))\s*=\s*(.+?)\s*<(.+)>\s*$/;
613                 my ($user, $name, $email) = ($1, $2, $3);
614                 if ($log) {
615                         $Git::SVN::Log::rusers{"$name <$email>"} = $user;
616                 } else {
617                         $users{$user} = [$name, $email];
618                 }
619         }
620         close $authors or croak $!;
623 # convert GetOpt::Long specs for use by git-config
624 sub read_repo_config {
625         return unless -d $ENV{GIT_DIR};
626         my $opts = shift;
627         foreach my $o (keys %$opts) {
628                 my $v = $opts->{$o};
629                 my ($key) = ($o =~ /^([a-z\-]+)/);
630                 $key =~ s/-//g;
631                 my $arg = 'git-config';
632                 $arg .= ' --int' if ($o =~ /[:=]i$/);
633                 $arg .= ' --bool' if ($o !~ /[:=][sfi]$/);
634                 if (ref $v eq 'ARRAY') {
635                         chomp(my @tmp = `$arg --get-all svn.$key`);
636                         @$v = @tmp if @tmp;
637                 } else {
638                         chomp(my $tmp = `$arg --get svn.$key`);
639                         if ($tmp && !($arg =~ / --bool/ && $tmp eq 'false')) {
640                                 $$v = $tmp;
641                         }
642                 }
643         }
646 sub extract_metadata {
647         my $id = shift or return (undef, undef, undef);
648         my ($url, $rev, $uuid) = ($id =~ /^git-svn-id:\s(\S+?)\@(\d+)
649                                                         \s([a-f\d\-]+)$/x);
650         if (!defined $rev || !$uuid || !$url) {
651                 # some of the original repositories I made had
652                 # identifiers like this:
653                 ($rev, $uuid) = ($id =~/^git-svn-id:\s(\d+)\@([a-f\d\-]+)/);
654         }
655         return ($url, $rev, $uuid);
658 sub cmt_metadata {
659         return extract_metadata((grep(/^git-svn-id: /,
660                 command(qw/cat-file commit/, shift)))[-1]);
663 sub get_commit_time {
664         my $cmt = shift;
665         my $fh = command_output_pipe(qw/rev-list --pretty=raw -n1/, $cmt);
666         while (<$fh>) {
667                 /^committer\s(?:.+) (\d+) ([\-\+]?\d+)$/ or next;
668                 my ($s, $tz) = ($1, $2);
669                 if ($tz =~ s/^\+//) {
670                         $s += tz_to_s_offset($tz);
671                 } elsif ($tz =~ s/^\-//) {
672                         $s -= tz_to_s_offset($tz);
673                 }
674                 close $fh;
675                 return $s;
676         }
677         die "Can't get commit time for commit: $cmt\n";
680 sub tz_to_s_offset {
681         my ($tz) = @_;
682         $tz =~ s/(\d\d)$//;
683         return ($1 * 60) + ($tz * 3600);
686 package Git::SVN;
687 use strict;
688 use warnings;
689 use vars qw/$default_repo_id/;
690 use Carp qw/croak/;
691 use File::Path qw/mkpath/;
692 use IPC::Open3;
694 # properties that we do not log:
695 my %SKIP_PROP;
696 BEGIN {
697         %SKIP_PROP = map { $_ => 1 } qw/svn:wc:ra_dav:version-url
698                                         svn:special svn:executable
699                                         svn:entry:committed-rev
700                                         svn:entry:last-author
701                                         svn:entry:uuid
702                                         svn:entry:committed-date/;
705 sub read_all_remotes {
706         my $r = {};
707         foreach (grep { s/^svn-remote\.// } command(qw/repo-config -l/)) {
708                 if (m!^(.+)\.fetch=\s*(.*)\s*:\s*refs/remotes/(.+)\s*$!) {
709                         $r->{$1}->{fetch}->{$2} = $3;
710                 } elsif (m!^(.+)\.url=\s*(.*)\s*$!) {
711                         $r->{$1}->{url} = $2;
712                 }
713         }
714         $r;
717 # we allow more chars than remotes2config.sh...
718 sub sanitize_remote_name {
719         my ($name) = @_;
720         $name =~ tr{A-Za-z0-9:,/+-}{.}c;
721         $name;
724 sub init {
725         my ($class, $url, $path, $repo_id, $ref_id) = @_;
726         my $self = _new($class, $repo_id, $ref_id, $path);
727         mkpath([$self->{dir}]);
728         if (defined $url) {
729                 $url =~ s!/+$!!; # strip trailing slash
730                 my $orig_url = eval {
731                         command_oneline('config', '--get',
732                                         "svn-remote.$repo_id.url")
733                 };
734                 if ($orig_url) {
735                         if ($orig_url ne $url) {
736                                 die "svn-remote.$repo_id.url already set: ",
737                                     "$orig_url\nwanted to set to: $url\n";
738                         }
739                 } else {
740                         command_noisy('config',
741                                       "svn-remote.$repo_id.url", $url);
742                 }
743                 command_noisy('config', '--add',
744                               "svn-remote.$repo_id.fetch",
745                               "$path:".$self->refname);
746         }
747         $self->{url} = $url;
748         unless (-f $self->{db_path}) {
749                 open my $fh, '>>', $self->{db_path} or croak $!;
750                 close $fh or croak $!;
751         }
752         $self;
755 sub find_ref {
756         my ($ref_id) = @_;
757         foreach (command(qw/config -l/)) {
758                 next unless m!^svn-remote\.(.+)\.fetch=
759                               \s*(.*)\s*:\s*refs/remotes/(.+)\s*$!x;
760                 my ($repo_id, $path, $ref) = ($1, $2, $3);
761                 if ($ref eq $ref_id) {
762                         $path = '' if ($path =~ m#^\./?#);
763                         return ($repo_id, $path);
764                 }
765         }
766         (undef, undef, undef);
769 sub new {
770         my ($class, $ref_id, $repo_id, $path) = @_;
771         if (defined $ref_id && !defined $repo_id && !defined $path) {
772                 ($repo_id, $path) = find_ref($ref_id);
773                 if (!defined $repo_id) {
774                         die "Could not find a \"svn-remote.*.fetch\" key ",
775                             "in the repository configuration matching: ",
776                             "refs/remotes/$ref_id\n";
777                 }
778         }
779         my $self = _new($class, $repo_id, $ref_id, $path);
780         $self->{url} = command_oneline('config', '--get',
781                                        "svn-remote.$repo_id.url") or
782                   die "Failed to read \"svn-remote.$repo_id.url\" in config\n";
783         $self;
786 sub refname { "refs/remotes/$_[0]->{ref_id}" }
788 sub ra {
789         my ($self) = shift;
790         $self->{ra} ||= Git::SVN::Ra->new($self->{url});
793 sub copy_remote_ref {
794         my ($self) = @_;
795         my $origin = $::_cp_remote ? $::_cp_remote : 'origin';
796         my $ref = $self->refname;
797         if (command('ls-remote', $origin, $ref)) {
798                 command_noisy('fetch', $origin, "$ref:$ref");
799         } elsif ($::_cp_remote && !$::_upgrade) {
800                 die "Unable to find remote reference: $ref on $origin\n";
801         }
804 sub traverse_ignore {
805         my ($self, $fh, $path, $r) = @_;
806         $path =~ s#^/+##g;
807         my ($dirent, undef, $props) = $self->ra->get_dir($path, $r);
808         my $p = $path;
809         $p =~ s#^\Q$self->{ra}->{svn_path}\E/##;
810         print $fh length $p ? "\n# $p\n" : "\n# /\n";
811         if (my $s = $props->{'svn:ignore'}) {
812                 $s =~ s/[\r\n]+/\n/g;
813                 chomp $s;
814                 if (length $p == 0) {
815                         $s =~ s#\n#\n/$p#g;
816                         print $fh "/$s\n";
817                 } else {
818                         $s =~ s#\n#\n/$p/#g;
819                         print $fh "/$p/$s\n";
820                 }
821         }
822         foreach (sort keys %$dirent) {
823                 next if $dirent->{$_}->kind != $SVN::Node::dir;
824                 $self->traverse_ignore($fh, "$path/$_", $r);
825         }
828 # returns the newest SVN revision number and newest commit SHA1
829 sub last_rev_commit {
830         my ($self) = @_;
831         if (defined $self->{last_rev} && defined $self->{last_commit}) {
832                 return ($self->{last_rev}, $self->{last_commit});
833         }
834         my $c = ::verify_ref($self->refname.'^0');
835         if ($c) {
836                 my $rev = (::cmt_metadata($c))[1];
837                 if (defined $rev) {
838                         ($self->{last_rev}, $self->{last_commit}) = ($rev, $c);
839                         return ($rev, $c);
840                 }
841         }
842         my $offset = -41; # from tail
843         my $rl;
844         open my $fh, '<', $self->{db_path} or
845                                  croak "$self->{db_path} not readable: $!\n";
846         seek $fh, $offset, 2;
847         $rl = readline $fh;
848         defined $rl or return (undef, undef);
849         chomp $rl;
850         while ($c ne $rl && tell $fh != 0) {
851                 $offset -= 41;
852                 seek $fh, $offset, 2;
853                 $rl = readline $fh;
854                 defined $rl or return (undef, undef);
855                 chomp $rl;
856         }
857         my $rev = tell $fh;
858         croak $! if ($rev < 0);
859         $rev =  ($rev - 41) / 41;
860         close $fh or croak $!;
861         ($self->{last_rev}, $self->{last_commit}) = ($rev, $c);
862         return ($rev, $c);
865 sub parse_revision {
866         my ($self, $base) = @_;
867         my $head = $self->ra->get_latest_revnum;
868         if (!defined $::_revision || $::_revision eq 'BASE:HEAD') {
869                 return ($base + 1, $head) if (defined $base);
870                 return (0, $head);
871         }
872         return ($1, $2) if ($::_revision =~ /^(\d+):(\d+)$/);
873         return ($::_revision, $::_revision) if ($::_revision =~ /^\d+$/);
874         if ($::_revision =~ /^BASE:(\d+)$/) {
875                 return ($base + 1, $1) if (defined $base);
876                 return (0, $head);
877         }
878         return ($1, $head) if ($::_revision =~ /^(\d+):HEAD$/);
879         die "revision argument: $::_revision not understood by git-svn\n",
880                 "Try using the command-line svn client instead\n";
883 sub tmp_index_do {
884         my ($self, $sub) = @_;
885         my $old_index = $ENV{GIT_INDEX_FILE};
886         $ENV{GIT_INDEX_FILE} = $self->{index};
887         my @ret = &$sub;
888         if ($old_index) {
889                 $ENV{GIT_INDEX_FILE} = $old_index;
890         } else {
891                 delete $ENV{GIT_INDEX_FILE};
892         }
893         wantarray ? @ret : $ret[0];
896 sub assert_index_clean {
897         my ($self, $treeish) = @_;
899         $self->tmp_index_do(sub {
900                 command_noisy('read-tree', $treeish) unless -e $self->{index};
901                 my $x = command_oneline('write-tree');
902                 my ($y) = (command(qw/cat-file commit/, $treeish) =~
903                            /^tree ($::sha1)/mo);
904                 if ($y ne $x) {
905                         unlink $self->{index} or croak $!;
906                         command_noisy('read-tree', $treeish);
907                 }
908                 $x = command_oneline('write-tree');
909                 if ($y ne $x) {
910                         ::fatal "trees ($treeish) $y != $x\n",
911                                 "Something is seriously wrong...\n";
912                 }
913         });
916 sub get_commit_parents {
917         my ($self, $log_entry, @parents) = @_;
918         my (%seen, @ret, @tmp);
919         # commit parents can be conditionally bound to a particular
920         # svn revision via: "svn_revno=commit_sha1", filter them out here:
921         foreach my $p (@parents) {
922                 next unless defined $p;
923                 if ($p =~ /^(\d+)=($::sha1_short)$/o) {
924                         push @tmp, $2 if $1 == $log_entry->{revision};
925                 } else {
926                         push @tmp, $p if $p =~ /^$::sha1_short$/o;
927                 }
928         }
929         if (my $cur = ::verify_ref($self->refname.'^0')) {
930                 push @tmp, $cur;
931         }
932         push @tmp, $_ foreach (@{$log_entry->{parents}}, @tmp);
933         while (my $p = shift @tmp) {
934                 next if $seen{$p};
935                 $seen{$p} = 1;
936                 push @ret, $p;
937                 # MAXPARENT is defined to 16 in commit-tree.c:
938                 last if @ret >= 16;
939         }
940         if (@tmp) {
941                 die "r$log_entry->{revision}: No room for parents:\n\t",
942                     join("\n\t", @tmp), "\n";
943         }
944         @ret;
947 sub full_url {
948         my ($self) = @_;
949         $self->ra->{url} . (length $self->{path} ? '/' . $self->{path} : '');
952 sub do_git_commit {
953         my ($self, $log_entry, @parents) = @_;
954         if (my $c = $self->rev_db_get($log_entry->{revision})) {
955                 croak "$log_entry->{revision} = $c already exists! ",
956                       "Why are we refetching it?\n";
957         }
958         my $author = $log_entry->{author};
959         my ($name, $email) = (defined $::users{$author} ? @{$::users{$author}}
960                            : ($author, "$author\@".$self->ra->uuid));
961         $ENV{GIT_AUTHOR_NAME} = $ENV{GIT_COMMITTER_NAME} = $name;
962         $ENV{GIT_AUTHOR_EMAIL} = $ENV{GIT_COMMITTER_EMAIL} = $email;
963         $ENV{GIT_AUTHOR_DATE} = $ENV{GIT_COMMITTER_DATE} = $log_entry->{date};
965         my $tree = $log_entry->{tree};
966         if (!defined $tree) {
967                 $tree = $self->tmp_index_do(sub {
968                                             command_oneline('write-tree') });
969         }
970         die "Tree is not a valid sha1: $tree\n" if $tree !~ /^$::sha1$/o;
972         my @exec = ('git-commit-tree', $tree);
973         foreach ($self->get_commit_parents($log_entry, @parents)) {
974                 push @exec, '-p', $_;
975         }
976         defined(my $pid = open3(my $msg_fh, my $out_fh, '>&STDERR', @exec))
977                                                                    or croak $!;
978         print $msg_fh $log_entry->{log} or croak $!;
979         print $msg_fh "\ngit-svn-id: ", $self->full_url, '@',
980                       $log_entry->{revision}, ' ',
981                       $self->ra->uuid, "\n" or croak $!;
982         $msg_fh->flush == 0 or croak $!;
983         close $msg_fh or croak $!;
984         chomp(my $commit = do { local $/; <$out_fh> });
985         close $out_fh or croak $!;
986         waitpid $pid, 0;
987         croak $? if $?;
988         if ($commit !~ /^$::sha1$/o) {
989                 die "Failed to commit, invalid sha1: $commit\n";
990         }
992         command_noisy('update-ref',$self->refname, $commit);
993         $self->rev_db_set($log_entry->{revision}, $commit);
995         $self->{last_rev} = $log_entry->{revision};
996         $self->{last_commit} = $commit;
997         print "r$log_entry->{revision} = $commit\n";
998         return $commit;
1001 sub do_fetch {
1002         my ($self, $paths, $rev) = @_;
1003         my $ed = SVN::Git::Fetcher->new($self);
1004         my ($last_rev, @parents);
1005         if ($self->{last_commit}) {
1006                 $last_rev = $self->{last_rev};
1007                 $ed->{c} = $self->{last_commit};
1008                 @parents = ($self->{last_commit});
1009         } else {
1010                 $last_rev = $rev;
1011         }
1012         unless ($self->ra->gs_do_update($last_rev, $rev,
1013                                         $self->{path}, 1, $ed)) {
1014                 die "SVN connection failed somewhere...\n";
1015         }
1016         $self->make_log_entry($rev, \@parents, $ed);
1019 sub write_untracked {
1020         my ($self, $rev, $fh, $untracked) = @_;
1021         my $h;
1022         print $fh "r$rev\n" or croak $!;
1023         $h = $untracked->{empty};
1024         foreach (sort keys %$h) {
1025                 my $act = $h->{$_} ? '+empty_dir' : '-empty_dir';
1026                 print $fh "  $act: ", uri_encode($_), "\n" or croak $!;
1027                 warn "W: $act: $_\n";
1028         }
1029         foreach my $t (qw/dir_prop file_prop/) {
1030                 $h = $untracked->{$t} or next;
1031                 foreach my $path (sort keys %$h) {
1032                         my $ppath = $path eq '' ? '.' : $path;
1033                         foreach my $prop (sort keys %{$h->{$path}}) {
1034                                 next if $SKIP_PROP{$prop};
1035                                 my $v = $h->{$path}->{$prop};
1036                                 if (defined $v) {
1037                                         print $fh "  +$t: ",
1038                                                   uri_encode($ppath), ' ',
1039                                                   uri_encode($prop), ' ',
1040                                                   uri_encode($v), "\n"
1041                                                   or croak $!;
1042                                 } else {
1043                                         print $fh "  -$t: ",
1044                                                   uri_encode($ppath), ' ',
1045                                                   uri_encode($prop), "\n"
1046                                                   or croak $!;
1047                                 }
1048                         }
1049                 }
1050         }
1051         foreach my $t (qw/absent_file absent_directory/) {
1052                 $h = $untracked->{$t} or next;
1053                 foreach my $parent (sort keys %$h) {
1054                         foreach my $path (sort @{$h->{$parent}}) {
1055                                 print $fh "  $t: ",
1056                                       uri_encode("$parent/$path"), "\n"
1057                                       or croak $!;
1058                                 warn "W: $t: $parent/$path ",
1059                                      "Insufficient permissions?\n";
1060                         }
1061                 }
1062         }
1065 sub parse_svn_date {
1066         my $date = shift || return '+0000 1970-01-01 00:00:00';
1067         my ($Y,$m,$d,$H,$M,$S) = ($date =~ /^(\d{4})\-(\d\d)\-(\d\d)T
1068                                             (\d\d)\:(\d\d)\:(\d\d).\d+Z$/x) or
1069                                          croak "Unable to parse date: $date\n";
1070         "+0000 $Y-$m-$d $H:$M:$S";
1073 sub check_author {
1074         my ($author) = @_;
1075         if (!defined $author || length $author == 0) {
1076                 $author = '(no author)';
1077         }
1078         if (defined $::_authors && ! defined $::users{$author}) {
1079                 die "Author: $author not defined in $::_authors file\n";
1080         }
1081         $author;
1084 sub make_log_entry {
1085         my ($self, $rev, $parents, $untracked) = @_;
1086         my $rp = $self->ra->rev_proplist($rev);
1087         my %log_entry = ( parents => $parents || [], revision => $rev,
1088                           revprops => $rp, log => '');
1089         open my $un, '>>', "$self->{dir}/unhandled.log" or croak $!;
1090         $self->write_untracked($rev, $un, $untracked);
1091         foreach (sort keys %$rp) {
1092                 my $v = $rp->{$_};
1093                 if (/^svn:(author|date|log)$/) {
1094                         $log_entry{$1} = $v;
1095                 } else {
1096                         print $un "  rev_prop: ", uri_encode($_), ' ',
1097                                   uri_encode($v), "\n";
1098                 }
1099         }
1100         close $un or croak $!;
1101         $log_entry{date} = parse_svn_date($log_entry{date});
1102         $log_entry{author} = check_author($log_entry{author});
1103         $log_entry{log} .= "\n";
1104         \%log_entry;
1107 sub fetch {
1108         my ($self, @parents) = @_;
1109         my ($last_rev, $last_commit) = $self->last_rev_commit;
1110         my ($base, $head) = $self->parse_revision($last_rev);
1111         return if ($base > $head);
1112         if (defined $last_commit) {
1113                 $self->assert_index_clean($last_commit);
1114         }
1115         my $inc = 1000;
1116         my ($min, $max) = ($base, $head < $base + $inc ? $head : $base + $inc);
1117         my $err_handler = $SVN::Error::handler;
1118         $SVN::Error::handler = \&skip_unknown_revs;
1119         while (1) {
1120                 my @revs;
1121                 $self->ra->get_log([''], $min, $max, 0, 1, 1, sub {
1122                         my ($paths, $rev, $author, $date, $log) = @_;
1123                         push @revs, $rev });
1124                 foreach (@revs) {
1125                         my $log_entry = $self->do_fetch(undef, $_);
1126                         $self->do_git_commit($log_entry, @parents);
1127                 }
1128                 last if $max >= $head;
1129                 $min = $max + 1;
1130                 $max += $inc;
1131                 $max = $head if ($max > $head);
1132         }
1133         $SVN::Error::handler = $err_handler;
1136 sub set_tree_cb {
1137         my ($self, $log_entry, $tree, $rev, $date, $author) = @_;
1138         # TODO: enable and test optimized commits:
1139         if (0 && $rev == ($self->{last_rev} + 1)) {
1140                 $log_entry->{revision} = $rev;
1141                 $log_entry->{author} = $author;
1142                 $self->do_git_commit($log_entry, "$rev=$tree");
1143         } else {
1144                 $self->fetch("$rev=$tree");
1145         }
1148 sub set_tree {
1149         my ($self, $tree) = (shift, shift);
1150         my $log_entry = ::get_commit_entry($tree);
1151         unless ($self->{last_rev}) {
1152                 fatal("Must have an existing revision to commit\n");
1153         }
1154         my $pool = SVN::Pool->new;
1155         my $ed = SVN::Git::Editor->new({ r => $self->{last_rev},
1156                                          ra => $self->ra->dup,
1157                                          svn_path => $self->ra->{svn_path}
1158                                        },
1159                                        $self->ra->get_commit_editor(
1160                                          $log_entry->{log}, sub {
1161                                            $self->set_tree_cb($log_entry,
1162                                                               $tree, @_);
1163                                        }),
1164                                        $pool);
1165         my $mods = $ed->apply_diff($self->{last_commit}, $tree);
1166         if (@$mods == 0) {
1167                 print "No changes\nr$self->{last_rev} = $tree\n";
1168         }
1169         $pool->clear;
1172 sub skip_unknown_revs {
1173         my ($err) = @_;
1174         my $errno = $err->apr_err();
1175         # Maybe the branch we're tracking didn't
1176         # exist when the repo started, so it's
1177         # not an error if it doesn't, just continue
1178         #
1179         # Wonderfully consistent library, eh?
1180         # 160013 - svn:// and file://
1181         # 175002 - http(s)://
1182         # 175007 - http(s):// (this repo required authorization, too...)
1183         #   More codes may be discovered later...
1184         if ($errno == 175007 || $errno == 175002 || $errno == 160013) {
1185                 return;
1186         }
1187         croak "Error from SVN, ($errno): ", $err->expanded_message,"\n";
1190 # rev_db:
1191 # Tie::File seems to be prone to offset errors if revisions get sparse,
1192 # it's not that fast, either.  Tie::File is also not in Perl 5.6.  So
1193 # one of my favorite modules is out :<  Next up would be one of the DBM
1194 # modules, but I'm not sure which is most portable...  So I'll just
1195 # go with something that's plain-text, but still capable of
1196 # being randomly accessed.  So here's my ultra-simple fixed-width
1197 # database.  All records are 40 characters + "\n", so it's easy to seek
1198 # to a revision: (41 * rev) is the byte offset.
1199 # A record of 40 0s denotes an empty revision.
1200 # And yes, it's still pretty fast (faster than Tie::File).
1202 sub rev_db_set {
1203         my ($self, $rev, $commit) = @_;
1204         length $commit == 40 or croak "arg3 must be a full SHA1 hexsum\n";
1205         open my $fh, '+<', $self->{db_path} or croak $!;
1206         my $offset = $rev * 41;
1207         # assume that append is the common case:
1208         seek $fh, 0, 2 or croak $!;
1209         my $pos = tell $fh;
1210         if ($pos < $offset) {
1211                 print $fh (('0' x 40),"\n") x (($offset - $pos) / 41)
1212                   or croak $!;
1213         }
1214         seek $fh, $offset, 0 or croak $!;
1215         print $fh $commit,"\n" or croak $!;
1216         close $fh or croak $!;
1219 sub rev_db_get {
1220         my ($self, $rev) = @_;
1221         my $ret;
1222         my $offset = $rev * 41;
1223         open my $fh, '<', $self->{db_path} or croak $!;
1224         if (seek $fh, $offset, 0) {
1225                 $ret = readline $fh;
1226                 if (defined $ret) {
1227                         chomp $ret;
1228                         $ret = undef if ($ret =~ /^0{40}$/);
1229                 }
1230         }
1231         close $fh or croak $!;
1232         $ret;
1235 sub _new {
1236         my ($class, $repo_id, $ref_id, $path) = @_;
1237         unless (defined $repo_id && length $repo_id) {
1238                 $repo_id = $Git::SVN::default_repo_id;
1239         }
1240         unless (defined $ref_id && length $ref_id) {
1241                 $_[2] = $ref_id = $repo_id;
1242         }
1243         $_[1] = $repo_id = sanitize_remote_name($repo_id);
1244         my $dir = "$ENV{GIT_DIR}/svn/$ref_id";
1245         $_[3] = $path = '' unless (defined $path);
1246         bless { ref_id => $ref_id, dir => $dir, index => "$dir/index",
1247                 path => $path,
1248                 db_path => "$dir/.rev_db", repo_id => $repo_id }, $class;
1251 sub uri_encode {
1252         my ($f) = @_;
1253         $f =~ s#([^a-zA-Z0-9\*!\:_\./\-])#uc sprintf("%%%02x",ord($1))#eg;
1254         $f
1257 package Git::SVN::Prompt;
1258 use strict;
1259 use warnings;
1260 require SVN::Core;
1261 use vars qw/$_no_auth_cache $_username/;
1263 sub simple {
1264         my ($cred, $realm, $default_username, $may_save, $pool) = @_;
1265         $may_save = undef if $_no_auth_cache;
1266         $default_username = $_username if defined $_username;
1267         if (defined $default_username && length $default_username) {
1268                 if (defined $realm && length $realm) {
1269                         print STDERR "Authentication realm: $realm\n";
1270                         STDERR->flush;
1271                 }
1272                 $cred->username($default_username);
1273         } else {
1274                 username($cred, $realm, $may_save, $pool);
1275         }
1276         $cred->password(_read_password("Password for '" .
1277                                        $cred->username . "': ", $realm));
1278         $cred->may_save($may_save);
1279         $SVN::_Core::SVN_NO_ERROR;
1282 sub ssl_server_trust {
1283         my ($cred, $realm, $failures, $cert_info, $may_save, $pool) = @_;
1284         $may_save = undef if $_no_auth_cache;
1285         print STDERR "Error validating server certificate for '$realm':\n";
1286         if ($failures & $SVN::Auth::SSL::UNKNOWNCA) {
1287                 print STDERR " - The certificate is not issued by a trusted ",
1288                       "authority. Use the\n",
1289                       "   fingerprint to validate the certificate manually!\n";
1290         }
1291         if ($failures & $SVN::Auth::SSL::CNMISMATCH) {
1292                 print STDERR " - The certificate hostname does not match.\n";
1293         }
1294         if ($failures & $SVN::Auth::SSL::NOTYETVALID) {
1295                 print STDERR " - The certificate is not yet valid.\n";
1296         }
1297         if ($failures & $SVN::Auth::SSL::EXPIRED) {
1298                 print STDERR " - The certificate has expired.\n";
1299         }
1300         if ($failures & $SVN::Auth::SSL::OTHER) {
1301                 print STDERR " - The certificate has an unknown error.\n";
1302         }
1303         printf STDERR
1304                 "Certificate information:\n".
1305                 " - Hostname: %s\n".
1306                 " - Valid: from %s until %s\n".
1307                 " - Issuer: %s\n".
1308                 " - Fingerprint: %s\n",
1309                 map $cert_info->$_, qw(hostname valid_from valid_until
1310                                        issuer_dname fingerprint);
1311         my $choice;
1312 prompt:
1313         print STDERR $may_save ?
1314               "(R)eject, accept (t)emporarily or accept (p)ermanently? " :
1315               "(R)eject or accept (t)emporarily? ";
1316         STDERR->flush;
1317         $choice = lc(substr(<STDIN> || 'R', 0, 1));
1318         if ($choice =~ /^t$/i) {
1319                 $cred->may_save(undef);
1320         } elsif ($choice =~ /^r$/i) {
1321                 return -1;
1322         } elsif ($may_save && $choice =~ /^p$/i) {
1323                 $cred->may_save($may_save);
1324         } else {
1325                 goto prompt;
1326         }
1327         $cred->accepted_failures($failures);
1328         $SVN::_Core::SVN_NO_ERROR;
1331 sub ssl_client_cert {
1332         my ($cred, $realm, $may_save, $pool) = @_;
1333         $may_save = undef if $_no_auth_cache;
1334         print STDERR "Client certificate filename: ";
1335         STDERR->flush;
1336         chomp(my $filename = <STDIN>);
1337         $cred->cert_file($filename);
1338         $cred->may_save($may_save);
1339         $SVN::_Core::SVN_NO_ERROR;
1342 sub ssl_client_cert_pw {
1343         my ($cred, $realm, $may_save, $pool) = @_;
1344         $may_save = undef if $_no_auth_cache;
1345         $cred->password(_read_password("Password: ", $realm));
1346         $cred->may_save($may_save);
1347         $SVN::_Core::SVN_NO_ERROR;
1350 sub username {
1351         my ($cred, $realm, $may_save, $pool) = @_;
1352         $may_save = undef if $_no_auth_cache;
1353         if (defined $realm && length $realm) {
1354                 print STDERR "Authentication realm: $realm\n";
1355         }
1356         my $username;
1357         if (defined $_username) {
1358                 $username = $_username;
1359         } else {
1360                 print STDERR "Username: ";
1361                 STDERR->flush;
1362                 chomp($username = <STDIN>);
1363         }
1364         $cred->username($username);
1365         $cred->may_save($may_save);
1366         $SVN::_Core::SVN_NO_ERROR;
1369 sub _read_password {
1370         my ($prompt, $realm) = @_;
1371         print STDERR $prompt;
1372         STDERR->flush;
1373         require Term::ReadKey;
1374         Term::ReadKey::ReadMode('noecho');
1375         my $password = '';
1376         while (defined(my $key = Term::ReadKey::ReadKey(0))) {
1377                 last if $key =~ /[\012\015]/; # \n\r
1378                 $password .= $key;
1379         }
1380         Term::ReadKey::ReadMode('restore');
1381         print STDERR "\n";
1382         STDERR->flush;
1383         $password;
1386 package main;
1388 sub uri_encode {
1389         my ($f) = @_;
1390         $f =~ s#([^a-zA-Z0-9\*!\:_\./\-])#uc sprintf("%%%02x",ord($1))#eg;
1391         $f
1394 sub uri_decode {
1395         my ($f) = @_;
1396         $f =~ tr/+/ /;
1397         $f =~ s/%([A-F0-9]{2})/chr hex($1)/ge;
1398         $f
1401 sub revisions_eq {
1402         my ($path, $r0, $r1) = @_;
1403         return 1 if $r0 == $r1;
1404         my $nr = 0;
1405         # should be OK to use Pool here (r1 - r0) should be small
1406         $SVN->get_log([$path], $r0, $r1, 0, 0, 1, sub {$nr++});
1407         return 0 if ($nr > 1);
1408         return 1;
1411 sub libsvn_find_parent_branch {
1412         my ($paths, $rev, $author, $date, $log) = @_;
1413         my $svn_path = '/'.$SVN->{svn_path};
1415         # look for a parent from another branch:
1416         my $i = $paths->{$svn_path} or return;
1417         my $branch_from = $i->copyfrom_path or return;
1418         my $r = $i->copyfrom_rev;
1419         print STDERR  "Found possible branch point: ",
1420                                 "$branch_from => $svn_path, $r\n";
1421         $branch_from =~ s#^/##;
1422         my $l_map = {};
1423         read_url_paths_all($l_map, '', "$GIT_DIR/svn");
1424         my $url = $SVN->{repos_root};
1425         defined $l_map->{$url} or return;
1426         my $id = $l_map->{$url}->{$branch_from};
1427         if (!defined $id && $_follow_parent) {
1428                 print STDERR "Following parent: $branch_from\@$r\n";
1429                 # auto create a new branch and follow it
1430                 $id = basename($branch_from);
1431                 $id .= '@'.$r if -r "$GIT_DIR/svn/$id";
1432                 while (-r "$GIT_DIR/svn/$id") {
1433                         # just grow a tail if we're not unique enough :x
1434                         $id .= '-';
1435                 }
1436         }
1437         return unless defined $id;
1439         my ($r0, $parent) = find_rev_before($r,$id,1);
1440         if ($_follow_parent && (!defined $r0 || !defined $parent)) {
1441                 defined(my $pid = fork) or croak $!;
1442                 if (!$pid) {
1443                         $GIT_SVN = $ENV{GIT_SVN_ID} = $id;
1444                         init_vars();
1445                         $SVN_URL = "$url/$branch_from";
1446                         $SVN = undef;
1447                         setup_git_svn();
1448                         # we can't assume SVN_URL exists at r+1:
1449                         $_revision = "0:$r";
1450                         fetch_lib();
1451                         exit 0;
1452                 }
1453                 waitpid $pid, 0;
1454                 croak $? if $?;
1455                 ($r0, $parent) = find_rev_before($r,$id,1);
1456         }
1457         return unless (defined $r0 && defined $parent);
1458         if (revisions_eq($branch_from, $r0, $r)) {
1459                 unlink $GIT_SVN_INDEX;
1460                 print STDERR "Found branch parent: ($GIT_SVN) $parent\n";
1461                 command_noisy('read-tree', $parent);
1462                 unless ($SVN->can_do_switch) {
1463                         return _libsvn_new_tree($paths, $rev, $author, $date,
1464                                                 $log, [$parent]);
1465                 }
1466                 # do_switch works with svn/trunk >= r22312, but that is not
1467                 # included with SVN 1.4.2 (the latest version at the moment),
1468                 # so we can't rely on it.
1469                 my $ra = Git::SVN::Ra->new("$url/$branch_from");
1470                 my $ed = SVN::Git::Fetcher->new({c => $parent, q => $_q });
1471                 $ra->gs_do_switch($r0, $rev, '', 1, $SVN->{url}, $ed) or
1472                                    die "SVN connection failed somewhere...\n";
1473                 return libsvn_log_entry($rev, $author, $date, $log, [$parent]);
1474         }
1475         print STDERR "Nope, branch point not imported or unknown\n";
1476         return undef;
1479 sub _libsvn_new_tree {
1480         my ($paths, $rev, $author, $date, $log, $parents) = @_;
1481         my $ed = SVN::Git::Fetcher->new({q => $_q});
1482         unless ($SVN->gs_do_update($rev, $rev, '', 1, $ed)) {
1483                 die "SVN connection failed somewhere...\n";
1484         }
1485         libsvn_log_entry($rev, $author, $date, $log, $parents, $ed);
1489         my $kill_stupid_warnings = $SVN::Node::none.$SVN::Node::file.
1490                                 $SVN::Node::dir.$SVN::Node::unknown.
1491                                 $SVN::Node::none.$SVN::Node::file.
1492                                 $SVN::Node::dir.$SVN::Node::unknown.
1493                                 $SVN::Auth::SSL::CNMISMATCH.
1494                                 $SVN::Auth::SSL::NOTYETVALID.
1495                                 $SVN::Auth::SSL::EXPIRED.
1496                                 $SVN::Auth::SSL::UNKNOWNCA.
1497                                 $SVN::Auth::SSL::OTHER;
1500 package SVN::Git::Fetcher;
1501 use vars qw/@ISA/;
1502 use strict;
1503 use warnings;
1504 use Carp qw/croak/;
1505 use IO::File qw//;
1507 # file baton members: path, mode_a, mode_b, pool, fh, blob, base
1508 sub new {
1509         my ($class, $git_svn) = @_;
1510         my $self = SVN::Delta::Editor->new;
1511         bless $self, $class;
1512         $self->{c} = $git_svn->{last_commit} if exists $git_svn->{last_commit};
1513         if (length $git_svn->{path}) {
1514                 $self->{path_strip} = qr/\Q$git_svn->{path}\E\/?/;
1515         }
1516         $self->{empty} = {};
1517         $self->{dir_prop} = {};
1518         $self->{file_prop} = {};
1519         $self->{absent_dir} = {};
1520         $self->{absent_file} = {};
1521         ($self->{gui}, $self->{ctx}) = $git_svn->tmp_index_do(
1522                sub { command_input_pipe(qw/update-index -z --index-info/) } );
1523         require Digest::MD5;
1524         $self;
1527 sub open_root {
1528         { path => '' };
1531 sub open_directory {
1532         my ($self, $path, $pb, $rev) = @_;
1533         { path => $path };
1536 sub git_path {
1537         my ($self, $path) = @_;
1538         $path =~ s!$self->{path_strip}!! if $self->{path_strip};
1539         $path;
1542 sub delete_entry {
1543         my ($self, $path, $rev, $pb) = @_;
1544         my $gui = $self->{gui};
1546         my $gpath = $self->git_path($path);
1547         # remove entire directories.
1548         if (command('ls-tree', $self->{c}, '--', $gpath) =~ /^040000 tree/) {
1549                 my ($ls, $ctx) = command_output_pipe(qw/ls-tree
1550                                                      -r --name-only -z/,
1551                                                      $self->{c}, '--', $gpath);
1552                 local $/ = "\0";
1553                 while (<$ls>) {
1554                         print $gui '0 ',0 x 40,"\t",$_ or croak $!;
1555                         print "\tD\t$_\n" unless $self->{q};
1556                 }
1557                 print "\tD\t$gpath/\n" unless $self->{q};
1558                 command_close_pipe($ls, $ctx);
1559                 $self->{empty}->{$path} = 0
1560         } else {
1561                 print $gui '0 ',0 x 40,"\t",$gpath,"\0" or croak $!;
1562                 print "\tD\t$gpath\n" unless $self->{q};
1563         }
1564         undef;
1567 sub open_file {
1568         my ($self, $path, $pb, $rev) = @_;
1569         my $gpath = $self->git_path($path);
1570         my ($mode, $blob) = (command('ls-tree', $self->{c}, '--', $gpath)
1571                              =~ /^(\d{6}) blob ([a-f\d]{40})\t/);
1572         unless (defined $mode && defined $blob) {
1573                 die "$path was not found in commit $self->{c} (r$rev)\n";
1574         }
1575         { path => $path, mode_a => $mode, mode_b => $mode, blob => $blob,
1576           pool => SVN::Pool->new, action => 'M' };
1579 sub add_file {
1580         my ($self, $path, $pb, $cp_path, $cp_rev) = @_;
1581         my ($dir, $file) = ($path =~ m#^(.*?)/?([^/]+)$#);
1582         delete $self->{empty}->{$dir};
1583         { path => $path, mode_a => 100644, mode_b => 100644,
1584           pool => SVN::Pool->new, action => 'A' };
1587 sub add_directory {
1588         my ($self, $path, $cp_path, $cp_rev) = @_;
1589         my ($dir, $file) = ($path =~ m#^(.*?)/?([^/]+)$#);
1590         delete $self->{empty}->{$dir};
1591         $self->{empty}->{$path} = 1;
1592         { path => $path };
1595 sub change_dir_prop {
1596         my ($self, $db, $prop, $value) = @_;
1597         $self->{dir_prop}->{$db->{path}} ||= {};
1598         $self->{dir_prop}->{$db->{path}}->{$prop} = $value;
1599         undef;
1602 sub absent_directory {
1603         my ($self, $path, $pb) = @_;
1604         $self->{absent_dir}->{$pb->{path}} ||= [];
1605         push @{$self->{absent_dir}->{$pb->{path}}}, $path;
1606         undef;
1609 sub absent_file {
1610         my ($self, $path, $pb) = @_;
1611         $self->{absent_file}->{$pb->{path}} ||= [];
1612         push @{$self->{absent_file}->{$pb->{path}}}, $path;
1613         undef;
1616 sub change_file_prop {
1617         my ($self, $fb, $prop, $value) = @_;
1618         if ($prop eq 'svn:executable') {
1619                 if ($fb->{mode_b} != 120000) {
1620                         $fb->{mode_b} = defined $value ? 100755 : 100644;
1621                 }
1622         } elsif ($prop eq 'svn:special') {
1623                 $fb->{mode_b} = defined $value ? 120000 : 100644;
1624         } else {
1625                 $self->{file_prop}->{$fb->{path}} ||= {};
1626                 $self->{file_prop}->{$fb->{path}}->{$prop} = $value;
1627         }
1628         undef;
1631 sub apply_textdelta {
1632         my ($self, $fb, $exp) = @_;
1633         my $fh = IO::File->new_tmpfile;
1634         $fh->autoflush(1);
1635         # $fh gets auto-closed() by SVN::TxDelta::apply(),
1636         # (but $base does not,) so dup() it for reading in close_file
1637         open my $dup, '<&', $fh or croak $!;
1638         my $base = IO::File->new_tmpfile;
1639         $base->autoflush(1);
1640         if ($fb->{blob}) {
1641                 defined (my $pid = fork) or croak $!;
1642                 if (!$pid) {
1643                         open STDOUT, '>&', $base or croak $!;
1644                         print STDOUT 'link ' if ($fb->{mode_a} == 120000);
1645                         exec qw/git-cat-file blob/, $fb->{blob} or croak $!;
1646                 }
1647                 waitpid $pid, 0;
1648                 croak $? if $?;
1650                 if (defined $exp) {
1651                         seek $base, 0, 0 or croak $!;
1652                         my $md5 = Digest::MD5->new;
1653                         $md5->addfile($base);
1654                         my $got = $md5->hexdigest;
1655                         die "Checksum mismatch: $fb->{path} $fb->{blob}\n",
1656                             "expected: $exp\n",
1657                             "     got: $got\n" if ($got ne $exp);
1658                 }
1659         }
1660         seek $base, 0, 0 or croak $!;
1661         $fb->{fh} = $dup;
1662         $fb->{base} = $base;
1663         [ SVN::TxDelta::apply($base, $fh, undef, $fb->{path}, $fb->{pool}) ];
1666 sub close_file {
1667         my ($self, $fb, $exp) = @_;
1668         my $hash;
1669         my $path = $self->git_path($fb->{path});
1670         if (my $fh = $fb->{fh}) {
1671                 seek($fh, 0, 0) or croak $!;
1672                 my $md5 = Digest::MD5->new;
1673                 $md5->addfile($fh);
1674                 my $got = $md5->hexdigest;
1675                 die "Checksum mismatch: $path\n",
1676                     "expected: $exp\n    got: $got\n" if ($got ne $exp);
1677                 seek($fh, 0, 0) or croak $!;
1678                 if ($fb->{mode_b} == 120000) {
1679                         read($fh, my $buf, 5) == 5 or croak $!;
1680                         $buf eq 'link ' or die "$path has mode 120000",
1681                                                "but is not a link\n";
1682                 }
1683                 defined(my $pid = open my $out,'-|') or die "Can't fork: $!\n";
1684                 if (!$pid) {
1685                         open STDIN, '<&', $fh or croak $!;
1686                         exec qw/git-hash-object -w --stdin/ or croak $!;
1687                 }
1688                 chomp($hash = do { local $/; <$out> });
1689                 close $out or croak $!;
1690                 close $fh or croak $!;
1691                 $hash =~ /^[a-f\d]{40}$/ or die "not a sha1: $hash\n";
1692                 close $fb->{base} or croak $!;
1693         } else {
1694                 $hash = $fb->{blob} or die "no blob information\n";
1695         }
1696         $fb->{pool}->clear;
1697         my $gui = $self->{gui};
1698         print $gui "$fb->{mode_b} $hash\t$path\0" or croak $!;
1699         print "\t$fb->{action}\t$path\n" if $fb->{action} && ! $self->{q};
1700         undef;
1703 sub abort_edit {
1704         my $self = shift;
1705         eval { command_close_pipe($self->{gui}, $self->{ctx}) };
1706         $self->SUPER::abort_edit(@_);
1709 sub close_edit {
1710         my $self = shift;
1711         command_close_pipe($self->{gui}, $self->{ctx});
1712         $self->{git_commit_ok} = 1;
1713         $self->SUPER::close_edit(@_);
1716 package SVN::Git::Editor;
1717 use vars qw/@ISA/;
1718 use strict;
1719 use warnings;
1720 use Carp qw/croak/;
1721 use IO::File;
1723 sub new {
1724         my $class = shift;
1725         my $git_svn = shift;
1726         my $self = SVN::Delta::Editor->new(@_);
1727         bless $self, $class;
1728         foreach (qw/svn_path r ra/) {
1729                 die "$_ required!\n" unless (defined $git_svn->{$_});
1730                 $self->{$_} = $git_svn->{$_};
1731         }
1732         $self->{pool} = SVN::Pool->new;
1733         $self->{bat} = { '' => $self->open_root($self->{r}, $self->{pool}) };
1734         $self->{rm} = { };
1735         require Digest::MD5;
1736         return $self;
1739 sub split_path {
1740         return ($_[0] =~ m#^(.*?)/?([^/]+)$#);
1743 sub repo_path {
1744         (defined $_[1] && length $_[1]) ? $_[1] : ''
1747 sub url_path {
1748         my ($self, $path) = @_;
1749         $self->{ra}->{url} . '/' . $self->repo_path($path);
1752 sub rmdirs {
1753         my ($self, $tree_b) = @_;
1754         my $rm = $self->{rm};
1755         delete $rm->{''}; # we never delete the url we're tracking
1756         return unless %$rm;
1758         foreach (keys %$rm) {
1759                 my @d = split m#/#, $_;
1760                 my $c = shift @d;
1761                 $rm->{$c} = 1;
1762                 while (@d) {
1763                         $c .= '/' . shift @d;
1764                         $rm->{$c} = 1;
1765                 }
1766         }
1767         delete $rm->{$self->{svn_path}};
1768         delete $rm->{''}; # we never delete the url we're tracking
1769         return unless %$rm;
1771         my ($fh, $ctx) = command_output_pipe(
1772                                    qw/ls-tree --name-only -r -z/, $tree_b);
1773         local $/ = "\0";
1774         while (<$fh>) {
1775                 chomp;
1776                 my @dn = split m#/#, $_;
1777                 while (pop @dn) {
1778                         delete $rm->{join '/', @dn};
1779                 }
1780                 unless (%$rm) {
1781                         close $fh;
1782                         return;
1783                 }
1784         }
1785         command_close_pipe($fh, $ctx);
1787         my ($r, $p, $bat) = ($self->{r}, $self->{pool}, $self->{bat});
1788         foreach my $d (sort { $b =~ tr#/#/# <=> $a =~ tr#/#/# } keys %$rm) {
1789                 $self->close_directory($bat->{$d}, $p);
1790                 my ($dn) = ($d =~ m#^(.*?)/?(?:[^/]+)$#);
1791                 print "\tD+\t$d/\n" unless $::_q;
1792                 $self->SUPER::delete_entry($d, $r, $bat->{$dn}, $p);
1793                 delete $bat->{$d};
1794         }
1797 sub open_or_add_dir {
1798         my ($self, $full_path, $baton) = @_;
1799         my $t = $self->{ra}->check_path($full_path, $self->{r});
1800         if ($t == $SVN::Node::none) {
1801                 return $self->add_directory($full_path, $baton,
1802                                                 undef, -1, $self->{pool});
1803         } elsif ($t == $SVN::Node::dir) {
1804                 return $self->open_directory($full_path, $baton,
1805                                                 $self->{r}, $self->{pool});
1806         }
1807         print STDERR "$full_path already exists in repository at ",
1808                 "r$self->{r} and it is not a directory (",
1809                 ($t == $SVN::Node::file ? 'file' : 'unknown'),"/$t)\n";
1810         exit 1;
1813 sub ensure_path {
1814         my ($self, $path) = @_;
1815         my $bat = $self->{bat};
1816         $path = $self->repo_path($path);
1817         return $bat->{''} unless (length $path);
1818         my @p = split m#/+#, $path;
1819         my $c = shift @p;
1820         $bat->{$c} ||= $self->open_or_add_dir($c, $bat->{''});
1821         while (@p) {
1822                 my $c0 = $c;
1823                 $c .= '/' . shift @p;
1824                 $bat->{$c} ||= $self->open_or_add_dir($c, $bat->{$c0});
1825         }
1826         return $bat->{$c};
1829 sub A {
1830         my ($self, $m) = @_;
1831         my ($dir, $file) = split_path($m->{file_b});
1832         my $pbat = $self->ensure_path($dir);
1833         my $fbat = $self->add_file($self->repo_path($m->{file_b}), $pbat,
1834                                         undef, -1);
1835         print "\tA\t$m->{file_b}\n" unless $::_q;
1836         $self->chg_file($fbat, $m);
1837         $self->close_file($fbat,undef,$self->{pool});
1840 sub C {
1841         my ($self, $m) = @_;
1842         my ($dir, $file) = split_path($m->{file_b});
1843         my $pbat = $self->ensure_path($dir);
1844         my $fbat = $self->add_file($self->repo_path($m->{file_b}), $pbat,
1845                                 $self->url_path($m->{file_a}), $self->{r});
1846         print "\tC\t$m->{file_a} => $m->{file_b}\n" unless $::_q;
1847         $self->chg_file($fbat, $m);
1848         $self->close_file($fbat,undef,$self->{pool});
1851 sub delete_entry {
1852         my ($self, $path, $pbat) = @_;
1853         my $rpath = $self->repo_path($path);
1854         my ($dir, $file) = split_path($rpath);
1855         $self->{rm}->{$dir} = 1;
1856         $self->SUPER::delete_entry($rpath, $self->{r}, $pbat, $self->{pool});
1859 sub R {
1860         my ($self, $m) = @_;
1861         my ($dir, $file) = split_path($m->{file_b});
1862         my $pbat = $self->ensure_path($dir);
1863         my $fbat = $self->add_file($self->repo_path($m->{file_b}), $pbat,
1864                                 $self->url_path($m->{file_a}), $self->{r});
1865         print "\tR\t$m->{file_a} => $m->{file_b}\n" unless $::_q;
1866         $self->chg_file($fbat, $m);
1867         $self->close_file($fbat,undef,$self->{pool});
1869         ($dir, $file) = split_path($m->{file_a});
1870         $pbat = $self->ensure_path($dir);
1871         $self->delete_entry($m->{file_a}, $pbat);
1874 sub M {
1875         my ($self, $m) = @_;
1876         my ($dir, $file) = split_path($m->{file_b});
1877         my $pbat = $self->ensure_path($dir);
1878         my $fbat = $self->open_file($self->repo_path($m->{file_b}),
1879                                 $pbat,$self->{r},$self->{pool});
1880         print "\t$m->{chg}\t$m->{file_b}\n" unless $::_q;
1881         $self->chg_file($fbat, $m);
1882         $self->close_file($fbat,undef,$self->{pool});
1885 sub T { shift->M(@_) }
1887 sub change_file_prop {
1888         my ($self, $fbat, $pname, $pval) = @_;
1889         $self->SUPER::change_file_prop($fbat, $pname, $pval, $self->{pool});
1892 sub chg_file {
1893         my ($self, $fbat, $m) = @_;
1894         if ($m->{mode_b} =~ /755$/ && $m->{mode_a} !~ /755$/) {
1895                 $self->change_file_prop($fbat,'svn:executable','*');
1896         } elsif ($m->{mode_b} !~ /755$/ && $m->{mode_a} =~ /755$/) {
1897                 $self->change_file_prop($fbat,'svn:executable',undef);
1898         }
1899         my $fh = IO::File->new_tmpfile or croak $!;
1900         if ($m->{mode_b} =~ /^120/) {
1901                 print $fh 'link ' or croak $!;
1902                 $self->change_file_prop($fbat,'svn:special','*');
1903         } elsif ($m->{mode_a} =~ /^120/ && $m->{mode_b} !~ /^120/) {
1904                 $self->change_file_prop($fbat,'svn:special',undef);
1905         }
1906         defined(my $pid = fork) or croak $!;
1907         if (!$pid) {
1908                 open STDOUT, '>&', $fh or croak $!;
1909                 exec qw/git-cat-file blob/, $m->{sha1_b} or croak $!;
1910         }
1911         waitpid $pid, 0;
1912         croak $? if $?;
1913         $fh->flush == 0 or croak $!;
1914         seek $fh, 0, 0 or croak $!;
1916         my $md5 = Digest::MD5->new;
1917         $md5->addfile($fh) or croak $!;
1918         seek $fh, 0, 0 or croak $!;
1920         my $exp = $md5->hexdigest;
1921         my $pool = SVN::Pool->new;
1922         my $atd = $self->apply_textdelta($fbat, undef, $pool);
1923         my $got = SVN::TxDelta::send_stream($fh, @$atd, $pool);
1924         die "Checksum mismatch\nexpected: $exp\ngot: $got\n" if ($got ne $exp);
1925         $pool->clear;
1927         close $fh or croak $!;
1930 sub D {
1931         my ($self, $m) = @_;
1932         my ($dir, $file) = split_path($m->{file_b});
1933         my $pbat = $self->ensure_path($dir);
1934         print "\tD\t$m->{file_b}\n" unless $::_q;
1935         $self->delete_entry($m->{file_b}, $pbat);
1938 sub close_edit {
1939         my ($self) = @_;
1940         my ($p,$bat) = ($self->{pool}, $self->{bat});
1941         foreach (sort { $b =~ tr#/#/# <=> $a =~ tr#/#/# } keys %$bat) {
1942                 $self->close_directory($bat->{$_}, $p);
1943         }
1944         $self->SUPER::close_edit($p);
1945         $p->clear;
1948 sub abort_edit {
1949         my ($self) = @_;
1950         $self->SUPER::abort_edit($self->{pool});
1951         $self->{pool}->clear;
1954 # this drives the editor
1955 sub apply_diff {
1956         my ($self, $tree_a, $tree_b) = @_;
1957         my @diff_tree = qw(diff-tree -z -r);
1958         if ($::_cp_similarity) {
1959                 push @diff_tree, "-C$::_cp_similarity";
1960         } else {
1961                 push @diff_tree, '-C';
1962         }
1963         push @diff_tree, '--find-copies-harder' if $::_find_copies_harder;
1964         push @diff_tree, "-l$::_l" if defined $::_l;
1965         push @diff_tree, $tree_a, $tree_b;
1966         my ($diff_fh, $ctx) = command_output_pipe(@diff_tree);
1967         my $nl = $/;
1968         local $/ = "\0";
1969         my $state = 'meta';
1970         my @mods;
1971         while (<$diff_fh>) {
1972                 chomp $_; # this gets rid of the trailing "\0"
1973                 if ($state eq 'meta' && /^:(\d{6})\s(\d{6})\s
1974                                         $::sha1\s($::sha1)\s
1975                                         ([MTCRAD])\d*$/xo) {
1976                         push @mods, {   mode_a => $1, mode_b => $2,
1977                                         sha1_b => $3, chg => $4 };
1978                         if ($4 =~ /^(?:C|R)$/) {
1979                                 $state = 'file_a';
1980                         } else {
1981                                 $state = 'file_b';
1982                         }
1983                 } elsif ($state eq 'file_a') {
1984                         my $x = $mods[$#mods] or croak "Empty array\n";
1985                         if ($x->{chg} !~ /^(?:C|R)$/) {
1986                                 croak "Error parsing $_, $x->{chg}\n";
1987                         }
1988                         $x->{file_a} = $_;
1989                         $state = 'file_b';
1990                 } elsif ($state eq 'file_b') {
1991                         my $x = $mods[$#mods] or croak "Empty array\n";
1992                         if (exists $x->{file_a} && $x->{chg} !~ /^(?:C|R)$/) {
1993                                 croak "Error parsing $_, $x->{chg}\n";
1994                         }
1995                         if (!exists $x->{file_a} && $x->{chg} =~ /^(?:C|R)$/) {
1996                                 croak "Error parsing $_, $x->{chg}\n";
1997                         }
1998                         $x->{file_b} = $_;
1999                         $state = 'meta';
2000                 } else {
2001                         croak "Error parsing $_\n";
2002                 }
2003         }
2004         command_close_pipe($diff_fh, $ctx);
2005         $/ = $nl;
2007         my %o = ( D => 1, R => 0, C => -1, A => 3, M => 3, T => 3 );
2008         foreach my $m (sort { $o{$a->{chg}} <=> $o{$b->{chg}} } @mods) {
2009                 my $f = $m->{chg};
2010                 if (defined $o{$f}) {
2011                         $self->$f($m);
2012                 } else {
2013                         fatal("Invalid change type: $f\n");
2014                 }
2015         }
2016         $self->rmdirs($tree_b) if $::_rmdir;
2017         if (@mods == 0) {
2018                 $self->abort_edit;
2019         } else {
2020                 $self->close_edit;
2021         }
2022         \@mods;
2025 package Git::SVN::Ra;
2026 use vars qw/@ISA $config_dir/;
2027 use strict;
2028 use warnings;
2029 my ($can_do_switch);
2030 my %RA;
2032 BEGIN {
2033         # enforce temporary pool usage for some simple functions
2034         my $e;
2035         foreach (qw/get_latest_revnum rev_proplist get_file
2036                     check_path get_dir get_uuid get_repos_root/) {
2037                 $e .= "sub $_ {
2038                         my \$self = shift;
2039                         my \$pool = SVN::Pool->new;
2040                         my \@ret = \$self->SUPER::$_(\@_,\$pool);
2041                         \$pool->clear;
2042                         wantarray ? \@ret : \$ret[0]; }\n";
2043         }
2044         eval $e;
2047 sub new {
2048         my ($class, $url) = @_;
2049         $url =~ s!/+$!!;
2050         return $RA{$url} if $RA{$url};
2052         SVN::_Core::svn_config_ensure($config_dir, undef);
2053         my ($baton, $callbacks) = SVN::Core::auth_open_helper([
2054             SVN::Client::get_simple_provider(),
2055             SVN::Client::get_ssl_server_trust_file_provider(),
2056             SVN::Client::get_simple_prompt_provider(
2057               \&Git::SVN::Prompt::simple, 2),
2058             SVN::Client::get_ssl_client_cert_prompt_provider(
2059               \&Git::SVN::Prompt::ssl_client_cert, 2),
2060             SVN::Client::get_ssl_client_cert_pw_prompt_provider(
2061               \&Git::SVN::Prompt::ssl_client_cert_pw, 2),
2062             SVN::Client::get_username_provider(),
2063             SVN::Client::get_ssl_server_trust_prompt_provider(
2064               \&Git::SVN::Prompt::ssl_server_trust),
2065             SVN::Client::get_username_prompt_provider(
2066               \&Git::SVN::Prompt::username, 2),
2067           ]);
2068         my $config = SVN::Core::config_get_config($config_dir);
2069         my $self = SVN::Ra->new(url => $url, auth => $baton,
2070                               config => $config,
2071                               pool => SVN::Pool->new,
2072                               auth_provider_callbacks => $callbacks);
2073         $self->{svn_path} = $url;
2074         $self->{repos_root} = $self->get_repos_root;
2075         $self->{svn_path} =~ s#^\Q$self->{repos_root}\E/*##;
2076         $RA{$url} = bless $self, $class;
2079 sub DESTROY {
2080         # do not call the real DESTROY since we store ourselves in %RA
2083 sub dup {
2084         my ($self) = @_;
2085         my $dup = SVN::Ra->new(pool => SVN::Pool->new,
2086                                 map { $_ => $self->{$_} } qw/config url
2087                      auth auth_provider_callbacks repos_root svn_path/);
2088         bless $dup, ref $self;
2091 sub get_log {
2092         my ($self, @args) = @_;
2093         my $pool = SVN::Pool->new;
2094         $args[4]-- if $args[4] && ! $::_follow_parent;
2095         splice(@args, 3, 1) if ($SVN::Core::VERSION le '1.2.0');
2096         my $ret = $self->SUPER::get_log(@args, $pool);
2097         $pool->clear;
2098         $ret;
2101 sub get_commit_editor {
2102         my ($self, $log, $cb, $pool) = @_;
2103         my @lock = $SVN::Core::VERSION ge '1.2.0' ? (undef, 0) : ();
2104         $self->SUPER::get_commit_editor($log, $cb, @lock, $pool);
2107 sub uuid {
2108         my ($self) = @_;
2109         $self->{uuid} ||= $self->get_uuid;
2112 sub gs_do_update {
2113         my ($self, $rev_a, $rev_b, $path, $recurse, $editor) = @_;
2114         my $pool = SVN::Pool->new;
2115         my $reporter = $self->do_update($rev_b, $path, $recurse,
2116                                         $editor, $pool);
2117         my @lock = $SVN::Core::VERSION ge '1.2.0' ? (undef) : ();
2118         my $new = ($rev_a == $rev_b);
2119         $reporter->set_path('', $rev_a, $new, @lock, $pool);
2120         $reporter->finish_report($pool);
2121         $pool->clear;
2122         $editor->{git_commit_ok};
2125 sub gs_do_switch {
2126         my ($self, $rev_a, $rev_b, $path, $recurse, $url_b, $editor) = @_;
2127         my $pool = SVN::Pool->new;
2128         my $reporter = $self->do_switch($rev_b, $path, $recurse,
2129                                         $url_b, $editor, $pool);
2130         my @lock = $SVN::Core::VERSION ge '1.2.0' ? (undef) : ();
2131         $reporter->set_path($path, $rev_a, 0, @lock, $pool);
2132         $reporter->finish_report($pool);
2133         $pool->clear;
2134         $editor->{git_commit_ok};
2137 sub can_do_switch {
2138         my $self = shift;
2139         unless (defined $can_do_switch) {
2140                 my $pool = SVN::Pool->new;
2141                 my $rep = eval {
2142                         $self->do_switch(1, '', 0, $self->{url},
2143                                          SVN::Delta::Editor->new, $pool);
2144                 };
2145                 if ($@) {
2146                         $can_do_switch = 0;
2147                 } else {
2148                         $rep->abort_report($pool);
2149                         $can_do_switch = 1;
2150                 }
2151                 $pool->clear;
2152         }
2153         $can_do_switch;
2156 package Git::SVN::Log;
2157 use strict;
2158 use warnings;
2159 use POSIX qw/strftime/;
2160 use vars qw/$TZ $limit $color $pager $non_recursive $verbose $oneline
2161             %rusers $show_commit $incremental/;
2162 my $l_fmt;
2164 sub cmt_showable {
2165         my ($c) = @_;
2166         return 1 if defined $c->{r};
2167         if ($c->{l} && $c->{l}->[-1] eq "...\n" &&
2168                                 $c->{a_raw} =~ /\@([a-f\d\-]+)>$/) {
2169                 my @log = command(qw/cat-file commit/, $c->{c});
2170                 shift @log while ($log[0] ne "\n");
2171                 shift @log;
2172                 @{$c->{l}} = grep !/^git-svn-id: /, @log;
2174                 (undef, $c->{r}, undef) = ::extract_metadata(
2175                                 (grep(/^git-svn-id: /, @log))[-1]);
2176         }
2177         return defined $c->{r};
2180 sub log_use_color {
2181         return 1 if $color;
2182         my ($dc, $dcvar);
2183         $dcvar = 'color.diff';
2184         $dc = `git-config --get $dcvar`;
2185         if ($dc eq '') {
2186                 # nothing at all; fallback to "diff.color"
2187                 $dcvar = 'diff.color';
2188                 $dc = `git-config --get $dcvar`;
2189         }
2190         chomp($dc);
2191         if ($dc eq 'auto') {
2192                 my $pc;
2193                 $pc = `git-config --get color.pager`;
2194                 if ($pc eq '') {
2195                         # does not have it -- fallback to pager.color
2196                         $pc = `git-config --bool --get pager.color`;
2197                 }
2198                 else {
2199                         $pc = `git-config --bool --get color.pager`;
2200                         if ($?) {
2201                                 $pc = 'false';
2202                         }
2203                 }
2204                 chomp($pc);
2205                 if (-t *STDOUT || (defined $pager && $pc eq 'true')) {
2206                         return ($ENV{TERM} && $ENV{TERM} ne 'dumb');
2207                 }
2208                 return 0;
2209         }
2210         return 0 if $dc eq 'never';
2211         return 1 if $dc eq 'always';
2212         chomp($dc = `git-config --bool --get $dcvar`);
2213         return ($dc eq 'true');
2216 sub git_svn_log_cmd {
2217         my ($r_min, $r_max) = @_;
2218         my $gs = Git::SVN->_new;
2219         my @cmd = (qw/log --abbrev-commit --pretty=raw --default/,
2220                    $gs->refname);
2221         push @cmd, '-r' unless $non_recursive;
2222         push @cmd, qw/--raw --name-status/ if $verbose;
2223         push @cmd, '--color' if log_use_color();
2224         return @cmd unless defined $r_max;
2225         if ($r_max == $r_min) {
2226                 push @cmd, '--max-count=1';
2227                 if (my $c = $gs->rev_db_get($r_max)) {
2228                         push @cmd, $c;
2229                 }
2230         } else {
2231                 my ($c_min, $c_max);
2232                 $c_max = $gs->rev_db_get($r_max);
2233                 $c_min = $gs->rev_db_get($r_min);
2234                 if (defined $c_min && defined $c_max) {
2235                         if ($r_max > $r_max) {
2236                                 push @cmd, "$c_min..$c_max";
2237                         } else {
2238                                 push @cmd, "$c_max..$c_min";
2239                         }
2240                 } elsif ($r_max > $r_min) {
2241                         push @cmd, $c_max;
2242                 } else {
2243                         push @cmd, $c_min;
2244                 }
2245         }
2246         return @cmd;
2249 # adapted from pager.c
2250 sub config_pager {
2251         $pager ||= $ENV{GIT_PAGER} || $ENV{PAGER};
2252         if (!defined $pager) {
2253                 $pager = 'less';
2254         } elsif (length $pager == 0 || $pager eq 'cat') {
2255                 $pager = undef;
2256         }
2259 sub run_pager {
2260         return unless -t *STDOUT;
2261         pipe my $rfd, my $wfd or return;
2262         defined(my $pid = fork) or ::fatal "Can't fork: $!\n";
2263         if (!$pid) {
2264                 open STDOUT, '>&', $wfd or
2265                                      ::fatal "Can't redirect to stdout: $!\n";
2266                 return;
2267         }
2268         open STDIN, '<&', $rfd or ::fatal "Can't redirect stdin: $!\n";
2269         $ENV{LESS} ||= 'FRSX';
2270         exec $pager or ::fatal "Can't run pager: $! ($pager)\n";
2273 sub get_author_info {
2274         my ($dest, $author, $t, $tz) = @_;
2275         $author =~ s/(?:^\s*|\s*$)//g;
2276         $dest->{a_raw} = $author;
2277         my $au;
2278         if ($::_authors) {
2279                 $au = $rusers{$author} || undef;
2280         }
2281         if (!$au) {
2282                 ($au) = ($author =~ /<([^>]+)\@[^>]+>$/);
2283         }
2284         $dest->{t} = $t;
2285         $dest->{tz} = $tz;
2286         $dest->{a} = $au;
2287         # Date::Parse isn't in the standard Perl distro :(
2288         if ($tz =~ s/^\+//) {
2289                 $t += ::tz_to_s_offset($tz);
2290         } elsif ($tz =~ s/^\-//) {
2291                 $t -= ::tz_to_s_offset($tz);
2292         }
2293         $dest->{t_utc} = $t;
2296 sub process_commit {
2297         my ($c, $r_min, $r_max, $defer) = @_;
2298         if (defined $r_min && defined $r_max) {
2299                 if ($r_min == $c->{r} && $r_min == $r_max) {
2300                         show_commit($c);
2301                         return 0;
2302                 }
2303                 return 1 if $r_min == $r_max;
2304                 if ($r_min < $r_max) {
2305                         # we need to reverse the print order
2306                         return 0 if (defined $limit && --$limit < 0);
2307                         push @$defer, $c;
2308                         return 1;
2309                 }
2310                 if ($r_min != $r_max) {
2311                         return 1 if ($r_min < $c->{r});
2312                         return 1 if ($r_max > $c->{r});
2313                 }
2314         }
2315         return 0 if (defined $limit && --$limit < 0);
2316         show_commit($c);
2317         return 1;
2320 sub show_commit {
2321         my $c = shift;
2322         if ($oneline) {
2323                 my $x = "\n";
2324                 if (my $l = $c->{l}) {
2325                         while ($l->[0] =~ /^\s*$/) { shift @$l }
2326                         $x = $l->[0];
2327                 }
2328                 $l_fmt ||= 'A' . length($c->{r});
2329                 print 'r',pack($l_fmt, $c->{r}),' | ';
2330                 print "$c->{c} | " if $show_commit;
2331                 print $x;
2332         } else {
2333                 show_commit_normal($c);
2334         }
2337 sub show_commit_changed_paths {
2338         my ($c) = @_;
2339         return unless $c->{changed};
2340         print "Changed paths:\n", @{$c->{changed}};
2343 sub show_commit_normal {
2344         my ($c) = @_;
2345         print '-' x72, "\nr$c->{r} | ";
2346         print "$c->{c} | " if $show_commit;
2347         print "$c->{a} | ", strftime("%Y-%m-%d %H:%M:%S %z (%a, %d %b %Y)",
2348                                  localtime($c->{t_utc})), ' | ';
2349         my $nr_line = 0;
2351         if (my $l = $c->{l}) {
2352                 while ($l->[$#$l] eq "\n" && $#$l > 0
2353                                           && $l->[($#$l - 1)] eq "\n") {
2354                         pop @$l;
2355                 }
2356                 $nr_line = scalar @$l;
2357                 if (!$nr_line) {
2358                         print "1 line\n\n\n";
2359                 } else {
2360                         if ($nr_line == 1) {
2361                                 $nr_line = '1 line';
2362                         } else {
2363                                 $nr_line .= ' lines';
2364                         }
2365                         print $nr_line, "\n";
2366                         show_commit_changed_paths($c);
2367                         print "\n";
2368                         print $_ foreach @$l;
2369                 }
2370         } else {
2371                 print "1 line\n";
2372                 show_commit_changed_paths($c);
2373                 print "\n";
2375         }
2376         foreach my $x (qw/raw diff/) {
2377                 if ($c->{$x}) {
2378                         print "\n";
2379                         print $_ foreach @{$c->{$x}}
2380                 }
2381         }
2384 sub cmd_show_log {
2385         my (@args) = @_;
2386         my ($r_min, $r_max);
2387         my $r_last = -1; # prevent dupes
2388         if (defined $TZ) {
2389                 $ENV{TZ} = $TZ;
2390         } else {
2391                 delete $ENV{TZ};
2392         }
2393         if (defined $::_revision) {
2394                 if ($::_revision =~ /^(\d+):(\d+)$/) {
2395                         ($r_min, $r_max) = ($1, $2);
2396                 } elsif ($::_revision =~ /^\d+$/) {
2397                         $r_min = $r_max = $::_revision;
2398                 } else {
2399                         ::fatal "-r$::_revision is not supported, use ",
2400                                 "standard \'git log\' arguments instead\n";
2401                 }
2402         }
2404         config_pager();
2405         @args = (git_svn_log_cmd($r_min, $r_max), @args);
2406         my $log = command_output_pipe(@args);
2407         run_pager();
2408         my (@k, $c, $d);
2409         my $esc_color = qr/(?:\033\[(?:(?:\d+;)*\d*)?m)*/;
2410         while (<$log>) {
2411                 if (/^${esc_color}commit ($::sha1_short)/o) {
2412                         my $cmt = $1;
2413                         if ($c && cmt_showable($c) && $c->{r} != $r_last) {
2414                                 $r_last = $c->{r};
2415                                 process_commit($c, $r_min, $r_max, \@k) or
2416                                                                 goto out;
2417                         }
2418                         $d = undef;
2419                         $c = { c => $cmt };
2420                 } elsif (/^${esc_color}author (.+) (\d+) ([\-\+]?\d+)$/o) {
2421                         get_author_info($c, $1, $2, $3);
2422                 } elsif (/^${esc_color}(?:tree|parent|committer) /o) {
2423                         # ignore
2424                 } elsif (/^${esc_color}:\d{6} \d{6} $::sha1_short/o) {
2425                         push @{$c->{raw}}, $_;
2426                 } elsif (/^${esc_color}[ACRMDT]\t/) {
2427                         # we could add $SVN->{svn_path} here, but that requires
2428                         # remote access at the moment (repo_path_split)...
2429                         s#^(${esc_color})([ACRMDT])\t#$1   $2 #o;
2430                         push @{$c->{changed}}, $_;
2431                 } elsif (/^${esc_color}diff /o) {
2432                         $d = 1;
2433                         push @{$c->{diff}}, $_;
2434                 } elsif ($d) {
2435                         push @{$c->{diff}}, $_;
2436                 } elsif (/^${esc_color}    (git-svn-id:.+)$/o) {
2437                         ($c->{url}, $c->{r}, undef) = ::extract_metadata($1);
2438                 } elsif (s/^${esc_color}    //o) {
2439                         push @{$c->{l}}, $_;
2440                 }
2441         }
2442         if ($c && defined $c->{r} && $c->{r} != $r_last) {
2443                 $r_last = $c->{r};
2444                 process_commit($c, $r_min, $r_max, \@k);
2445         }
2446         if (@k) {
2447                 my $swap = $r_max;
2448                 $r_max = $r_min;
2449                 $r_min = $swap;
2450                 process_commit($_, $r_min, $r_max) foreach reverse @k;
2451         }
2452 out:
2453         close $log;
2454         print '-' x72,"\n" unless $incremental || $oneline;
2457 package Git::SVN::Migration;
2458 # these version numbers do NOT correspond to actual version numbers
2459 # of git nor git-svn.  They are just relative.
2461 # v0 layout: .git/$id/info/url, refs/heads/$id-HEAD
2463 # v1 layout: .git/$id/info/url, refs/remotes/$id
2465 # v2 layout: .git/svn/$id/info/url, refs/remotes/$id
2467 # v3 layout: .git/svn/$id, refs/remotes/$id
2468 #            - info/url may remain for backwards compatibility
2469 #            - this is what we migrate up to this layout automatically,
2470 #            - this will be used by git svn init on single branches
2472 # v4 layout: .git/svn/$repo_id/$id, refs/remotes/$repo_id/$id
2473 #            - this is only created for newly multi-init-ed
2474 #              repositories.  Similar in spirit to the
2475 #              --use-separate-remotes option in git-clone (now default)
2476 #            - we do not automatically migrate to this (following
2477 #              the example set by core git)
2478 use strict;
2479 use warnings;
2480 use Carp qw/croak/;
2481 use File::Path qw/mkpath/;
2482 use File::Basename qw/dirname basename/;
2483 use vars qw/$_minimize/;
2485 sub migrate_from_v0 {
2486         my $git_dir = $ENV{GIT_DIR};
2487         return undef unless -d $git_dir;
2488         my ($fh, $ctx) = command_output_pipe(qw/rev-parse --symbolic --all/);
2489         my $migrated = 0;
2490         while (<$fh>) {
2491                 chomp;
2492                 my ($id, $orig_ref) = ($_, $_);
2493                 next unless $id =~ s#^refs/heads/(.+)-HEAD$#$1#;
2494                 next unless -f "$git_dir/$id/info/url";
2495                 my $new_ref = "refs/remotes/$id";
2496                 if (::verify_ref("$new_ref^0")) {
2497                         print STDERR "W: $orig_ref is probably an old ",
2498                                      "branch used by an ancient version of ",
2499                                      "git-svn.\n",
2500                                      "However, $new_ref also exists.\n",
2501                                      "We will not be able ",
2502                                      "to use this branch until this ",
2503                                      "ambiguity is resolved.\n";
2504                         next;
2505                 }
2506                 print STDERR "Migrating from v0 layout...\n" if !$migrated;
2507                 print STDERR "Renaming ref: $orig_ref => $new_ref\n";
2508                 command_noisy('update-ref', $new_ref, $orig_ref);
2509                 command_noisy('update-ref', '-d', $orig_ref, $orig_ref);
2510                 $migrated++;
2511         }
2512         command_close_pipe($fh, $ctx);
2513         print STDERR "Done migrating from v0 layout...\n" if $migrated;
2514         $migrated;
2517 sub migrate_from_v1 {
2518         my $git_dir = $ENV{GIT_DIR};
2519         my $migrated = 0;
2520         return $migrated unless -d $git_dir;
2521         my $svn_dir = "$git_dir/svn";
2523         # just in case somebody used 'svn' as their $id at some point...
2524         return $migrated if -d $svn_dir && ! -f "$svn_dir/info/url";
2526         print STDERR "Migrating from a git-svn v1 layout...\n";
2527         mkpath([$svn_dir]);
2528         print STDERR "Data from a previous version of git-svn exists, but\n\t",
2529                      "$svn_dir\n\t(required for this version ",
2530                      "($::VERSION) of git-svn) does not. exist\n";
2531         my ($fh, $ctx) = command_output_pipe(qw/rev-parse --symbolic --all/);
2532         while (<$fh>) {
2533                 my $x = $_;
2534                 next unless $x =~ s#^refs/remotes/##;
2535                 chomp $x;
2536                 next unless -f "$git_dir/$x/info/url";
2537                 my $u = eval { ::file_to_s("$git_dir/$x/info/url") };
2538                 next unless $u;
2539                 my $dn = dirname("$git_dir/svn/$x");
2540                 mkpath([$dn]) unless -d $dn;
2541                 if ($x eq 'svn') { # they used 'svn' as GIT_SVN_ID:
2542                         mkpath(["$git_dir/svn/svn"]);
2543                         print STDERR " - $git_dir/$x/info => ",
2544                                         "$git_dir/svn/$x/info\n";
2545                         rename "$git_dir/$x/info", "$git_dir/svn/$x/info" or
2546                                croak "$!: $x";
2547                         # don't worry too much about these, they probably
2548                         # don't exist with repos this old (save for index,
2549                         # and we can easily regenerate that)
2550                         foreach my $f (qw/unhandled.log index .rev_db/) {
2551                                 rename "$git_dir/$x/$f", "$git_dir/svn/$x/$f";
2552                         }
2553                 } else {
2554                         print STDERR " - $git_dir/$x => $git_dir/svn/$x\n";
2555                         rename "$git_dir/$x", "$git_dir/svn/$x" or
2556                                croak "$!: $x";
2557                 }
2558                 $migrated++;
2559         }
2560         command_close_pipe($fh, $ctx);
2561         print STDERR "Done migrating from a git-svn v1 layout\n";
2562         $migrated;
2565 sub read_old_urls {
2566         my ($l_map, $pfx, $path) = @_;
2567         my @dir;
2568         foreach (<$path/*>) {
2569                 if (-r "$_/info/url") {
2570                         $pfx .= '/' if $pfx && $pfx !~ m!/$!;
2571                         my $ref_id = $pfx . basename $_;
2572                         my $url = ::file_to_s("$_/info/url");
2573                         $l_map->{$ref_id} = $url;
2574                 } elsif (-d $_) {
2575                         push @dir, $_;
2576                 }
2577         }
2578         foreach (@dir) {
2579                 my $x = $_;
2580                 $x =~ s!^\Q$ENV{GIT_DIR}\E/svn/!!o;
2581                 read_old_urls($l_map, $x, $_);
2582         }
2585 sub migrate_from_v2 {
2586         my @cfg = command(qw/config -l/);
2587         return if grep /^svn-remote\..+\.url=/, @cfg;
2588         my %l_map;
2589         read_old_urls(\%l_map, '', "$ENV{GIT_DIR}/svn");
2590         my $migrated = 0;
2592         foreach my $ref_id (sort keys %l_map) {
2593                 Git::SVN->init($l_map{$ref_id}, '', $ref_id, $ref_id);
2594                 $migrated++;
2595         }
2596         $migrated;
2599 sub minimize_connections {
2600         my $r = Git::SVN::read_all_remotes();
2601         my $new_urls = {};
2602         my $root_repos = {};
2603         foreach my $repo_id (keys %$r) {
2604                 my $url = $r->{$repo_id}->{url} or next;
2605                 my $fetch = $r->{$repo_id}->{fetch} or next;
2606                 my $ra = Git::SVN::Ra->new($url);
2608                 # skip existing cases where we already connect to the root
2609                 if (($ra->{url} eq $ra->{repos_root}) ||
2610                     (Git::SVN::sanitize_remote_name($ra->{repos_root}) eq
2611                      $repo_id)) {
2612                         $root_repos->{$ra->{url}} = $repo_id;
2613                         next;
2614                 }
2616                 my $root_ra = Git::SVN::Ra->new($ra->{repos_root});
2617                 my $root_path = $ra->{url};
2618                 $root_path =~ s#^\Q$ra->{repos_root}\E/*##;
2619                 foreach my $path (keys %$fetch) {
2620                         my $ref_id = $fetch->{$path};
2621                         my $gs = Git::SVN->new($ref_id, $repo_id, $path);
2623                         # make sure we can read when connecting to
2624                         # a higher level of a repository
2625                         my ($last_rev, undef) = $gs->last_rev_commit;
2626                         if (!defined $last_rev) {
2627                                 $last_rev = eval {
2628                                         $root_ra->get_latest_revnum;
2629                                 };
2630                                 next if $@;
2631                         }
2632                         my $new = $root_path;
2633                         $new .= length $path ? "/$path" : '';
2634                         eval {
2635                                 $root_ra->get_log([$new], $last_rev, $last_rev,
2636                                                   0, 0, 1, sub { });
2637                         };
2638                         next if $@;
2639                         $new_urls->{$ra->{repos_root}}->{$new} =
2640                                 { ref_id => $ref_id,
2641                                   old_repo_id => $repo_id,
2642                                   old_path => $path };
2643                 }
2644         }
2646         my @emptied;
2647         foreach my $url (keys %$new_urls) {
2648                 # see if we can re-use an existing [svn-remote "repo_id"]
2649                 # instead of creating a(n ugly) new section:
2650                 my $repo_id = $root_repos->{$url} ||
2651                               Git::SVN::sanitize_remote_name($url);
2653                 my $fetch = $new_urls->{$url};
2654                 foreach my $path (keys %$fetch) {
2655                         my $x = $fetch->{$path};
2656                         Git::SVN->init($url, $path, $repo_id, $x->{ref_id});
2657                         my $pfx = "svn-remote.$x->{old_repo_id}";
2659                         my $old_fetch = quotemeta("$x->{old_path}:".
2660                                                   "refs/remotes/$x->{ref_id}");
2661                         command_noisy(qw/repo-config --unset/,
2662                                       "$pfx.fetch", '^'. $old_fetch . '$');
2663                         delete $r->{$x->{old_repo_id}}->
2664                                {fetch}->{$x->{old_path}};
2665                         if (!keys %{$r->{$x->{old_repo_id}}->{fetch}}) {
2666                                 command_noisy(qw/repo-config --unset/,
2667                                               "$pfx.url");
2668                                 push @emptied, $x->{old_repo_id}
2669                         }
2670                 }
2671         }
2672         if (@emptied) {
2673                 my $file = $ENV{GIT_CONFIG} || $ENV{GIT_CONFIG_LOCAL} ||
2674                            "$ENV{GIT_DIR}/config";
2675                 print STDERR <<EOF;
2676 The following [svn-remote] sections in your config file ($file) are empty
2677 and can be safely removed:
2678 EOF
2679                 print STDERR "[svn-remote \"$_\"]\n" foreach @emptied;
2680         }
2683 sub migration_check {
2684         migrate_from_v0();
2685         migrate_from_v1();
2686         migrate_from_v2();
2687         minimize_connections() if $_minimize;
2690 __END__
2692 Data structures:
2694 $log_entry hashref as returned by libsvn_log_entry()
2696         log => 'whitespace-formatted log entry
2697 ',                                              # trailing newline is preserved
2698         revision => '8',                        # integer
2699         date => '2004-02-24T17:01:44.108345Z',  # commit date
2700         author => 'committer name'
2701 };
2703 @mods = array of diff-index line hashes, each element represents one line
2704         of diff-index output
2706 diff-index line ($m hash)
2708         mode_a => first column of diff-index output, no leading ':',
2709         mode_b => second column of diff-index output,
2710         sha1_b => sha1sum of the final blob,
2711         chg => change type [MCRADT],
2712         file_a => original file name of a file (iff chg is 'C' or 'R')
2713         file_b => new/current file name of a file (any chg)
2717 # retval of read_url_paths{,_all}();
2718 $l_map = {
2719         # repository root url
2720         'https://svn.musicpd.org' => {
2721                 # repository path               # GIT_SVN_ID
2722                 'mpd/trunk'             =>      'trunk',
2723                 'mpd/tags/0.11.5'       =>      'tags/0.11.5',
2724         },
2727 Notes:
2728         I don't trust the each() function on unless I created %hash myself
2729         because the internal iterator may not have started at base.