Code

git-svn: cleanup remove unused function
[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 @gs;
420         foreach (command(qw/config -l/)) {
421                 next unless m!^svn-remote\.(.+)\.fetch=
422                               \s*(.*)\s*:\s*refs/remotes/(.+)\s*$!x;
423                 my ($repo_id, $path, $ref_id) = ($1, $2, $3);
424                 push @gs, Git::SVN->new($ref_id, $repo_id, $path);
425         }
426         foreach (@gs) {
427                 $_->fetch;
428         }
431 # this command is special because it requires no metadata
432 sub cmd_commit_diff {
433         my ($ta, $tb, $url) = @_;
434         my $usage = "Usage: $0 commit-diff -r<revision> ".
435                     "<tree-ish> <tree-ish> [<URL>]\n";
436         fatal($usage) if (!defined $ta || !defined $tb);
437         my $svn_path;
438         if (!defined $url) {
439                 my $gs = eval { Git::SVN->new };
440                 if (!$gs) {
441                         fatal("Needed URL or usable git-svn --id in ",
442                               "the command-line\n", $usage);
443                 }
444                 $url = $gs->{url};
445                 $svn_path = $gs->{path};
446         }
447         unless (defined $_revision) {
448                 fatal("-r|--revision is a required argument\n", $usage);
449         }
450         if (defined $_message && defined $_file) {
451                 fatal("Both --message/-m and --file/-F specified ",
452                       "for the commit message.\n",
453                       "I have no idea what you mean\n");
454         }
455         if (defined $_file) {
456                 $_message = file_to_s($_file);
457         } else {
458                 $_message ||= get_commit_entry($tb)->{log};
459         }
460         my $ra ||= Git::SVN::Ra->new($url);
461         $svn_path ||= $ra->{svn_path};
462         my $r = $_revision;
463         if ($r eq 'HEAD') {
464                 $r = $ra->get_latest_revnum;
465         } elsif ($r !~ /^\d+$/) {
466                 die "revision argument: $r not understood by git-svn\n";
467         }
468         my %ed_opts = ( r => $r,
469                         log => $_message,
470                         ra => $ra,
471                         tree_a => $ta,
472                         tree_b => $tb,
473                         editor_cb => sub { print "Committed r$_[0]\n" },
474                         svn_path => $svn_path );
475         if (!SVN::Git::Editor->new(\%ed_opts)->apply_diff) {
476                 print "No changes\n$ta == $tb\n";
477         }
480 ########################### utility functions #########################
482 sub parse_revision_argument {
483         if (!defined $_revision || $_revision eq 'BASE:HEAD') {
484                 return (undef, undef);
485         }
486         return ($1, $2) if ($_revision =~ /^(\d+):(\d+)$/);
487         return ($_revision, $_revision) if ($_revision =~ /^\d+$/);
488         return (undef, $1) if ($_revision =~ /^BASE:(\d+)$/);
489         return ($1, undef) if ($_revision =~ /^(\d+):HEAD$/);
490         die "revision argument: $_revision not understood by git-svn\n",
491             "Try using the command-line svn client instead\n";
494 sub complete_svn_url {
495         my ($url, $path) = @_;
496         $path =~ s#/+$##;
497         if ($path !~ m#^[a-z\+]+://#) {
498                 if (!defined $url || $url !~ m#^[a-z\+]+://#) {
499                         fatal("E: '$path' is not a complete URL ",
500                               "and a separate URL is not specified\n");
501                 }
502                 return ($url, $path);
503         }
504         return ($path, '');
507 sub complete_url_ls_init {
508         my ($ra, $repo_path, $switch, $pfx) = @_;
509         unless ($repo_path) {
510                 print STDERR "W: $switch not specified\n";
511                 return;
512         }
513         $repo_path =~ s#/+$##;
514         if ($repo_path =~ m#^[a-z\+]+://#) {
515                 $ra = Git::SVN::Ra->new($repo_path);
516                 $repo_path = '';
517         } else {
518                 $repo_path =~ s#^/+##;
519                 unless ($ra) {
520                         fatal("E: '$repo_path' is not a complete URL ",
521                               "and a separate URL is not specified\n");
522                 }
523         }
524         my $r = defined $_revision ? $_revision : $ra->get_latest_revnum;
525         my ($dirent, undef, undef) = $ra->get_dir($repo_path, $r);
526         my $url = $ra->{url};
527         foreach my $d (sort keys %$dirent) {
528                 next if ($dirent->{$d}->kind != $SVN::Node::dir);
529                 my $path =  "$repo_path/$d";
530                 my $ref = "$pfx$d";
531                 my $gs = eval { Git::SVN->new($ref) };
532                 # don't try to init already existing refs
533                 unless ($gs) {
534                         print "init $url/$path => $ref\n";
535                         Git::SVN->init($url, $path, undef, $ref);
536                 }
537         }
540 sub verify_ref {
541         my ($ref) = @_;
542         eval { command_oneline([ 'rev-parse', '--verify', $ref ],
543                                { STDERR => 0 }); };
546 sub get_tree_from_treeish {
547         my ($treeish) = @_;
548         # $treeish can be a symbolic ref, too:
549         my $type = command_oneline(qw/cat-file -t/, $treeish);
550         my $expected;
551         while ($type eq 'tag') {
552                 ($treeish, $type) = command(qw/cat-file tag/, $treeish);
553         }
554         if ($type eq 'commit') {
555                 $expected = (grep /^tree /, command(qw/cat-file commit/,
556                                                     $treeish))[0];
557                 ($expected) = ($expected =~ /^tree ($sha1)$/o);
558                 die "Unable to get tree from $treeish\n" unless $expected;
559         } elsif ($type eq 'tree') {
560                 $expected = $treeish;
561         } else {
562                 die "$treeish is a $type, expected tree, tag or commit\n";
563         }
564         return $expected;
567 sub get_commit_entry {
568         my ($treeish) = shift;
569         my %log_entry = ( log => '', tree => get_tree_from_treeish($treeish) );
570         my $commit_editmsg = "$ENV{GIT_DIR}/COMMIT_EDITMSG";
571         my $commit_msg = "$ENV{GIT_DIR}/COMMIT_MSG";
572         open my $log_fh, '>', $commit_editmsg or croak $!;
574         my $type = command_oneline(qw/cat-file -t/, $treeish);
575         if ($type eq 'commit' || $type eq 'tag') {
576                 my ($msg_fh, $ctx) = command_output_pipe('cat-file',
577                                                          $type, $treeish);
578                 my $in_msg = 0;
579                 while (<$msg_fh>) {
580                         if (!$in_msg) {
581                                 $in_msg = 1 if (/^\s*$/);
582                         } elsif (/^git-svn-id: /) {
583                                 # skip this for now, we regenerate the
584                                 # correct one on re-fetch anyways
585                                 # TODO: set *:merge properties or like...
586                         } else {
587                                 print $log_fh $_ or croak $!;
588                         }
589                 }
590                 command_close_pipe($msg_fh, $ctx);
591         }
592         close $log_fh or croak $!;
594         if ($_edit || ($type eq 'tree')) {
595                 my $editor = $ENV{VISUAL} || $ENV{EDITOR} || 'vi';
596                 # TODO: strip out spaces, comments, like git-commit.sh
597                 system($editor, $commit_editmsg);
598         }
599         rename $commit_editmsg, $commit_msg or croak $!;
600         open $log_fh, '<', $commit_msg or croak $!;
601         { local $/; chomp($log_entry{log} = <$log_fh>); }
602         close $log_fh or croak $!;
603         unlink $commit_msg;
604         \%log_entry;
607 sub s_to_file {
608         my ($str, $file, $mode) = @_;
609         open my $fd,'>',$file or croak $!;
610         print $fd $str,"\n" or croak $!;
611         close $fd or croak $!;
612         chmod ($mode &~ umask, $file) if (defined $mode);
615 sub file_to_s {
616         my $file = shift;
617         open my $fd,'<',$file or croak "$!: file: $file\n";
618         local $/;
619         my $ret = <$fd>;
620         close $fd or croak $!;
621         $ret =~ s/\s*$//s;
622         return $ret;
625 # '<svn username> = real-name <email address>' mapping based on git-svnimport:
626 sub load_authors {
627         open my $authors, '<', $_authors or die "Can't open $_authors $!\n";
628         my $log = $cmd eq 'log';
629         while (<$authors>) {
630                 chomp;
631                 next unless /^(\S+?|\(no author\))\s*=\s*(.+?)\s*<(.+)>\s*$/;
632                 my ($user, $name, $email) = ($1, $2, $3);
633                 if ($log) {
634                         $Git::SVN::Log::rusers{"$name <$email>"} = $user;
635                 } else {
636                         $users{$user} = [$name, $email];
637                 }
638         }
639         close $authors or croak $!;
642 # convert GetOpt::Long specs for use by git-config
643 sub read_repo_config {
644         return unless -d $ENV{GIT_DIR};
645         my $opts = shift;
646         foreach my $o (keys %$opts) {
647                 my $v = $opts->{$o};
648                 my ($key) = ($o =~ /^([a-z\-]+)/);
649                 $key =~ s/-//g;
650                 my $arg = 'git-config';
651                 $arg .= ' --int' if ($o =~ /[:=]i$/);
652                 $arg .= ' --bool' if ($o !~ /[:=][sfi]$/);
653                 if (ref $v eq 'ARRAY') {
654                         chomp(my @tmp = `$arg --get-all svn.$key`);
655                         @$v = @tmp if @tmp;
656                 } else {
657                         chomp(my $tmp = `$arg --get svn.$key`);
658                         if ($tmp && !($arg =~ / --bool/ && $tmp eq 'false')) {
659                                 $$v = $tmp;
660                         }
661                 }
662         }
665 sub extract_metadata {
666         my $id = shift or return (undef, undef, undef);
667         my ($url, $rev, $uuid) = ($id =~ /^git-svn-id:\s(\S+?)\@(\d+)
668                                                         \s([a-f\d\-]+)$/x);
669         if (!defined $rev || !$uuid || !$url) {
670                 # some of the original repositories I made had
671                 # identifiers like this:
672                 ($rev, $uuid) = ($id =~/^git-svn-id:\s(\d+)\@([a-f\d\-]+)/);
673         }
674         return ($url, $rev, $uuid);
677 sub cmt_metadata {
678         return extract_metadata((grep(/^git-svn-id: /,
679                 command(qw/cat-file commit/, shift)))[-1]);
682 package Git::SVN;
683 use strict;
684 use warnings;
685 use vars qw/$default_repo_id $default_ref_id/;
686 use Carp qw/croak/;
687 use File::Path qw/mkpath/;
688 use IPC::Open3;
690 # properties that we do not log:
691 my %SKIP_PROP;
692 BEGIN {
693         %SKIP_PROP = map { $_ => 1 } qw/svn:wc:ra_dav:version-url
694                                         svn:special svn:executable
695                                         svn:entry:committed-rev
696                                         svn:entry:last-author
697                                         svn:entry:uuid
698                                         svn:entry:committed-date/;
701 sub read_all_remotes {
702         my $r = {};
703         foreach (grep { s/^svn-remote\.// } command(qw/config -l/)) {
704                 if (m!^(.+)\.fetch=\s*(.*)\s*:\s*refs/remotes/(.+)\s*$!) {
705                         $r->{$1}->{fetch}->{$2} = $3;
706                 } elsif (m!^(.+)\.url=\s*(.*)\s*$!) {
707                         $r->{$1}->{url} = $2;
708                 }
709         }
710         $r;
713 sub verify_remotes_sanity {
714         return unless -d $ENV{GIT_DIR};
715         my %seen;
716         foreach (command(qw/config -l/)) {
717                 if (m!^svn-remote\.(?:.+)\.fetch=.*:refs/remotes/(\S+)\s*$!) {
718                         if ($seen{$1}) {
719                                 die "Remote ref refs/remote/$1 is tracked by",
720                                     "\n  \"$_\"\nand\n  \"$seen{$1}\"\n",
721                                     "Please resolve this ambiguity in ",
722                                     "your git configuration file before ",
723                                     "continuing\n";
724                         }
725                         $seen{$1} = $_;
726                 }
727         }
730 # we allow more chars than remotes2config.sh...
731 sub sanitize_remote_name {
732         my ($name) = @_;
733         $name =~ tr{A-Za-z0-9:,/+-}{.}c;
734         $name;
737 sub find_existing_remote {
738         my ($url, $remotes) = @_;
739         my $existing;
740         foreach my $repo_id (keys %$remotes) {
741                 my $u = $remotes->{$repo_id}->{url} or next;
742                 next if $u ne $url;
743                 $existing = $repo_id;
744                 last;
745         }
746         $existing;
749 sub init_remote_config {
750         my ($self, $url) = @_;
751         $url =~ s!/+$!!; # strip trailing slash
752         my $r = read_all_remotes();
753         my $existing = find_existing_remote($url, $r);
754         if ($existing) {
755                 print STDERR "Using existing ",
756                              "[svn-remote \"$existing\"]\n";
757                 $self->{repo_id} = $existing;
758         } else {
759                 my $min_url = Git::SVN::Ra->new($url)->minimize_url;
760                 $existing = find_existing_remote($min_url, $r);
761                 if ($existing) {
762                         print STDERR "Using existing ",
763                                      "[svn-remote \"$existing\"]\n";
764                         $self->{repo_id} = $existing;
765                 }
766                 if ($min_url ne $url) {
767                         print STDERR "Using higher level of URL: ",
768                                      "$url => $min_url\n";
769                         my $old_path = $self->{path};
770                         $self->{path} = $url;
771                         $self->{path} =~ s!^\Q$min_url\E/*!!;
772                         if (length $old_path) {
773                                 $self->{path} .= "/$old_path";
774                         }
775                         $url = $min_url;
776                 }
777         }
778         my $orig_url;
779         if (!$existing) {
780                 # verify that we aren't overwriting anything:
781                 $orig_url = eval {
782                         command_oneline('config', '--get',
783                                         "svn-remote.$self->{repo_id}.url")
784                 };
785                 if ($orig_url && ($orig_url ne $url)) {
786                         die "svn-remote.$self->{repo_id}.url already set: ",
787                             "$orig_url\nwanted to set to: $url\n";
788                 }
789         }
790         my ($xrepo_id, $xpath) = find_ref($self->refname);
791         if (defined $xpath) {
792                 die "svn-remote.$xrepo_id.fetch already set to track ",
793                     "$xpath:refs/remotes/", $self->refname, "\n";
794         }
795         command_noisy('config',
796                       "svn-remote.$self->{repo_id}.url", $url);
797         command_noisy('config', '--add',
798                       "svn-remote.$self->{repo_id}.fetch",
799                       "$self->{path}:".$self->refname);
800         $self->{url} = $url;
803 sub init {
804         my ($class, $url, $path, $repo_id, $ref_id) = @_;
805         my $self = _new($class, $repo_id, $ref_id, $path);
806         if (defined $url) {
807                 $self->init_remote_config($url);
808         }
809         $self;
812 sub find_ref {
813         my ($ref_id) = @_;
814         foreach (command(qw/config -l/)) {
815                 next unless m!^svn-remote\.(.+)\.fetch=
816                               \s*(.*)\s*:\s*refs/remotes/(.+)\s*$!x;
817                 my ($repo_id, $path, $ref) = ($1, $2, $3);
818                 if ($ref eq $ref_id) {
819                         $path = '' if ($path =~ m#^\./?#);
820                         return ($repo_id, $path);
821                 }
822         }
823         (undef, undef, undef);
826 sub new {
827         my ($class, $ref_id, $repo_id, $path) = @_;
828         if (defined $ref_id && !defined $repo_id && !defined $path) {
829                 ($repo_id, $path) = find_ref($ref_id);
830                 if (!defined $repo_id) {
831                         die "Could not find a \"svn-remote.*.fetch\" key ",
832                             "in the repository configuration matching: ",
833                             "refs/remotes/$ref_id\n";
834                 }
835         }
836         my $self = _new($class, $repo_id, $ref_id, $path);
837         if (!defined $self->{path} || !length $self->{path}) {
838                 my $fetch = command_oneline('config', '--get',
839                                             "svn-remote.$repo_id.fetch",
840                                             ":refs/remotes/$ref_id\$") or
841                      die "Failed to read \"svn-remote.$repo_id.fetch\" ",
842                          "\":refs/remotes/$ref_id\$\" in config\n";
843                 ($self->{path}, undef) = split(/\s*:\s*/, $fetch);
844         }
845         $self->{url} = command_oneline('config', '--get',
846                                        "svn-remote.$repo_id.url") or
847                   die "Failed to read \"svn-remote.$repo_id.url\" in config\n";
848         $self;
851 sub refname { "refs/remotes/$_[0]->{ref_id}" }
853 sub ra {
854         my ($self) = shift;
855         $self->{ra} ||= Git::SVN::Ra->new($self->{url});
858 sub rel_path {
859         my ($self) = @_;
860         my $repos_root = $self->ra->{repos_root};
861         return $self->{path} if ($self->{url} eq $repos_root);
862         my $url = $self->{url} .
863                   (length $self->{path} ? "/$self->{path}" : $self->{path});
864         $url =~ s!^\Q$repos_root\E/*!!g;
865         $url;
868 sub copy_remote_ref {
869         my ($self) = @_;
870         my $origin = $::_cp_remote ? $::_cp_remote : 'origin';
871         my $ref = $self->refname;
872         if (command('ls-remote', $origin, $ref)) {
873                 command_noisy('fetch', $origin, "$ref:$ref");
874         } elsif ($::_cp_remote && !$::_upgrade) {
875                 die "Unable to find remote reference: $ref on $origin\n";
876         }
879 sub traverse_ignore {
880         my ($self, $fh, $path, $r) = @_;
881         $path =~ s#^/+##g;
882         my ($dirent, undef, $props) = $self->ra->get_dir($path, $r);
883         my $p = $path;
884         $p =~ s#^\Q$self->{ra}->{svn_path}\E/##;
885         print $fh length $p ? "\n# $p\n" : "\n# /\n";
886         if (my $s = $props->{'svn:ignore'}) {
887                 $s =~ s/[\r\n]+/\n/g;
888                 chomp $s;
889                 if (length $p == 0) {
890                         $s =~ s#\n#\n/$p#g;
891                         print $fh "/$s\n";
892                 } else {
893                         $s =~ s#\n#\n/$p/#g;
894                         print $fh "/$p/$s\n";
895                 }
896         }
897         foreach (sort keys %$dirent) {
898                 next if $dirent->{$_}->kind != $SVN::Node::dir;
899                 $self->traverse_ignore($fh, "$path/$_", $r);
900         }
903 sub last_rev { ($_[0]->last_rev_commit)[0] }
904 sub last_commit { ($_[0]->last_rev_commit)[1] }
906 # returns the newest SVN revision number and newest commit SHA1
907 sub last_rev_commit {
908         my ($self) = @_;
909         if (defined $self->{last_rev} && defined $self->{last_commit}) {
910                 return ($self->{last_rev}, $self->{last_commit});
911         }
912         my $c = ::verify_ref($self->refname.'^0');
913         if ($c) {
914                 my $rev = (::cmt_metadata($c))[1];
915                 if (defined $rev) {
916                         ($self->{last_rev}, $self->{last_commit}) = ($rev, $c);
917                         return ($rev, $c);
918                 }
919         }
920         my $offset = -41; # from tail
921         my $rl;
922         open my $fh, '<', $self->{db_path} or
923                                  croak "$self->{db_path} not readable: $!\n";
924         seek $fh, $offset, 2;
925         $rl = readline $fh;
926         defined $rl or return (undef, undef);
927         chomp $rl;
928         while ($c ne $rl && tell $fh != 0) {
929                 $offset -= 41;
930                 seek $fh, $offset, 2;
931                 $rl = readline $fh;
932                 defined $rl or return (undef, undef);
933                 chomp $rl;
934         }
935         my $rev = tell $fh;
936         croak $! if ($rev < 0);
937         $rev =  ($rev - 41) / 41;
938         close $fh or croak $!;
939         ($self->{last_rev}, $self->{last_commit}) = ($rev, $c);
940         return ($rev, $c);
943 sub get_fetch_range {
944         my ($self, $min, $max) = @_;
945         $max ||= $self->ra->get_latest_revnum;
946         $min ||= $self->last_rev || 0;
947         (++$min, $max);
950 sub tmp_index_do {
951         my ($self, $sub) = @_;
952         my $old_index = $ENV{GIT_INDEX_FILE};
953         $ENV{GIT_INDEX_FILE} = $self->{index};
954         my @ret = &$sub;
955         if ($old_index) {
956                 $ENV{GIT_INDEX_FILE} = $old_index;
957         } else {
958                 delete $ENV{GIT_INDEX_FILE};
959         }
960         wantarray ? @ret : $ret[0];
963 sub assert_index_clean {
964         my ($self, $treeish) = @_;
966         $self->tmp_index_do(sub {
967                 command_noisy('read-tree', $treeish) unless -e $self->{index};
968                 my $x = command_oneline('write-tree');
969                 my ($y) = (command(qw/cat-file commit/, $treeish) =~
970                            /^tree ($::sha1)/mo);
971                 if ($y ne $x) {
972                         unlink $self->{index} or croak $!;
973                         command_noisy('read-tree', $treeish);
974                 }
975                 $x = command_oneline('write-tree');
976                 if ($y ne $x) {
977                         ::fatal "trees ($treeish) $y != $x\n",
978                                 "Something is seriously wrong...\n";
979                 }
980         });
983 sub get_commit_parents {
984         my ($self, $log_entry, @parents) = @_;
985         my (%seen, @ret, @tmp);
986         # commit parents can be conditionally bound to a particular
987         # svn revision via: "svn_revno=commit_sha1", filter them out here:
988         foreach my $p (@parents) {
989                 next unless defined $p;
990                 if ($p =~ /^(\d+)=($::sha1_short)$/o) {
991                         push @tmp, $2 if $1 == $log_entry->{revision};
992                 } else {
993                         push @tmp, $p if $p =~ /^$::sha1_short$/o;
994                 }
995         }
996         if (my $cur = ::verify_ref($self->refname.'^0')) {
997                 push @tmp, $cur;
998         }
999         push @tmp, $_ foreach (@{$log_entry->{parents}}, @tmp);
1000         while (my $p = shift @tmp) {
1001                 next if $seen{$p};
1002                 $seen{$p} = 1;
1003                 push @ret, $p;
1004                 # MAXPARENT is defined to 16 in commit-tree.c:
1005                 last if @ret >= 16;
1006         }
1007         if (@tmp) {
1008                 die "r$log_entry->{revision}: No room for parents:\n\t",
1009                     join("\n\t", @tmp), "\n";
1010         }
1011         @ret;
1014 sub full_url {
1015         my ($self) = @_;
1016         $self->ra->{url} . (length $self->{path} ? '/' . $self->{path} : '');
1019 sub do_git_commit {
1020         my ($self, $log_entry, @parents) = @_;
1021         if (my $c = $self->rev_db_get($log_entry->{revision})) {
1022                 croak "$log_entry->{revision} = $c already exists! ",
1023                       "Why are we refetching it?\n";
1024         }
1025         my $author = $log_entry->{author};
1026         my ($name, $email) = (defined $::users{$author} ? @{$::users{$author}}
1027                            : ($author, "$author\@".$self->ra->uuid));
1028         $ENV{GIT_AUTHOR_NAME} = $ENV{GIT_COMMITTER_NAME} = $name;
1029         $ENV{GIT_AUTHOR_EMAIL} = $ENV{GIT_COMMITTER_EMAIL} = $email;
1030         $ENV{GIT_AUTHOR_DATE} = $ENV{GIT_COMMITTER_DATE} = $log_entry->{date};
1032         my $tree = $log_entry->{tree};
1033         if (!defined $tree) {
1034                 $tree = $self->tmp_index_do(sub {
1035                                             command_oneline('write-tree') });
1036         }
1037         die "Tree is not a valid sha1: $tree\n" if $tree !~ /^$::sha1$/o;
1039         my @exec = ('git-commit-tree', $tree);
1040         foreach ($self->get_commit_parents($log_entry, @parents)) {
1041                 push @exec, '-p', $_;
1042         }
1043         defined(my $pid = open3(my $msg_fh, my $out_fh, '>&STDERR', @exec))
1044                                                                    or croak $!;
1045         print $msg_fh $log_entry->{log} or croak $!;
1046         print $msg_fh "\ngit-svn-id: ", $self->full_url, '@',
1047                       $log_entry->{revision}, ' ',
1048                       $self->ra->uuid, "\n" or croak $!;
1049         $msg_fh->flush == 0 or croak $!;
1050         close $msg_fh or croak $!;
1051         chomp(my $commit = do { local $/; <$out_fh> });
1052         close $out_fh or croak $!;
1053         waitpid $pid, 0;
1054         croak $? if $?;
1055         if ($commit !~ /^$::sha1$/o) {
1056                 die "Failed to commit, invalid sha1: $commit\n";
1057         }
1059         command_noisy('update-ref',$self->refname, $commit);
1060         $self->rev_db_set($log_entry->{revision}, $commit);
1062         $self->{last_rev} = $log_entry->{revision};
1063         $self->{last_commit} = $commit;
1064         print "r$log_entry->{revision} = $commit\n";
1065         return $commit;
1068 sub revisions_eq {
1069         my ($self, $r0, $r1) = @_;
1070         return 1 if $r0 == $r1;
1071         my $nr = 0;
1072         $self->ra->get_log([$self->{path}], $r0, $r1,
1073                            0, 0, 1, sub { $nr++ });
1074         return 0 if ($nr > 1);
1075         return 1;
1078 sub find_parent_branch {
1079         my ($self, $paths, $rev) = @_;
1080         return undef unless $::_follow_parent;
1081         unless (defined $paths) {
1082                 $self->ra->get_log([$self->{path}], $rev, $rev, 0, 1, 1,
1083                                    sub { $paths = dup_changed_paths($_[0]) });
1084         }
1085         return undef unless defined $paths;
1087         # look for a parent from another branch:
1088         my @b_path_components = split m#/#, $self->rel_path;
1089         my @a_path_components;
1090         my $i;
1091         while (@b_path_components) {
1092                 $i = $paths->{'/'.join('/', @b_path_components)};
1093                 last if $i;
1094                 unshift(@a_path_components, pop(@b_path_components));
1095         }
1096         goto not_found unless defined $i;
1097         my $branch_from = $i->{copyfrom_path} or goto not_found;
1098         if (@a_path_components) {
1099                 print STDERR "branch_from: $branch_from => ";
1100                 $branch_from .= '/'.join('/', @a_path_components);
1101                 print STDERR $branch_from, "\n";
1102         }
1103         my $r = $i->{copyfrom_rev};
1104         my $repos_root = $self->ra->{repos_root};
1105         my $url = $self->ra->{url};
1106         my $new_url = $repos_root . $branch_from;
1107         print STDERR  "Found possible branch point: ",
1108                       "$new_url => ", $self->full_url, ", $r\n";
1109         $branch_from =~ s#^/##;
1110         my $remotes = read_all_remotes();
1111         my $gs;
1112         foreach my $repo_id (keys %$remotes) {
1113                 my $u = $remotes->{$repo_id}->{url} or next;
1114                 next if $url ne $u;
1115                 my $fetch = $remotes->{$repo_id}->{fetch};
1116                 foreach my $f (keys %$fetch) {
1117                         next if $f ne $branch_from;
1118                         $gs = Git::SVN->new($fetch->{$f}, $repo_id, $f);
1119                         last;
1120                 }
1121                 last if $gs;
1122         }
1123         unless ($gs) {
1124                 my $ref_id = $branch_from;
1125                 $ref_id .= "\@$r" if find_ref($ref_id);
1126                 # just grow a tail if we're not unique enough :x
1127                 $ref_id .= '-' while find_ref($ref_id);
1128                 $gs = Git::SVN->init($new_url, '', $ref_id, $ref_id);
1129         }
1130         my ($r0, $parent) = $gs->find_rev_before($r, 1);
1131         if ($::_follow_parent && (!defined $r0 || !defined $parent)) {
1132                 $gs->fetch(0, $r);
1133                 ($r0, $parent) = $gs->last_rev_commit;
1134         }
1135         if (defined $r0 && defined $parent && $gs->revisions_eq($r0, $r)) {
1136                 print STDERR "Found branch parent: ($self->{ref_id}) $parent\n";
1137                 $self->assert_index_clean($parent);
1138                 my $ed;
1139                 if ($self->ra->can_do_switch) {
1140                         print STDERR "Following parent with do_switch\n";
1141                         # do_switch works with svn/trunk >= r22312, but that
1142                         # is not included with SVN 1.4.2 (the latest version
1143                         # at the moment), so we can't rely on it
1144                         $self->{last_commit} = $parent;
1145                         $ed = SVN::Git::Fetcher->new($self);
1146                         $gs->ra->gs_do_switch($r0, $rev, $gs->{path}, 1,
1147                                               $self->full_url, $ed)
1148                           or die "SVN connection failed somewhere...\n";
1149                 } else {
1150                         print STDERR "Following parent with do_update\n";
1151                         $ed = SVN::Git::Fetcher->new($self);
1152                         $self->ra->gs_do_update($rev, $rev, $self->{path},
1153                                                 1, $ed)
1154                           or die "SVN connection failed somewhere...\n";
1155                 }
1156                 return $self->make_log_entry($rev, [$parent], $ed);
1157         }
1158 not_found:
1159         print STDERR "Branch parent for path: '/",
1160                      $self->rel_path, "' @ r$rev not found:\n";
1161         return undef unless $paths;
1162         print STDERR "Changed paths:\n";
1163         foreach my $x (sort keys %$paths) {
1164                 my $p = $paths->{$x};
1165                 print STDERR "\t$p->{action}\t$x";
1166                 if ($p->{copyfrom_path}) {
1167                         print STDERR "(from $p->{copyfrom_path}: ",
1168                                      "$p->{copyfrom_rev})";
1169                 }
1170                 print STDERR "\n";
1171         }
1172         print STDERR '-'x72, "\n";
1173         return undef;
1176 sub do_fetch {
1177         my ($self, $paths, $rev) = @_;
1178         my $ed;
1179         my ($last_rev, @parents);
1180         if ($self->{last_commit}) {
1181                 $ed = SVN::Git::Fetcher->new($self);
1182                 $last_rev = $self->{last_rev};
1183                 $ed->{c} = $self->{last_commit};
1184                 @parents = ($self->{last_commit});
1185         } else {
1186                 $last_rev = $rev;
1187                 if (my $log_entry = $self->find_parent_branch($paths, $rev)) {
1188                         return $log_entry;
1189                 }
1190                 $ed = SVN::Git::Fetcher->new($self);
1191         }
1192         unless ($self->ra->gs_do_update($last_rev, $rev,
1193                                         $self->{path}, 1, $ed)) {
1194                 die "SVN connection failed somewhere...\n";
1195         }
1196         $self->make_log_entry($rev, \@parents, $ed);
1199 sub get_untracked {
1200         my ($self, $ed) = @_;
1201         my @out;
1202         my $h = $ed->{empty};
1203         foreach (sort keys %$h) {
1204                 my $act = $h->{$_} ? '+empty_dir' : '-empty_dir';
1205                 push @out, "  $act: " . uri_encode($_);
1206                 warn "W: $act: $_\n";
1207         }
1208         foreach my $t (qw/dir_prop file_prop/) {
1209                 $h = $ed->{$t} or next;
1210                 foreach my $path (sort keys %$h) {
1211                         my $ppath = $path eq '' ? '.' : $path;
1212                         foreach my $prop (sort keys %{$h->{$path}}) {
1213                                 next if $SKIP_PROP{$prop};
1214                                 my $v = $h->{$path}->{$prop};
1215                                 my $t_ppath_prop = "$t: " .
1216                                                     uri_encode($ppath) . ' ' .
1217                                                     uri_encode($prop);
1218                                 if (defined $v) {
1219                                         push @out, "  +$t_ppath_prop " .
1220                                                    uri_encode($v);
1221                                 } else {
1222                                         push @out, "  -$t_ppath_prop";
1223                                 }
1224                         }
1225                 }
1226         }
1227         foreach my $t (qw/absent_file absent_directory/) {
1228                 $h = $ed->{$t} or next;
1229                 foreach my $parent (sort keys %$h) {
1230                         foreach my $path (sort @{$h->{$parent}}) {
1231                                 push @out, "  $t: " .
1232                                            uri_encode("$parent/$path");
1233                                 warn "W: $t: $parent/$path ",
1234                                      "Insufficient permissions?\n";
1235                         }
1236                 }
1237         }
1238         \@out;
1241 sub parse_svn_date {
1242         my $date = shift || return '+0000 1970-01-01 00:00:00';
1243         my ($Y,$m,$d,$H,$M,$S) = ($date =~ /^(\d{4})\-(\d\d)\-(\d\d)T
1244                                             (\d\d)\:(\d\d)\:(\d\d).\d+Z$/x) or
1245                                          croak "Unable to parse date: $date\n";
1246         "+0000 $Y-$m-$d $H:$M:$S";
1249 sub check_author {
1250         my ($author) = @_;
1251         if (!defined $author || length $author == 0) {
1252                 $author = '(no author)';
1253         }
1254         if (defined $::_authors && ! defined $::users{$author}) {
1255                 die "Author: $author not defined in $::_authors file\n";
1256         }
1257         $author;
1260 sub make_log_entry {
1261         my ($self, $rev, $parents, $ed) = @_;
1262         my $untracked = $self->get_untracked($ed);
1264         return undef if ($ed->{nr} == 0 && scalar @$untracked == 0);
1266         open my $un, '>>', "$self->{dir}/unhandled.log" or croak $!;
1267         print $un "r$rev\n" or croak $!;
1268         print $un $_, "\n" foreach @$untracked;
1269         my %log_entry = ( parents => $parents || [], revision => $rev,
1270                           log => '');
1271         my $rp = $self->ra->rev_proplist($rev);
1272         foreach (sort keys %$rp) {
1273                 my $v = $rp->{$_};
1274                 if (/^svn:(author|date|log)$/) {
1275                         $log_entry{$1} = $v;
1276                 } else {
1277                         print $un "  rev_prop: ", uri_encode($_), ' ',
1278                                   uri_encode($v), "\n";
1279                 }
1280         }
1281         close $un or croak $!;
1283         $log_entry{date} = parse_svn_date($log_entry{date});
1284         $log_entry{author} = check_author($log_entry{author});
1285         $log_entry{log} .= "\n";
1286         \%log_entry;
1289 sub fetch {
1290         my ($self, $min_rev, $max_rev, @parents) = @_;
1291         my ($last_rev, $last_commit) = $self->last_rev_commit;
1292         my ($base, $head) = $self->get_fetch_range($min_rev, $max_rev);
1293         return if ($base > $head);
1294         if (defined $last_commit) {
1295                 $self->assert_index_clean($last_commit);
1296         }
1297         my $inc = 1000;
1298         my ($min, $max) = ($base, $head < $base + $inc ? $head : $base + $inc);
1299         my $err_handler = $SVN::Error::handler;
1300         my $err;
1301         $SVN::Error::handler = sub { ($err) = @_; skip_unknown_revs($err); } ;
1302         while (1) {
1303                 my @revs;
1304                 $self->ra->get_log([$self->{path}], $min, $max, 0, 1, 1,
1305                     sub {
1306                         my ($paths, $rev) = @_;
1307                         push @revs, [ dup_changed_paths($paths), $rev ];
1308                         });
1309                 if (! @revs && $err && $max >= $head) {
1310                         print STDERR "Branch probably deleted:\n  ",
1311                                      $err->expanded_message,
1312                                      "\nWill attempt to follow revisions ",
1313                                      "r$min .. r$max",
1314                                      "committed before the deletion\n";
1315                         @revs = map { [ undef, $_ ] } ($min .. $max);
1316                 }
1317                 foreach (@revs) {
1318                         if (my $log_entry = $self->do_fetch(@$_)) {
1319                                 $self->do_git_commit($log_entry, @parents);
1320                         }
1321                 }
1322                 last if $max >= $head;
1323                 $min = $max + 1;
1324                 $max += $inc;
1325                 $max = $head if ($max > $head);
1326         }
1327         $SVN::Error::handler = $err_handler;
1330 sub set_tree_cb {
1331         my ($self, $log_entry, $tree, $rev, $date, $author) = @_;
1332         # TODO: enable and test optimized commits:
1333         if (0 && $rev == ($self->{last_rev} + 1)) {
1334                 $log_entry->{revision} = $rev;
1335                 $log_entry->{author} = $author;
1336                 $self->do_git_commit($log_entry, "$rev=$tree");
1337         } else {
1338                 $self->fetch(undef, undef, "$rev=$tree");
1339         }
1342 sub set_tree {
1343         my ($self, $tree) = (shift, shift);
1344         my $log_entry = ::get_commit_entry($tree);
1345         unless ($self->{last_rev}) {
1346                 fatal("Must have an existing revision to commit\n");
1347         }
1348         my %ed_opts = ( r => $self->{last_rev},
1349                         log => $log_entry->{log},
1350                         ra => $self->ra,
1351                         tree_a => $self->{last_commit},
1352                         tree_b => $tree,
1353                         editor_cb => sub {
1354                                $self->set_tree_cb($log_entry, $tree, @_) },
1355                         svn_path => $self->{path} );
1356         if (!SVN::Git::Editor->new(\%ed_opts)->apply_diff) {
1357                 print "No changes\nr$self->{last_rev} = $tree\n";
1358         }
1361 sub skip_unknown_revs {
1362         my ($err) = @_;
1363         my $errno = $err->apr_err();
1364         # Maybe the branch we're tracking didn't
1365         # exist when the repo started, so it's
1366         # not an error if it doesn't, just continue
1367         #
1368         # Wonderfully consistent library, eh?
1369         # 160013 - svn:// and file://
1370         # 175002 - http(s)://
1371         # 175007 - http(s):// (this repo required authorization, too...)
1372         #   More codes may be discovered later...
1373         if ($errno == 175007 || $errno == 175002 || $errno == 160013) {
1374                 return;
1375         }
1376         croak "Error from SVN, ($errno): ", $err->expanded_message,"\n";
1379 # svn_log_changed_path_t objects passed to get_log are likely to be
1380 # overwritten even if only the refs are copied to an external variable,
1381 # so we should dup the structures in their entirety.  Using an externally
1382 # passed pool (instead of our temporary and quickly cleared pool in
1383 # Git::SVN::Ra) does not help matters at all...
1384 sub dup_changed_paths {
1385         my ($paths) = @_;
1386         return undef unless $paths;
1387         my %ret;
1388         foreach my $p (keys %$paths) {
1389                 my $i = $paths->{$p};
1390                 my %s = map { $_ => $i->$_ }
1391                               qw/copyfrom_path copyfrom_rev action/;
1392                 $ret{$p} = \%s;
1393         }
1394         \%ret;
1397 # rev_db:
1398 # Tie::File seems to be prone to offset errors if revisions get sparse,
1399 # it's not that fast, either.  Tie::File is also not in Perl 5.6.  So
1400 # one of my favorite modules is out :<  Next up would be one of the DBM
1401 # modules, but I'm not sure which is most portable...  So I'll just
1402 # go with something that's plain-text, but still capable of
1403 # being randomly accessed.  So here's my ultra-simple fixed-width
1404 # database.  All records are 40 characters + "\n", so it's easy to seek
1405 # to a revision: (41 * rev) is the byte offset.
1406 # A record of 40 0s denotes an empty revision.
1407 # And yes, it's still pretty fast (faster than Tie::File).
1409 sub rev_db_set {
1410         my ($self, $rev, $commit) = @_;
1411         length $commit == 40 or croak "arg3 must be a full SHA1 hexsum\n";
1412         open my $fh, '+<', $self->{db_path} or croak $!;
1413         my $offset = $rev * 41;
1414         # assume that append is the common case:
1415         seek $fh, 0, 2 or croak $!;
1416         my $pos = tell $fh;
1417         if ($pos < $offset) {
1418                 print $fh (('0' x 40),"\n") x (($offset - $pos) / 41)
1419                   or croak $!;
1420         }
1421         seek $fh, $offset, 0 or croak $!;
1422         print $fh $commit,"\n" or croak $!;
1423         close $fh or croak $!;
1426 sub rev_db_get {
1427         my ($self, $rev) = @_;
1428         my $ret;
1429         my $offset = $rev * 41;
1430         open my $fh, '<', $self->{db_path} or croak $!;
1431         if (seek $fh, $offset, 0) {
1432                 $ret = readline $fh;
1433                 if (defined $ret) {
1434                         chomp $ret;
1435                         $ret = undef if ($ret =~ /^0{40}$/);
1436                 }
1437         }
1438         close $fh or croak $!;
1439         $ret;
1442 sub find_rev_before {
1443         my ($self, $rev, $eq_ok) = @_;
1444         --$rev unless $eq_ok;
1445         while ($rev > 0) {
1446                 if (my $c = $self->rev_db_get($rev)) {
1447                         return ($rev, $c);
1448                 }
1449                 --$rev;
1450         }
1451         return (undef, undef);
1454 sub _new {
1455         my ($class, $repo_id, $ref_id, $path) = @_;
1456         unless (defined $repo_id && length $repo_id) {
1457                 $repo_id = $Git::SVN::default_repo_id;
1458         }
1459         unless (defined $ref_id && length $ref_id) {
1460                 $_[2] = $ref_id = $Git::SVN::default_ref_id;
1461         }
1462         $_[1] = $repo_id = sanitize_remote_name($repo_id);
1463         my $dir = "$ENV{GIT_DIR}/svn/$ref_id";
1464         $_[3] = $path = '' unless (defined $path);
1465         mkpath([$dir]);
1466         unless (-f "$dir/.rev_db") {
1467                 open my $fh, '>>', "$dir/.rev_db" or croak $!;
1468                 close $fh or croak $!;
1469         }
1470         bless { ref_id => $ref_id, dir => $dir, index => "$dir/index",
1471                 path => $path,
1472                 db_path => "$dir/.rev_db", repo_id => $repo_id }, $class;
1475 sub uri_encode {
1476         my ($f) = @_;
1477         $f =~ s#([^a-zA-Z0-9\*!\:_\./\-])#uc sprintf("%%%02x",ord($1))#eg;
1478         $f
1481 package Git::SVN::Prompt;
1482 use strict;
1483 use warnings;
1484 require SVN::Core;
1485 use vars qw/$_no_auth_cache $_username/;
1487 sub simple {
1488         my ($cred, $realm, $default_username, $may_save, $pool) = @_;
1489         $may_save = undef if $_no_auth_cache;
1490         $default_username = $_username if defined $_username;
1491         if (defined $default_username && length $default_username) {
1492                 if (defined $realm && length $realm) {
1493                         print STDERR "Authentication realm: $realm\n";
1494                         STDERR->flush;
1495                 }
1496                 $cred->username($default_username);
1497         } else {
1498                 username($cred, $realm, $may_save, $pool);
1499         }
1500         $cred->password(_read_password("Password for '" .
1501                                        $cred->username . "': ", $realm));
1502         $cred->may_save($may_save);
1503         $SVN::_Core::SVN_NO_ERROR;
1506 sub ssl_server_trust {
1507         my ($cred, $realm, $failures, $cert_info, $may_save, $pool) = @_;
1508         $may_save = undef if $_no_auth_cache;
1509         print STDERR "Error validating server certificate for '$realm':\n";
1510         if ($failures & $SVN::Auth::SSL::UNKNOWNCA) {
1511                 print STDERR " - The certificate is not issued by a trusted ",
1512                       "authority. Use the\n",
1513                       "   fingerprint to validate the certificate manually!\n";
1514         }
1515         if ($failures & $SVN::Auth::SSL::CNMISMATCH) {
1516                 print STDERR " - The certificate hostname does not match.\n";
1517         }
1518         if ($failures & $SVN::Auth::SSL::NOTYETVALID) {
1519                 print STDERR " - The certificate is not yet valid.\n";
1520         }
1521         if ($failures & $SVN::Auth::SSL::EXPIRED) {
1522                 print STDERR " - The certificate has expired.\n";
1523         }
1524         if ($failures & $SVN::Auth::SSL::OTHER) {
1525                 print STDERR " - The certificate has an unknown error.\n";
1526         }
1527         printf STDERR
1528                 "Certificate information:\n".
1529                 " - Hostname: %s\n".
1530                 " - Valid: from %s until %s\n".
1531                 " - Issuer: %s\n".
1532                 " - Fingerprint: %s\n",
1533                 map $cert_info->$_, qw(hostname valid_from valid_until
1534                                        issuer_dname fingerprint);
1535         my $choice;
1536 prompt:
1537         print STDERR $may_save ?
1538               "(R)eject, accept (t)emporarily or accept (p)ermanently? " :
1539               "(R)eject or accept (t)emporarily? ";
1540         STDERR->flush;
1541         $choice = lc(substr(<STDIN> || 'R', 0, 1));
1542         if ($choice =~ /^t$/i) {
1543                 $cred->may_save(undef);
1544         } elsif ($choice =~ /^r$/i) {
1545                 return -1;
1546         } elsif ($may_save && $choice =~ /^p$/i) {
1547                 $cred->may_save($may_save);
1548         } else {
1549                 goto prompt;
1550         }
1551         $cred->accepted_failures($failures);
1552         $SVN::_Core::SVN_NO_ERROR;
1555 sub ssl_client_cert {
1556         my ($cred, $realm, $may_save, $pool) = @_;
1557         $may_save = undef if $_no_auth_cache;
1558         print STDERR "Client certificate filename: ";
1559         STDERR->flush;
1560         chomp(my $filename = <STDIN>);
1561         $cred->cert_file($filename);
1562         $cred->may_save($may_save);
1563         $SVN::_Core::SVN_NO_ERROR;
1566 sub ssl_client_cert_pw {
1567         my ($cred, $realm, $may_save, $pool) = @_;
1568         $may_save = undef if $_no_auth_cache;
1569         $cred->password(_read_password("Password: ", $realm));
1570         $cred->may_save($may_save);
1571         $SVN::_Core::SVN_NO_ERROR;
1574 sub username {
1575         my ($cred, $realm, $may_save, $pool) = @_;
1576         $may_save = undef if $_no_auth_cache;
1577         if (defined $realm && length $realm) {
1578                 print STDERR "Authentication realm: $realm\n";
1579         }
1580         my $username;
1581         if (defined $_username) {
1582                 $username = $_username;
1583         } else {
1584                 print STDERR "Username: ";
1585                 STDERR->flush;
1586                 chomp($username = <STDIN>);
1587         }
1588         $cred->username($username);
1589         $cred->may_save($may_save);
1590         $SVN::_Core::SVN_NO_ERROR;
1593 sub _read_password {
1594         my ($prompt, $realm) = @_;
1595         print STDERR $prompt;
1596         STDERR->flush;
1597         require Term::ReadKey;
1598         Term::ReadKey::ReadMode('noecho');
1599         my $password = '';
1600         while (defined(my $key = Term::ReadKey::ReadKey(0))) {
1601                 last if $key =~ /[\012\015]/; # \n\r
1602                 $password .= $key;
1603         }
1604         Term::ReadKey::ReadMode('restore');
1605         print STDERR "\n";
1606         STDERR->flush;
1607         $password;
1610 package main;
1612 sub uri_encode {
1613         my ($f) = @_;
1614         $f =~ s#([^a-zA-Z0-9\*!\:_\./\-])#uc sprintf("%%%02x",ord($1))#eg;
1615         $f
1618 sub uri_decode {
1619         my ($f) = @_;
1620         $f =~ tr/+/ /;
1621         $f =~ s/%([A-F0-9]{2})/chr hex($1)/ge;
1622         $f
1626         my $kill_stupid_warnings = $SVN::Node::none.$SVN::Node::file.
1627                                 $SVN::Node::dir.$SVN::Node::unknown.
1628                                 $SVN::Node::none.$SVN::Node::file.
1629                                 $SVN::Node::dir.$SVN::Node::unknown.
1630                                 $SVN::Auth::SSL::CNMISMATCH.
1631                                 $SVN::Auth::SSL::NOTYETVALID.
1632                                 $SVN::Auth::SSL::EXPIRED.
1633                                 $SVN::Auth::SSL::UNKNOWNCA.
1634                                 $SVN::Auth::SSL::OTHER;
1637 package SVN::Git::Fetcher;
1638 use vars qw/@ISA/;
1639 use strict;
1640 use warnings;
1641 use Carp qw/croak/;
1642 use IO::File qw//;
1644 # file baton members: path, mode_a, mode_b, pool, fh, blob, base
1645 sub new {
1646         my ($class, $git_svn) = @_;
1647         my $self = SVN::Delta::Editor->new;
1648         bless $self, $class;
1649         $self->{c} = $git_svn->{last_commit} if exists $git_svn->{last_commit};
1650         $self->{empty} = {};
1651         $self->{dir_prop} = {};
1652         $self->{file_prop} = {};
1653         $self->{absent_dir} = {};
1654         $self->{absent_file} = {};
1655         $self->{gii} = $git_svn->tmp_index_do(sub { Git::IndexInfo->new });
1656         require Digest::MD5;
1657         $self;
1660 sub set_path_strip {
1661         my ($self, $path) = @_;
1662         $self->{path_strip} = qr/^\Q$path\E\/?/;
1665 sub open_root {
1666         { path => '' };
1669 sub open_directory {
1670         my ($self, $path, $pb, $rev) = @_;
1671         { path => $path };
1674 sub git_path {
1675         my ($self, $path) = @_;
1676         $path =~ s!$self->{path_strip}!! if $self->{path_strip};
1677         $path;
1680 sub delete_entry {
1681         my ($self, $path, $rev, $pb) = @_;
1683         my $gpath = $self->git_path($path);
1684         # remove entire directories.
1685         if (command('ls-tree', $self->{c}, '--', $gpath) =~ /^040000 tree/) {
1686                 my ($ls, $ctx) = command_output_pipe(qw/ls-tree
1687                                                      -r --name-only -z/,
1688                                                      $self->{c}, '--', $gpath);
1689                 local $/ = "\0";
1690                 while (<$ls>) {
1691                         chomp;
1692                         $self->{gii}->remove($_);
1693                         print "\tD\t$_\n" unless $self->{q};
1694                 }
1695                 print "\tD\t$gpath/\n" unless $self->{q};
1696                 command_close_pipe($ls, $ctx);
1697                 $self->{empty}->{$path} = 0
1698         } else {
1699                 $self->{gii}->remove($gpath);
1700                 print "\tD\t$gpath\n" unless $self->{q};
1701         }
1702         undef;
1705 sub open_file {
1706         my ($self, $path, $pb, $rev) = @_;
1707         my $gpath = $self->git_path($path);
1708         my ($mode, $blob) = (command('ls-tree', $self->{c}, '--', $gpath)
1709                              =~ /^(\d{6}) blob ([a-f\d]{40})\t/);
1710         unless (defined $mode && defined $blob) {
1711                 die "$path was not found in commit $self->{c} (r$rev)\n";
1712         }
1713         { path => $path, mode_a => $mode, mode_b => $mode, blob => $blob,
1714           pool => SVN::Pool->new, action => 'M' };
1717 sub add_file {
1718         my ($self, $path, $pb, $cp_path, $cp_rev) = @_;
1719         my ($dir, $file) = ($path =~ m#^(.*?)/?([^/]+)$#);
1720         delete $self->{empty}->{$dir};
1721         { path => $path, mode_a => 100644, mode_b => 100644,
1722           pool => SVN::Pool->new, action => 'A' };
1725 sub add_directory {
1726         my ($self, $path, $cp_path, $cp_rev) = @_;
1727         my ($dir, $file) = ($path =~ m#^(.*?)/?([^/]+)$#);
1728         delete $self->{empty}->{$dir};
1729         $self->{empty}->{$path} = 1;
1730         { path => $path };
1733 sub change_dir_prop {
1734         my ($self, $db, $prop, $value) = @_;
1735         $self->{dir_prop}->{$db->{path}} ||= {};
1736         $self->{dir_prop}->{$db->{path}}->{$prop} = $value;
1737         undef;
1740 sub absent_directory {
1741         my ($self, $path, $pb) = @_;
1742         $self->{absent_dir}->{$pb->{path}} ||= [];
1743         push @{$self->{absent_dir}->{$pb->{path}}}, $path;
1744         undef;
1747 sub absent_file {
1748         my ($self, $path, $pb) = @_;
1749         $self->{absent_file}->{$pb->{path}} ||= [];
1750         push @{$self->{absent_file}->{$pb->{path}}}, $path;
1751         undef;
1754 sub change_file_prop {
1755         my ($self, $fb, $prop, $value) = @_;
1756         if ($prop eq 'svn:executable') {
1757                 if ($fb->{mode_b} != 120000) {
1758                         $fb->{mode_b} = defined $value ? 100755 : 100644;
1759                 }
1760         } elsif ($prop eq 'svn:special') {
1761                 $fb->{mode_b} = defined $value ? 120000 : 100644;
1762         } else {
1763                 $self->{file_prop}->{$fb->{path}} ||= {};
1764                 $self->{file_prop}->{$fb->{path}}->{$prop} = $value;
1765         }
1766         undef;
1769 sub apply_textdelta {
1770         my ($self, $fb, $exp) = @_;
1771         my $fh = IO::File->new_tmpfile;
1772         $fh->autoflush(1);
1773         # $fh gets auto-closed() by SVN::TxDelta::apply(),
1774         # (but $base does not,) so dup() it for reading in close_file
1775         open my $dup, '<&', $fh or croak $!;
1776         my $base = IO::File->new_tmpfile;
1777         $base->autoflush(1);
1778         if ($fb->{blob}) {
1779                 defined (my $pid = fork) or croak $!;
1780                 if (!$pid) {
1781                         open STDOUT, '>&', $base or croak $!;
1782                         print STDOUT 'link ' if ($fb->{mode_a} == 120000);
1783                         exec qw/git-cat-file blob/, $fb->{blob} or croak $!;
1784                 }
1785                 waitpid $pid, 0;
1786                 croak $? if $?;
1788                 if (defined $exp) {
1789                         seek $base, 0, 0 or croak $!;
1790                         my $md5 = Digest::MD5->new;
1791                         $md5->addfile($base);
1792                         my $got = $md5->hexdigest;
1793                         die "Checksum mismatch: $fb->{path} $fb->{blob}\n",
1794                             "expected: $exp\n",
1795                             "     got: $got\n" if ($got ne $exp);
1796                 }
1797         }
1798         seek $base, 0, 0 or croak $!;
1799         $fb->{fh} = $dup;
1800         $fb->{base} = $base;
1801         [ SVN::TxDelta::apply($base, $fh, undef, $fb->{path}, $fb->{pool}) ];
1804 sub close_file {
1805         my ($self, $fb, $exp) = @_;
1806         my $hash;
1807         my $path = $self->git_path($fb->{path});
1808         if (my $fh = $fb->{fh}) {
1809                 seek($fh, 0, 0) or croak $!;
1810                 my $md5 = Digest::MD5->new;
1811                 $md5->addfile($fh);
1812                 my $got = $md5->hexdigest;
1813                 die "Checksum mismatch: $path\n",
1814                     "expected: $exp\n    got: $got\n" if ($got ne $exp);
1815                 seek($fh, 0, 0) or croak $!;
1816                 if ($fb->{mode_b} == 120000) {
1817                         read($fh, my $buf, 5) == 5 or croak $!;
1818                         $buf eq 'link ' or die "$path has mode 120000",
1819                                                "but is not a link\n";
1820                 }
1821                 defined(my $pid = open my $out,'-|') or die "Can't fork: $!\n";
1822                 if (!$pid) {
1823                         open STDIN, '<&', $fh or croak $!;
1824                         exec qw/git-hash-object -w --stdin/ or croak $!;
1825                 }
1826                 chomp($hash = do { local $/; <$out> });
1827                 close $out or croak $!;
1828                 close $fh or croak $!;
1829                 $hash =~ /^[a-f\d]{40}$/ or die "not a sha1: $hash\n";
1830                 close $fb->{base} or croak $!;
1831         } else {
1832                 $hash = $fb->{blob} or die "no blob information\n";
1833         }
1834         $fb->{pool}->clear;
1835         $self->{gii}->update($fb->{mode_b}, $hash, $path) or croak $!;
1836         print "\t$fb->{action}\t$path\n" if $fb->{action} && ! $self->{q};
1837         undef;
1840 sub abort_edit {
1841         my $self = shift;
1842         $self->{nr} = $self->{gii}->{nr};
1843         delete $self->{gii};
1844         $self->SUPER::abort_edit(@_);
1847 sub close_edit {
1848         my $self = shift;
1849         $self->{git_commit_ok} = 1;
1850         $self->{nr} = $self->{gii}->{nr};
1851         delete $self->{gii};
1852         $self->SUPER::close_edit(@_);
1855 package SVN::Git::Editor;
1856 use vars qw/@ISA/;
1857 use strict;
1858 use warnings;
1859 use Carp qw/croak/;
1860 use IO::File;
1862 sub new {
1863         my ($class, $opts) = @_;
1864         foreach (qw/svn_path r ra tree_a tree_b log editor_cb/) {
1865                 die "$_ required!\n" unless (defined $opts->{$_});
1866         }
1868         my $pool = SVN::Pool->new;
1869         my $mods = generate_diff($opts->{tree_a}, $opts->{tree_b});
1870         my $types = check_diff_paths($opts->{ra}, $opts->{svn_path},
1871                                      $opts->{r}, $mods);
1873         # $opts->{ra} functions should not be used after this:
1874         my @ce  = $opts->{ra}->get_commit_editor($opts->{log},
1875                                                 $opts->{editor_cb}, $pool);
1876         my $self = SVN::Delta::Editor->new(@ce, $pool);
1877         bless $self, $class;
1878         foreach (qw/svn_path r tree_a tree_b/) {
1879                 $self->{$_} = $opts->{$_};
1880         }
1881         $self->{url} = $opts->{ra}->{url};
1882         $self->{mods} = $mods;
1883         $self->{types} = $types;
1884         $self->{pool} = $pool;
1885         $self->{bat} = { '' => $self->open_root($self->{r}, $self->{pool}) };
1886         $self->{rm} = { };
1887         $self->{path_prefix} = length $self->{svn_path} ?
1888                                "$self->{svn_path}/" : '';
1889         require Digest::MD5;
1890         return $self;
1893 sub generate_diff {
1894         my ($tree_a, $tree_b) = @_;
1895         my @diff_tree = qw(diff-tree -z -r);
1896         if ($::_cp_similarity) {
1897                 push @diff_tree, "-C$::_cp_similarity";
1898         } else {
1899                 push @diff_tree, '-C';
1900         }
1901         push @diff_tree, '--find-copies-harder' if $::_find_copies_harder;
1902         push @diff_tree, "-l$::_l" if defined $::_l;
1903         push @diff_tree, $tree_a, $tree_b;
1904         my ($diff_fh, $ctx) = command_output_pipe(@diff_tree);
1905         local $/ = "\0";
1906         my $state = 'meta';
1907         my @mods;
1908         while (<$diff_fh>) {
1909                 chomp $_; # this gets rid of the trailing "\0"
1910                 if ($state eq 'meta' && /^:(\d{6})\s(\d{6})\s
1911                                         $::sha1\s($::sha1)\s
1912                                         ([MTCRAD])\d*$/xo) {
1913                         push @mods, {   mode_a => $1, mode_b => $2,
1914                                         sha1_b => $3, chg => $4 };
1915                         if ($4 =~ /^(?:C|R)$/) {
1916                                 $state = 'file_a';
1917                         } else {
1918                                 $state = 'file_b';
1919                         }
1920                 } elsif ($state eq 'file_a') {
1921                         my $x = $mods[$#mods] or croak "Empty array\n";
1922                         if ($x->{chg} !~ /^(?:C|R)$/) {
1923                                 croak "Error parsing $_, $x->{chg}\n";
1924                         }
1925                         $x->{file_a} = $_;
1926                         $state = 'file_b';
1927                 } elsif ($state eq 'file_b') {
1928                         my $x = $mods[$#mods] or croak "Empty array\n";
1929                         if (exists $x->{file_a} && $x->{chg} !~ /^(?:C|R)$/) {
1930                                 croak "Error parsing $_, $x->{chg}\n";
1931                         }
1932                         if (!exists $x->{file_a} && $x->{chg} =~ /^(?:C|R)$/) {
1933                                 croak "Error parsing $_, $x->{chg}\n";
1934                         }
1935                         $x->{file_b} = $_;
1936                         $state = 'meta';
1937                 } else {
1938                         croak "Error parsing $_\n";
1939                 }
1940         }
1941         command_close_pipe($diff_fh, $ctx);
1942         \@mods;
1945 sub check_diff_paths {
1946         my ($ra, $pfx, $rev, $mods) = @_;
1947         my %types;
1948         $pfx .= '/' if length $pfx;
1950         sub type_diff_paths {
1951                 my ($ra, $types, $path, $rev) = @_;
1952                 my @p = split m#/+#, $path;
1953                 my $c = shift @p;
1954                 unless (defined $types->{$c}) {
1955                         $types->{$c} = $ra->check_path($c, $rev);
1956                 }
1957                 while (@p) {
1958                         $c .= '/' . shift @p;
1959                         next if defined $types->{$c};
1960                         $types->{$c} = $ra->check_path($c, $rev);
1961                 }
1962         }
1964         foreach my $m (@$mods) {
1965                 foreach my $f (qw/file_a file_b/) {
1966                         next unless defined $m->{$f};
1967                         my ($dir) = ($m->{$f} =~ m#^(.*?)/?(?:[^/]+)$#);
1968                         if (length $pfx.$dir && ! defined $types{$dir}) {
1969                                 type_diff_paths($ra, \%types, $pfx.$dir, $rev);
1970                         }
1971                 }
1972         }
1973         \%types;
1976 sub split_path {
1977         return ($_[0] =~ m#^(.*?)/?([^/]+)$#);
1980 sub repo_path {
1981         my ($self, $path) = @_;
1982         $self->{path_prefix}.(defined $path ? $path : '');
1985 sub url_path {
1986         my ($self, $path) = @_;
1987         $self->{url} . '/' . $self->repo_path($path);
1990 sub rmdirs {
1991         my ($self) = @_;
1992         my $rm = $self->{rm};
1993         delete $rm->{''}; # we never delete the url we're tracking
1994         return unless %$rm;
1996         foreach (keys %$rm) {
1997                 my @d = split m#/#, $_;
1998                 my $c = shift @d;
1999                 $rm->{$c} = 1;
2000                 while (@d) {
2001                         $c .= '/' . shift @d;
2002                         $rm->{$c} = 1;
2003                 }
2004         }
2005         delete $rm->{$self->{svn_path}};
2006         delete $rm->{''}; # we never delete the url we're tracking
2007         return unless %$rm;
2009         my ($fh, $ctx) = command_output_pipe(qw/ls-tree --name-only -r -z/,
2010                                              $self->{tree_b});
2011         local $/ = "\0";
2012         while (<$fh>) {
2013                 chomp;
2014                 my @dn = split m#/#, $_;
2015                 while (pop @dn) {
2016                         delete $rm->{join '/', @dn};
2017                 }
2018                 unless (%$rm) {
2019                         close $fh;
2020                         return;
2021                 }
2022         }
2023         command_close_pipe($fh, $ctx);
2025         my ($r, $p, $bat) = ($self->{r}, $self->{pool}, $self->{bat});
2026         foreach my $d (sort { $b =~ tr#/#/# <=> $a =~ tr#/#/# } keys %$rm) {
2027                 $self->close_directory($bat->{$d}, $p);
2028                 my ($dn) = ($d =~ m#^(.*?)/?(?:[^/]+)$#);
2029                 print "\tD+\t$d/\n" unless $::_q;
2030                 $self->SUPER::delete_entry($d, $r, $bat->{$dn}, $p);
2031                 delete $bat->{$d};
2032         }
2035 sub open_or_add_dir {
2036         my ($self, $full_path, $baton) = @_;
2037         my $t = $self->{types}->{$full_path};
2038         if (!defined $t) {
2039                 die "$full_path not known in r$self->{r} or we have a bug!\n";
2040         }
2041         if ($t == $SVN::Node::none) {
2042                 return $self->add_directory($full_path, $baton,
2043                                                 undef, -1, $self->{pool});
2044         } elsif ($t == $SVN::Node::dir) {
2045                 return $self->open_directory($full_path, $baton,
2046                                                 $self->{r}, $self->{pool});
2047         }
2048         print STDERR "$full_path already exists in repository at ",
2049                 "r$self->{r} and it is not a directory (",
2050                 ($t == $SVN::Node::file ? 'file' : 'unknown'),"/$t)\n";
2051         exit 1;
2054 sub ensure_path {
2055         my ($self, $path) = @_;
2056         my $bat = $self->{bat};
2057         my $repo_path = $self->repo_path($path);
2058         return $bat->{''} unless (length $repo_path);
2059         my @p = split m#/+#, $repo_path;
2060         my $c = shift @p;
2061         $bat->{$c} ||= $self->open_or_add_dir($c, $bat->{''});
2062         while (@p) {
2063                 my $c0 = $c;
2064                 $c .= '/' . shift @p;
2065                 $bat->{$c} ||= $self->open_or_add_dir($c, $bat->{$c0});
2066         }
2067         return $bat->{$c};
2070 sub A {
2071         my ($self, $m) = @_;
2072         my ($dir, $file) = split_path($m->{file_b});
2073         my $pbat = $self->ensure_path($dir);
2074         my $fbat = $self->add_file($self->repo_path($m->{file_b}), $pbat,
2075                                         undef, -1);
2076         print "\tA\t$m->{file_b}\n" unless $::_q;
2077         $self->chg_file($fbat, $m);
2078         $self->close_file($fbat,undef,$self->{pool});
2081 sub C {
2082         my ($self, $m) = @_;
2083         my ($dir, $file) = split_path($m->{file_b});
2084         my $pbat = $self->ensure_path($dir);
2085         my $fbat = $self->add_file($self->repo_path($m->{file_b}), $pbat,
2086                                 $self->url_path($m->{file_a}), $self->{r});
2087         print "\tC\t$m->{file_a} => $m->{file_b}\n" unless $::_q;
2088         $self->chg_file($fbat, $m);
2089         $self->close_file($fbat,undef,$self->{pool});
2092 sub delete_entry {
2093         my ($self, $path, $pbat) = @_;
2094         my $rpath = $self->repo_path($path);
2095         my ($dir, $file) = split_path($rpath);
2096         $self->{rm}->{$dir} = 1;
2097         $self->SUPER::delete_entry($rpath, $self->{r}, $pbat, $self->{pool});
2100 sub R {
2101         my ($self, $m) = @_;
2102         my ($dir, $file) = split_path($m->{file_b});
2103         my $pbat = $self->ensure_path($dir);
2104         my $fbat = $self->add_file($self->repo_path($m->{file_b}), $pbat,
2105                                 $self->url_path($m->{file_a}), $self->{r});
2106         print "\tR\t$m->{file_a} => $m->{file_b}\n" unless $::_q;
2107         $self->chg_file($fbat, $m);
2108         $self->close_file($fbat,undef,$self->{pool});
2110         ($dir, $file) = split_path($m->{file_a});
2111         $pbat = $self->ensure_path($dir);
2112         $self->delete_entry($m->{file_a}, $pbat);
2115 sub M {
2116         my ($self, $m) = @_;
2117         my ($dir, $file) = split_path($m->{file_b});
2118         my $pbat = $self->ensure_path($dir);
2119         my $fbat = $self->open_file($self->repo_path($m->{file_b}),
2120                                 $pbat,$self->{r},$self->{pool});
2121         print "\t$m->{chg}\t$m->{file_b}\n" unless $::_q;
2122         $self->chg_file($fbat, $m);
2123         $self->close_file($fbat,undef,$self->{pool});
2126 sub T { shift->M(@_) }
2128 sub change_file_prop {
2129         my ($self, $fbat, $pname, $pval) = @_;
2130         $self->SUPER::change_file_prop($fbat, $pname, $pval, $self->{pool});
2133 sub chg_file {
2134         my ($self, $fbat, $m) = @_;
2135         if ($m->{mode_b} =~ /755$/ && $m->{mode_a} !~ /755$/) {
2136                 $self->change_file_prop($fbat,'svn:executable','*');
2137         } elsif ($m->{mode_b} !~ /755$/ && $m->{mode_a} =~ /755$/) {
2138                 $self->change_file_prop($fbat,'svn:executable',undef);
2139         }
2140         my $fh = IO::File->new_tmpfile or croak $!;
2141         if ($m->{mode_b} =~ /^120/) {
2142                 print $fh 'link ' or croak $!;
2143                 $self->change_file_prop($fbat,'svn:special','*');
2144         } elsif ($m->{mode_a} =~ /^120/ && $m->{mode_b} !~ /^120/) {
2145                 $self->change_file_prop($fbat,'svn:special',undef);
2146         }
2147         defined(my $pid = fork) or croak $!;
2148         if (!$pid) {
2149                 open STDOUT, '>&', $fh or croak $!;
2150                 exec qw/git-cat-file blob/, $m->{sha1_b} or croak $!;
2151         }
2152         waitpid $pid, 0;
2153         croak $? if $?;
2154         $fh->flush == 0 or croak $!;
2155         seek $fh, 0, 0 or croak $!;
2157         my $md5 = Digest::MD5->new;
2158         $md5->addfile($fh) or croak $!;
2159         seek $fh, 0, 0 or croak $!;
2161         my $exp = $md5->hexdigest;
2162         my $pool = SVN::Pool->new;
2163         my $atd = $self->apply_textdelta($fbat, undef, $pool);
2164         my $got = SVN::TxDelta::send_stream($fh, @$atd, $pool);
2165         die "Checksum mismatch\nexpected: $exp\ngot: $got\n" if ($got ne $exp);
2166         $pool->clear;
2168         close $fh or croak $!;
2171 sub D {
2172         my ($self, $m) = @_;
2173         my ($dir, $file) = split_path($m->{file_b});
2174         my $pbat = $self->ensure_path($dir);
2175         print "\tD\t$m->{file_b}\n" unless $::_q;
2176         $self->delete_entry($m->{file_b}, $pbat);
2179 sub close_edit {
2180         my ($self) = @_;
2181         my ($p,$bat) = ($self->{pool}, $self->{bat});
2182         foreach (sort { $b =~ tr#/#/# <=> $a =~ tr#/#/# } keys %$bat) {
2183                 $self->close_directory($bat->{$_}, $p);
2184         }
2185         $self->SUPER::close_edit($p);
2186         $p->clear;
2189 sub abort_edit {
2190         my ($self) = @_;
2191         $self->SUPER::abort_edit($self->{pool});
2194 sub DESTROY {
2195         my $self = shift;
2196         $self->SUPER::DESTROY(@_);
2197         $self->{pool}->clear;
2200 # this drives the editor
2201 sub apply_diff {
2202         my ($self) = @_;
2203         my $mods = $self->{mods};
2204         my %o = ( D => 1, R => 0, C => -1, A => 3, M => 3, T => 3 );
2205         foreach my $m (sort { $o{$a->{chg}} <=> $o{$b->{chg}} } @$mods) {
2206                 my $f = $m->{chg};
2207                 if (defined $o{$f}) {
2208                         $self->$f($m);
2209                 } else {
2210                         fatal("Invalid change type: $f\n");
2211                 }
2212         }
2213         $self->rmdirs if $::_rmdir;
2214         if (@$mods == 0) {
2215                 $self->abort_edit;
2216         } else {
2217                 $self->close_edit;
2218         }
2219         return scalar @$mods;
2222 package Git::SVN::Ra;
2223 use vars qw/@ISA $config_dir/;
2224 use strict;
2225 use warnings;
2226 my ($can_do_switch);
2227 my %RA;
2229 BEGIN {
2230         # enforce temporary pool usage for some simple functions
2231         my $e;
2232         foreach (qw/get_latest_revnum rev_proplist get_file
2233                     check_path get_dir get_uuid get_repos_root/) {
2234                 $e .= "sub $_ {
2235                         my \$self = shift;
2236                         my \$pool = SVN::Pool->new;
2237                         my \@ret = \$self->SUPER::$_(\@_,\$pool);
2238                         \$pool->clear;
2239                         wantarray ? \@ret : \$ret[0]; }\n";
2240         }
2241         eval $e;
2244 sub new {
2245         my ($class, $url) = @_;
2246         $url =~ s!/+$!!;
2247         return $RA{$url} if $RA{$url};
2249         SVN::_Core::svn_config_ensure($config_dir, undef);
2250         my ($baton, $callbacks) = SVN::Core::auth_open_helper([
2251             SVN::Client::get_simple_provider(),
2252             SVN::Client::get_ssl_server_trust_file_provider(),
2253             SVN::Client::get_simple_prompt_provider(
2254               \&Git::SVN::Prompt::simple, 2),
2255             SVN::Client::get_ssl_client_cert_prompt_provider(
2256               \&Git::SVN::Prompt::ssl_client_cert, 2),
2257             SVN::Client::get_ssl_client_cert_pw_prompt_provider(
2258               \&Git::SVN::Prompt::ssl_client_cert_pw, 2),
2259             SVN::Client::get_username_provider(),
2260             SVN::Client::get_ssl_server_trust_prompt_provider(
2261               \&Git::SVN::Prompt::ssl_server_trust),
2262             SVN::Client::get_username_prompt_provider(
2263               \&Git::SVN::Prompt::username, 2),
2264           ]);
2265         my $config = SVN::Core::config_get_config($config_dir);
2266         my $self = SVN::Ra->new(url => $url, auth => $baton,
2267                               config => $config,
2268                               pool => SVN::Pool->new,
2269                               auth_provider_callbacks => $callbacks);
2270         $self->{svn_path} = $url;
2271         $self->{repos_root} = $self->get_repos_root;
2272         $self->{svn_path} =~ s#^\Q$self->{repos_root}\E/*##;
2273         $RA{$url} = bless $self, $class;
2276 sub DESTROY {
2277         # do not call the real DESTROY since we store ourselves in %RA
2280 sub get_log {
2281         my ($self, @args) = @_;
2282         my $pool = SVN::Pool->new;
2283         splice(@args, 3, 1) if ($SVN::Core::VERSION le '1.2.0');
2284         my $ret = $self->SUPER::get_log(@args, $pool);
2285         $pool->clear;
2286         $ret;
2289 sub get_commit_editor {
2290         my ($self, $log, $cb, $pool) = @_;
2291         my @lock = $SVN::Core::VERSION ge '1.2.0' ? (undef, 0) : ();
2292         $self->SUPER::get_commit_editor($log, $cb, @lock, $pool);
2295 sub uuid {
2296         my ($self) = @_;
2297         $self->{uuid} ||= $self->get_uuid;
2300 sub gs_do_update {
2301         my ($self, $rev_a, $rev_b, $path, $recurse, $editor) = @_;
2302         my $pool = SVN::Pool->new;
2303         $editor->set_path_strip($path);
2304         my $reporter = $self->do_update($rev_b, $path, $recurse,
2305                                         $editor, $pool);
2306         my @lock = $SVN::Core::VERSION ge '1.2.0' ? (undef) : ();
2307         my $new = ($rev_a == $rev_b);
2308         $reporter->set_path('', $rev_a, $new, @lock, $pool);
2309         $reporter->finish_report($pool);
2310         $pool->clear;
2311         $editor->{git_commit_ok};
2314 sub gs_do_switch {
2315         my ($self, $rev_a, $rev_b, $path, $recurse, $url_b, $editor) = @_;
2316         my $pool = SVN::Pool->new;
2317         $editor->set_path_strip($path);
2318         my $reporter = $self->do_switch($rev_b, $path, $recurse,
2319                                         $url_b, $editor, $pool);
2320         my @lock = $SVN::Core::VERSION ge '1.2.0' ? (undef) : ();
2321         $reporter->set_path('', $rev_a, 0, @lock, $pool);
2322         $reporter->finish_report($pool);
2323         $pool->clear;
2324         $editor->{git_commit_ok};
2327 sub minimize_url {
2328         my ($self) = @_;
2329         return $self->{url} if ($self->{url} eq $self->{repos_root});
2330         my $url = $self->{repos_root};
2331         my @components = split(m!/!, $self->{svn_path});
2332         my $c = '';
2333         do {
2334                 $url .= "/$c" if length $c;
2335                 eval { (ref $self)->new($url)->get_latest_revnum };
2336         } while ($@ && ($c = shift @components));
2337         $url;
2340 sub can_do_switch {
2341         my $self = shift;
2342         unless (defined $can_do_switch) {
2343                 my $pool = SVN::Pool->new;
2344                 my $rep = eval {
2345                         $self->do_switch(1, '', 0, $self->{url},
2346                                          SVN::Delta::Editor->new, $pool);
2347                 };
2348                 if ($@) {
2349                         $can_do_switch = 0;
2350                 } else {
2351                         $rep->abort_report($pool);
2352                         $can_do_switch = 1;
2353                 }
2354                 $pool->clear;
2355         }
2356         $can_do_switch;
2359 package Git::SVN::Log;
2360 use strict;
2361 use warnings;
2362 use POSIX qw/strftime/;
2363 use vars qw/$TZ $limit $color $pager $non_recursive $verbose $oneline
2364             %rusers $show_commit $incremental/;
2365 my $l_fmt;
2367 sub cmt_showable {
2368         my ($c) = @_;
2369         return 1 if defined $c->{r};
2370         if ($c->{l} && $c->{l}->[-1] eq "...\n" &&
2371                                 $c->{a_raw} =~ /\@([a-f\d\-]+)>$/) {
2372                 my @log = command(qw/cat-file commit/, $c->{c});
2373                 shift @log while ($log[0] ne "\n");
2374                 shift @log;
2375                 @{$c->{l}} = grep !/^git-svn-id: /, @log;
2377                 (undef, $c->{r}, undef) = ::extract_metadata(
2378                                 (grep(/^git-svn-id: /, @log))[-1]);
2379         }
2380         return defined $c->{r};
2383 sub log_use_color {
2384         return 1 if $color;
2385         my ($dc, $dcvar);
2386         $dcvar = 'color.diff';
2387         $dc = `git-config --get $dcvar`;
2388         if ($dc eq '') {
2389                 # nothing at all; fallback to "diff.color"
2390                 $dcvar = 'diff.color';
2391                 $dc = `git-config --get $dcvar`;
2392         }
2393         chomp($dc);
2394         if ($dc eq 'auto') {
2395                 my $pc;
2396                 $pc = `git-config --get color.pager`;
2397                 if ($pc eq '') {
2398                         # does not have it -- fallback to pager.color
2399                         $pc = `git-config --bool --get pager.color`;
2400                 }
2401                 else {
2402                         $pc = `git-config --bool --get color.pager`;
2403                         if ($?) {
2404                                 $pc = 'false';
2405                         }
2406                 }
2407                 chomp($pc);
2408                 if (-t *STDOUT || (defined $pager && $pc eq 'true')) {
2409                         return ($ENV{TERM} && $ENV{TERM} ne 'dumb');
2410                 }
2411                 return 0;
2412         }
2413         return 0 if $dc eq 'never';
2414         return 1 if $dc eq 'always';
2415         chomp($dc = `git-config --bool --get $dcvar`);
2416         return ($dc eq 'true');
2419 sub git_svn_log_cmd {
2420         my ($r_min, $r_max) = @_;
2421         my $gs = Git::SVN->_new;
2422         my @cmd = (qw/log --abbrev-commit --pretty=raw --default/,
2423                    $gs->refname);
2424         push @cmd, '-r' unless $non_recursive;
2425         push @cmd, qw/--raw --name-status/ if $verbose;
2426         push @cmd, '--color' if log_use_color();
2427         return @cmd unless defined $r_max;
2428         if ($r_max == $r_min) {
2429                 push @cmd, '--max-count=1';
2430                 if (my $c = $gs->rev_db_get($r_max)) {
2431                         push @cmd, $c;
2432                 }
2433         } else {
2434                 my ($c_min, $c_max);
2435                 $c_max = $gs->rev_db_get($r_max);
2436                 $c_min = $gs->rev_db_get($r_min);
2437                 if (defined $c_min && defined $c_max) {
2438                         if ($r_max > $r_max) {
2439                                 push @cmd, "$c_min..$c_max";
2440                         } else {
2441                                 push @cmd, "$c_max..$c_min";
2442                         }
2443                 } elsif ($r_max > $r_min) {
2444                         push @cmd, $c_max;
2445                 } else {
2446                         push @cmd, $c_min;
2447                 }
2448         }
2449         return @cmd;
2452 # adapted from pager.c
2453 sub config_pager {
2454         $pager ||= $ENV{GIT_PAGER} || $ENV{PAGER};
2455         if (!defined $pager) {
2456                 $pager = 'less';
2457         } elsif (length $pager == 0 || $pager eq 'cat') {
2458                 $pager = undef;
2459         }
2462 sub run_pager {
2463         return unless -t *STDOUT;
2464         pipe my $rfd, my $wfd or return;
2465         defined(my $pid = fork) or ::fatal "Can't fork: $!\n";
2466         if (!$pid) {
2467                 open STDOUT, '>&', $wfd or
2468                                      ::fatal "Can't redirect to stdout: $!\n";
2469                 return;
2470         }
2471         open STDIN, '<&', $rfd or ::fatal "Can't redirect stdin: $!\n";
2472         $ENV{LESS} ||= 'FRSX';
2473         exec $pager or ::fatal "Can't run pager: $! ($pager)\n";
2476 sub tz_to_s_offset {
2477         my ($tz) = @_;
2478         $tz =~ s/(\d\d)$//;
2479         return ($1 * 60) + ($tz * 3600);
2482 sub get_author_info {
2483         my ($dest, $author, $t, $tz) = @_;
2484         $author =~ s/(?:^\s*|\s*$)//g;
2485         $dest->{a_raw} = $author;
2486         my $au;
2487         if ($::_authors) {
2488                 $au = $rusers{$author} || undef;
2489         }
2490         if (!$au) {
2491                 ($au) = ($author =~ /<([^>]+)\@[^>]+>$/);
2492         }
2493         $dest->{t} = $t;
2494         $dest->{tz} = $tz;
2495         $dest->{a} = $au;
2496         # Date::Parse isn't in the standard Perl distro :(
2497         if ($tz =~ s/^\+//) {
2498                 $t += tz_to_s_offset($tz);
2499         } elsif ($tz =~ s/^\-//) {
2500                 $t -= tz_to_s_offset($tz);
2501         }
2502         $dest->{t_utc} = $t;
2505 sub process_commit {
2506         my ($c, $r_min, $r_max, $defer) = @_;
2507         if (defined $r_min && defined $r_max) {
2508                 if ($r_min == $c->{r} && $r_min == $r_max) {
2509                         show_commit($c);
2510                         return 0;
2511                 }
2512                 return 1 if $r_min == $r_max;
2513                 if ($r_min < $r_max) {
2514                         # we need to reverse the print order
2515                         return 0 if (defined $limit && --$limit < 0);
2516                         push @$defer, $c;
2517                         return 1;
2518                 }
2519                 if ($r_min != $r_max) {
2520                         return 1 if ($r_min < $c->{r});
2521                         return 1 if ($r_max > $c->{r});
2522                 }
2523         }
2524         return 0 if (defined $limit && --$limit < 0);
2525         show_commit($c);
2526         return 1;
2529 sub show_commit {
2530         my $c = shift;
2531         if ($oneline) {
2532                 my $x = "\n";
2533                 if (my $l = $c->{l}) {
2534                         while ($l->[0] =~ /^\s*$/) { shift @$l }
2535                         $x = $l->[0];
2536                 }
2537                 $l_fmt ||= 'A' . length($c->{r});
2538                 print 'r',pack($l_fmt, $c->{r}),' | ';
2539                 print "$c->{c} | " if $show_commit;
2540                 print $x;
2541         } else {
2542                 show_commit_normal($c);
2543         }
2546 sub show_commit_changed_paths {
2547         my ($c) = @_;
2548         return unless $c->{changed};
2549         print "Changed paths:\n", @{$c->{changed}};
2552 sub show_commit_normal {
2553         my ($c) = @_;
2554         print '-' x72, "\nr$c->{r} | ";
2555         print "$c->{c} | " if $show_commit;
2556         print "$c->{a} | ", strftime("%Y-%m-%d %H:%M:%S %z (%a, %d %b %Y)",
2557                                  localtime($c->{t_utc})), ' | ';
2558         my $nr_line = 0;
2560         if (my $l = $c->{l}) {
2561                 while ($l->[$#$l] eq "\n" && $#$l > 0
2562                                           && $l->[($#$l - 1)] eq "\n") {
2563                         pop @$l;
2564                 }
2565                 $nr_line = scalar @$l;
2566                 if (!$nr_line) {
2567                         print "1 line\n\n\n";
2568                 } else {
2569                         if ($nr_line == 1) {
2570                                 $nr_line = '1 line';
2571                         } else {
2572                                 $nr_line .= ' lines';
2573                         }
2574                         print $nr_line, "\n";
2575                         show_commit_changed_paths($c);
2576                         print "\n";
2577                         print $_ foreach @$l;
2578                 }
2579         } else {
2580                 print "1 line\n";
2581                 show_commit_changed_paths($c);
2582                 print "\n";
2584         }
2585         foreach my $x (qw/raw diff/) {
2586                 if ($c->{$x}) {
2587                         print "\n";
2588                         print $_ foreach @{$c->{$x}}
2589                 }
2590         }
2593 sub cmd_show_log {
2594         my (@args) = @_;
2595         my ($r_min, $r_max);
2596         my $r_last = -1; # prevent dupes
2597         if (defined $TZ) {
2598                 $ENV{TZ} = $TZ;
2599         } else {
2600                 delete $ENV{TZ};
2601         }
2602         if (defined $::_revision) {
2603                 if ($::_revision =~ /^(\d+):(\d+)$/) {
2604                         ($r_min, $r_max) = ($1, $2);
2605                 } elsif ($::_revision =~ /^\d+$/) {
2606                         $r_min = $r_max = $::_revision;
2607                 } else {
2608                         ::fatal "-r$::_revision is not supported, use ",
2609                                 "standard \'git log\' arguments instead\n";
2610                 }
2611         }
2613         config_pager();
2614         @args = (git_svn_log_cmd($r_min, $r_max), @args);
2615         my $log = command_output_pipe(@args);
2616         run_pager();
2617         my (@k, $c, $d);
2618         my $esc_color = qr/(?:\033\[(?:(?:\d+;)*\d*)?m)*/;
2619         while (<$log>) {
2620                 if (/^${esc_color}commit ($::sha1_short)/o) {
2621                         my $cmt = $1;
2622                         if ($c && cmt_showable($c) && $c->{r} != $r_last) {
2623                                 $r_last = $c->{r};
2624                                 process_commit($c, $r_min, $r_max, \@k) or
2625                                                                 goto out;
2626                         }
2627                         $d = undef;
2628                         $c = { c => $cmt };
2629                 } elsif (/^${esc_color}author (.+) (\d+) ([\-\+]?\d+)$/o) {
2630                         get_author_info($c, $1, $2, $3);
2631                 } elsif (/^${esc_color}(?:tree|parent|committer) /o) {
2632                         # ignore
2633                 } elsif (/^${esc_color}:\d{6} \d{6} $::sha1_short/o) {
2634                         push @{$c->{raw}}, $_;
2635                 } elsif (/^${esc_color}[ACRMDT]\t/) {
2636                         # we could add $SVN->{svn_path} here, but that requires
2637                         # remote access at the moment (repo_path_split)...
2638                         s#^(${esc_color})([ACRMDT])\t#$1   $2 #o;
2639                         push @{$c->{changed}}, $_;
2640                 } elsif (/^${esc_color}diff /o) {
2641                         $d = 1;
2642                         push @{$c->{diff}}, $_;
2643                 } elsif ($d) {
2644                         push @{$c->{diff}}, $_;
2645                 } elsif (/^${esc_color}    (git-svn-id:.+)$/o) {
2646                         ($c->{url}, $c->{r}, undef) = ::extract_metadata($1);
2647                 } elsif (s/^${esc_color}    //o) {
2648                         push @{$c->{l}}, $_;
2649                 }
2650         }
2651         if ($c && defined $c->{r} && $c->{r} != $r_last) {
2652                 $r_last = $c->{r};
2653                 process_commit($c, $r_min, $r_max, \@k);
2654         }
2655         if (@k) {
2656                 my $swap = $r_max;
2657                 $r_max = $r_min;
2658                 $r_min = $swap;
2659                 process_commit($_, $r_min, $r_max) foreach reverse @k;
2660         }
2661 out:
2662         close $log;
2663         print '-' x72,"\n" unless $incremental || $oneline;
2666 package Git::SVN::Migration;
2667 # these version numbers do NOT correspond to actual version numbers
2668 # of git nor git-svn.  They are just relative.
2670 # v0 layout: .git/$id/info/url, refs/heads/$id-HEAD
2672 # v1 layout: .git/$id/info/url, refs/remotes/$id
2674 # v2 layout: .git/svn/$id/info/url, refs/remotes/$id
2676 # v3 layout: .git/svn/$id, refs/remotes/$id
2677 #            - info/url may remain for backwards compatibility
2678 #            - this is what we migrate up to this layout automatically,
2679 #            - this will be used by git svn init on single branches
2681 # v4 layout: .git/svn/$repo_id/$id, refs/remotes/$repo_id/$id
2682 #            - this is only created for newly multi-init-ed
2683 #              repositories.  Similar in spirit to the
2684 #              --use-separate-remotes option in git-clone (now default)
2685 #            - we do not automatically migrate to this (following
2686 #              the example set by core git)
2687 use strict;
2688 use warnings;
2689 use Carp qw/croak/;
2690 use File::Path qw/mkpath/;
2691 use File::Basename qw/dirname basename/;
2692 use vars qw/$_minimize/;
2694 sub migrate_from_v0 {
2695         my $git_dir = $ENV{GIT_DIR};
2696         return undef unless -d $git_dir;
2697         my ($fh, $ctx) = command_output_pipe(qw/rev-parse --symbolic --all/);
2698         my $migrated = 0;
2699         while (<$fh>) {
2700                 chomp;
2701                 my ($id, $orig_ref) = ($_, $_);
2702                 next unless $id =~ s#^refs/heads/(.+)-HEAD$#$1#;
2703                 next unless -f "$git_dir/$id/info/url";
2704                 my $new_ref = "refs/remotes/$id";
2705                 if (::verify_ref("$new_ref^0")) {
2706                         print STDERR "W: $orig_ref is probably an old ",
2707                                      "branch used by an ancient version of ",
2708                                      "git-svn.\n",
2709                                      "However, $new_ref also exists.\n",
2710                                      "We will not be able ",
2711                                      "to use this branch until this ",
2712                                      "ambiguity is resolved.\n";
2713                         next;
2714                 }
2715                 print STDERR "Migrating from v0 layout...\n" if !$migrated;
2716                 print STDERR "Renaming ref: $orig_ref => $new_ref\n";
2717                 command_noisy('update-ref', $new_ref, $orig_ref);
2718                 command_noisy('update-ref', '-d', $orig_ref, $orig_ref);
2719                 $migrated++;
2720         }
2721         command_close_pipe($fh, $ctx);
2722         print STDERR "Done migrating from v0 layout...\n" if $migrated;
2723         $migrated;
2726 sub migrate_from_v1 {
2727         my $git_dir = $ENV{GIT_DIR};
2728         my $migrated = 0;
2729         return $migrated unless -d $git_dir;
2730         my $svn_dir = "$git_dir/svn";
2732         # just in case somebody used 'svn' as their $id at some point...
2733         return $migrated if -d $svn_dir && ! -f "$svn_dir/info/url";
2735         print STDERR "Migrating from a git-svn v1 layout...\n";
2736         mkpath([$svn_dir]);
2737         print STDERR "Data from a previous version of git-svn exists, but\n\t",
2738                      "$svn_dir\n\t(required for this version ",
2739                      "($::VERSION) of git-svn) does not. exist\n";
2740         my ($fh, $ctx) = command_output_pipe(qw/rev-parse --symbolic --all/);
2741         while (<$fh>) {
2742                 my $x = $_;
2743                 next unless $x =~ s#^refs/remotes/##;
2744                 chomp $x;
2745                 next unless -f "$git_dir/$x/info/url";
2746                 my $u = eval { ::file_to_s("$git_dir/$x/info/url") };
2747                 next unless $u;
2748                 my $dn = dirname("$git_dir/svn/$x");
2749                 mkpath([$dn]) unless -d $dn;
2750                 if ($x eq 'svn') { # they used 'svn' as GIT_SVN_ID:
2751                         mkpath(["$git_dir/svn/svn"]);
2752                         print STDERR " - $git_dir/$x/info => ",
2753                                         "$git_dir/svn/$x/info\n";
2754                         rename "$git_dir/$x/info", "$git_dir/svn/$x/info" or
2755                                croak "$!: $x";
2756                         # don't worry too much about these, they probably
2757                         # don't exist with repos this old (save for index,
2758                         # and we can easily regenerate that)
2759                         foreach my $f (qw/unhandled.log index .rev_db/) {
2760                                 rename "$git_dir/$x/$f", "$git_dir/svn/$x/$f";
2761                         }
2762                 } else {
2763                         print STDERR " - $git_dir/$x => $git_dir/svn/$x\n";
2764                         rename "$git_dir/$x", "$git_dir/svn/$x" or
2765                                croak "$!: $x";
2766                 }
2767                 $migrated++;
2768         }
2769         command_close_pipe($fh, $ctx);
2770         print STDERR "Done migrating from a git-svn v1 layout\n";
2771         $migrated;
2774 sub read_old_urls {
2775         my ($l_map, $pfx, $path) = @_;
2776         my @dir;
2777         foreach (<$path/*>) {
2778                 if (-r "$_/info/url") {
2779                         $pfx .= '/' if $pfx && $pfx !~ m!/$!;
2780                         my $ref_id = $pfx . basename $_;
2781                         my $url = ::file_to_s("$_/info/url");
2782                         $l_map->{$ref_id} = $url;
2783                 } elsif (-d $_) {
2784                         push @dir, $_;
2785                 }
2786         }
2787         foreach (@dir) {
2788                 my $x = $_;
2789                 $x =~ s!^\Q$ENV{GIT_DIR}\E/svn/!!o;
2790                 read_old_urls($l_map, $x, $_);
2791         }
2794 sub migrate_from_v2 {
2795         my @cfg = command(qw/config -l/);
2796         return if grep /^svn-remote\..+\.url=/, @cfg;
2797         my %l_map;
2798         read_old_urls(\%l_map, '', "$ENV{GIT_DIR}/svn");
2799         my $migrated = 0;
2801         foreach my $ref_id (sort keys %l_map) {
2802                 Git::SVN->init($l_map{$ref_id}, '', $ref_id, $ref_id);
2803                 $migrated++;
2804         }
2805         $migrated;
2808 sub minimize_connections {
2809         my $r = Git::SVN::read_all_remotes();
2810         my $new_urls = {};
2811         my $root_repos = {};
2812         foreach my $repo_id (keys %$r) {
2813                 my $url = $r->{$repo_id}->{url} or next;
2814                 my $fetch = $r->{$repo_id}->{fetch} or next;
2815                 my $ra = Git::SVN::Ra->new($url);
2817                 # skip existing cases where we already connect to the root
2818                 if (($ra->{url} eq $ra->{repos_root}) ||
2819                     (Git::SVN::sanitize_remote_name($ra->{repos_root}) eq
2820                      $repo_id)) {
2821                         $root_repos->{$ra->{url}} = $repo_id;
2822                         next;
2823                 }
2825                 my $root_ra = Git::SVN::Ra->new($ra->{repos_root});
2826                 my $root_path = $ra->{url};
2827                 $root_path =~ s#^\Q$ra->{repos_root}\E/*##;
2828                 foreach my $path (keys %$fetch) {
2829                         my $ref_id = $fetch->{$path};
2830                         my $gs = Git::SVN->new($ref_id, $repo_id, $path);
2832                         # make sure we can read when connecting to
2833                         # a higher level of a repository
2834                         my ($last_rev, undef) = $gs->last_rev_commit;
2835                         if (!defined $last_rev) {
2836                                 $last_rev = eval {
2837                                         $root_ra->get_latest_revnum;
2838                                 };
2839                                 next if $@;
2840                         }
2841                         my $new = $root_path;
2842                         $new .= length $path ? "/$path" : '';
2843                         eval {
2844                                 $root_ra->get_log([$new], $last_rev, $last_rev,
2845                                                   0, 0, 1, sub { });
2846                         };
2847                         next if $@;
2848                         $new_urls->{$ra->{repos_root}}->{$new} =
2849                                 { ref_id => $ref_id,
2850                                   old_repo_id => $repo_id,
2851                                   old_path => $path };
2852                 }
2853         }
2855         my @emptied;
2856         foreach my $url (keys %$new_urls) {
2857                 # see if we can re-use an existing [svn-remote "repo_id"]
2858                 # instead of creating a(n ugly) new section:
2859                 my $repo_id = $root_repos->{$url} ||
2860                               Git::SVN::sanitize_remote_name($url);
2862                 my $fetch = $new_urls->{$url};
2863                 foreach my $path (keys %$fetch) {
2864                         my $x = $fetch->{$path};
2865                         Git::SVN->init($url, $path, $repo_id, $x->{ref_id});
2866                         my $pfx = "svn-remote.$x->{old_repo_id}";
2868                         my $old_fetch = quotemeta("$x->{old_path}:".
2869                                                   "refs/remotes/$x->{ref_id}");
2870                         command_noisy(qw/config --unset/,
2871                                       "$pfx.fetch", '^'. $old_fetch . '$');
2872                         delete $r->{$x->{old_repo_id}}->
2873                                {fetch}->{$x->{old_path}};
2874                         if (!keys %{$r->{$x->{old_repo_id}}->{fetch}}) {
2875                                 command_noisy(qw/config --unset/,
2876                                               "$pfx.url");
2877                                 push @emptied, $x->{old_repo_id}
2878                         }
2879                 }
2880         }
2881         if (@emptied) {
2882                 my $file = $ENV{GIT_CONFIG} || $ENV{GIT_CONFIG_LOCAL} ||
2883                            "$ENV{GIT_DIR}/config";
2884                 print STDERR <<EOF;
2885 The following [svn-remote] sections in your config file ($file) are empty
2886 and can be safely removed:
2887 EOF
2888                 print STDERR "[svn-remote \"$_\"]\n" foreach @emptied;
2889         }
2892 sub migration_check {
2893         migrate_from_v0();
2894         migrate_from_v1();
2895         migrate_from_v2();
2896         minimize_connections() if $_minimize;
2899 package Git::IndexInfo;
2900 use strict;
2901 use warnings;
2902 use Git qw/command_input_pipe command_close_pipe/;
2904 sub new {
2905         my ($class) = @_;
2906         my ($gui, $ctx) = command_input_pipe(qw/update-index -z --index-info/);
2907         bless { gui => $gui, ctx => $ctx, nr => 0}, $class;
2910 sub remove {
2911         my ($self, $path) = @_;
2912         if (print { $self->{gui} } '0 ', 0 x 40, "\t", $path, "\0") {
2913                 return ++$self->{nr};
2914         }
2915         undef;
2918 sub update {
2919         my ($self, $mode, $hash, $path) = @_;
2920         if (print { $self->{gui} } $mode, ' ', $hash, "\t", $path, "\0") {
2921                 return ++$self->{nr};
2922         }
2923         undef;
2926 sub DESTROY {
2927         my ($self) = @_;
2928         command_close_pipe($self->{gui}, $self->{ctx});
2931 __END__
2933 Data structures:
2935 $log_entry hashref as returned by libsvn_log_entry()
2937         log => 'whitespace-formatted log entry
2938 ',                                              # trailing newline is preserved
2939         revision => '8',                        # integer
2940         date => '2004-02-24T17:01:44.108345Z',  # commit date
2941         author => 'committer name'
2942 };
2945 # this is generated by generate_diff();
2946 @mods = array of diff-index line hashes, each element represents one line
2947         of diff-index output
2949 diff-index line ($m hash)
2951         mode_a => first column of diff-index output, no leading ':',
2952         mode_b => second column of diff-index output,
2953         sha1_b => sha1sum of the final blob,
2954         chg => change type [MCRADT],
2955         file_a => original file name of a file (iff chg is 'C' or 'R')
2956         file_b => new/current file name of a file (any chg)
2960 # retval of read_url_paths{,_all}();
2961 $l_map = {
2962         # repository root url
2963         'https://svn.musicpd.org' => {
2964                 # repository path               # GIT_SVN_ID
2965                 'mpd/trunk'             =>      'trunk',
2966                 'mpd/tags/0.11.5'       =>      'tags/0.11.5',
2967         },
2970 Notes:
2971         I don't trust the each() function on unless I created %hash myself
2972         because the internal iterator may not have started at base.