Code

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