Code

Fix t4200-rerere for white-space from "wc -l"
[git.git] / git-svn.perl
1 #!/usr/bin/env perl
2 # Copyright (C) 2006, Eric Wong <normalperson@yhbt.net>
3 # License: GPL v2 or later
4 use warnings;
5 use strict;
6 use vars qw/    $AUTHOR $VERSION
7                 $sha1 $sha1_short $_revision
8                 $_q $_authors %users/;
9 $AUTHOR = 'Eric Wong <normalperson@yhbt.net>';
10 $VERSION = '@@GIT_VERSION@@';
12 my $git_dir_user_set = 1 if defined $ENV{GIT_DIR};
13 $ENV{GIT_DIR} ||= '.git';
14 $Git::SVN::default_repo_id = 'svn';
15 $Git::SVN::default_ref_id = $ENV{GIT_SVN_ID} || 'git-svn';
16 $Git::SVN::Ra::_log_window_size = 100;
18 $Git::SVN::Log::TZ = $ENV{TZ};
19 $ENV{TZ} = 'UTC';
20 $| = 1; # unbuffer STDOUT
22 sub fatal (@) { print STDERR @_; exit 1 }
23 require SVN::Core; # use()-ing this causes segfaults for me... *shrug*
24 require SVN::Ra;
25 require SVN::Delta;
26 if ($SVN::Core::VERSION lt '1.1.0') {
27         fatal "Need SVN::Core 1.1.0 or better (got $SVN::Core::VERSION)\n";
28 }
29 push @Git::SVN::Ra::ISA, 'SVN::Ra';
30 push @SVN::Git::Editor::ISA, 'SVN::Delta::Editor';
31 push @SVN::Git::Fetcher::ISA, 'SVN::Delta::Editor';
32 use Carp qw/croak/;
33 use IO::File qw//;
34 use File::Basename qw/dirname basename/;
35 use File::Path qw/mkpath/;
36 use Getopt::Long qw/:config gnu_getopt no_ignore_case auto_abbrev pass_through/;
37 use IPC::Open3;
38 use Git;
40 BEGIN {
41         my $s;
42         foreach (qw/command command_oneline command_noisy command_output_pipe
43                     command_input_pipe command_close_pipe/) {
44                 $s .= "*SVN::Git::Editor::$_ = *SVN::Git::Fetcher::$_ = ".
45                       "*Git::SVN::Migration::$_ = ".
46                       "*Git::SVN::Log::$_ = *Git::SVN::$_ = *$_ = *Git::$_; ";
47         }
48         eval $s;
49 }
51 my ($SVN);
53 $sha1 = qr/[a-f\d]{40}/;
54 $sha1_short = qr/[a-f\d]{4,40}/;
55 my ($_stdin, $_help, $_edit,
56         $_message, $_file,
57         $_template, $_shared,
58         $_version, $_fetch_all,
59         $_merge, $_strategy, $_dry_run, $_local,
60         $_prefix, $_no_checkout, $_verbose);
61 $Git::SVN::_follow_parent = 1;
62 my %remote_opts = ( 'username=s' => \$Git::SVN::Prompt::_username,
63                     'config-dir=s' => \$Git::SVN::Ra::config_dir,
64                     'no-auth-cache' => \$Git::SVN::Prompt::_no_auth_cache );
65 my %fc_opts = ( 'follow-parent|follow!' => \$Git::SVN::_follow_parent,
66                 'authors-file|A=s' => \$_authors,
67                 'repack:i' => \$Git::SVN::_repack,
68                 'noMetadata' => \$Git::SVN::_no_metadata,
69                 'useSvmProps' => \$Git::SVN::_use_svm_props,
70                 'useSvnsyncProps' => \$Git::SVN::_use_svnsync_props,
71                 'log-window-size=i' => \$Git::SVN::Ra::_log_window_size,
72                 'no-checkout' => \$_no_checkout,
73                 'quiet|q' => \$_q,
74                 'repack-flags|repack-args|repack-opts=s' =>
75                    \$Git::SVN::_repack_flags,
76                 %remote_opts );
78 my ($_trunk, $_tags, $_branches);
79 my %icv;
80 my %init_opts = ( 'template=s' => \$_template, 'shared:s' => \$_shared,
81                   'trunk|T=s' => \$_trunk, 'tags|t=s' => \$_tags,
82                   'branches|b=s' => \$_branches, 'prefix=s' => \$_prefix,
83                   'no-metadata' => sub { $icv{noMetadata} = 1 },
84                   'use-svm-props' => sub { $icv{useSvmProps} = 1 },
85                   'use-svnsync-props' => sub { $icv{useSvnsyncProps} = 1 },
86                   'rewrite-root=s' => sub { $icv{rewriteRoot} = $_[1] },
87                   %remote_opts );
88 my %cmt_opts = ( 'edit|e' => \$_edit,
89                 'rmdir' => \$SVN::Git::Editor::_rmdir,
90                 'find-copies-harder' => \$SVN::Git::Editor::_find_copies_harder,
91                 'l=i' => \$SVN::Git::Editor::_rename_limit,
92                 'copy-similarity|C=i'=> \$SVN::Git::Editor::_cp_similarity
93 );
95 my %cmd = (
96         fetch => [ \&cmd_fetch, "Download new revisions from SVN",
97                         { 'revision|r=s' => \$_revision,
98                           'fetch-all|all' => \$_fetch_all,
99                            %fc_opts } ],
100         clone => [ \&cmd_clone, "Initialize and fetch revisions",
101                         { 'revision|r=s' => \$_revision,
102                            %fc_opts, %init_opts } ],
103         init => [ \&cmd_init, "Initialize a repo for tracking" .
104                           " (requires URL argument)",
105                           \%init_opts ],
106         'multi-init' => [ \&cmd_multi_init,
107                           "Deprecated alias for ".
108                           "'$0 init -T<trunk> -b<branches> -t<tags>'",
109                           \%init_opts ],
110         dcommit => [ \&cmd_dcommit,
111                      'Commit several diffs to merge with upstream',
112                         { 'merge|m|M' => \$_merge,
113                           'strategy|s=s' => \$_strategy,
114                           'verbose|v' => \$_verbose,
115                           'dry-run|n' => \$_dry_run,
116                           'fetch-all|all' => \$_fetch_all,
117                         %cmt_opts, %fc_opts } ],
118         'set-tree' => [ \&cmd_set_tree,
119                         "Set an SVN repository to a git tree-ish",
120                         { 'stdin|' => \$_stdin, %cmt_opts, %fc_opts, } ],
121         'show-ignore' => [ \&cmd_show_ignore, "Show svn:ignore listings",
122                         { 'revision|r=i' => \$_revision } ],
123         'multi-fetch' => [ \&cmd_multi_fetch,
124                            "Deprecated alias for $0 fetch --all",
125                            { 'revision|r=s' => \$_revision, %fc_opts } ],
126         'migrate' => [ sub { },
127                        # no-op, we automatically run this anyways,
128                        'Migrate configuration/metadata/layout from
129                         previous versions of git-svn',
130                        { 'minimize' => \$Git::SVN::Migration::_minimize,
131                          %remote_opts } ],
132         'log' => [ \&Git::SVN::Log::cmd_show_log, 'Show commit logs',
133                         { 'limit=i' => \$Git::SVN::Log::limit,
134                           'revision|r=s' => \$_revision,
135                           'verbose|v' => \$Git::SVN::Log::verbose,
136                           'incremental' => \$Git::SVN::Log::incremental,
137                           'oneline' => \$Git::SVN::Log::oneline,
138                           'show-commit' => \$Git::SVN::Log::show_commit,
139                           'non-recursive' => \$Git::SVN::Log::non_recursive,
140                           'authors-file|A=s' => \$_authors,
141                           'color' => \$Git::SVN::Log::color,
142                           'pager=s' => \$Git::SVN::Log::pager,
143                         } ],
144         'rebase' => [ \&cmd_rebase, "Fetch and rebase your working directory",
145                         { 'merge|m|M' => \$_merge,
146                           'verbose|v' => \$_verbose,
147                           'strategy|s=s' => \$_strategy,
148                           'local|l' => \$_local,
149                           'fetch-all|all' => \$_fetch_all,
150                           %fc_opts } ],
151         'commit-diff' => [ \&cmd_commit_diff,
152                            'Commit a diff between two trees',
153                         { 'message|m=s' => \$_message,
154                           'file|F=s' => \$_file,
155                           'revision|r=s' => \$_revision,
156                         %cmt_opts } ],
157 );
159 my $cmd;
160 for (my $i = 0; $i < @ARGV; $i++) {
161         if (defined $cmd{$ARGV[$i]}) {
162                 $cmd = $ARGV[$i];
163                 splice @ARGV, $i, 1;
164                 last;
165         }
166 };
168 my %opts = %{$cmd{$cmd}->[2]} if (defined $cmd);
170 read_repo_config(\%opts);
171 my $rv = GetOptions(%opts, 'help|H|h' => \$_help, 'version|V' => \$_version,
172                     'minimize-connections' => \$Git::SVN::Migration::_minimize,
173                     'id|i=s' => \$Git::SVN::default_ref_id,
174                     'svn-remote|remote|R=s' => sub {
175                        $Git::SVN::no_reuse_existing = 1;
176                        $Git::SVN::default_repo_id = $_[1] });
177 exit 1 if (!$rv && $cmd ne 'log');
179 usage(0) if $_help;
180 version() if $_version;
181 usage(1) unless defined $cmd;
182 load_authors() if $_authors;
184 # make sure we're always running
185 unless ($cmd =~ /(?:clone|init|multi-init)$/) {
186         unless (-d $ENV{GIT_DIR}) {
187                 if ($git_dir_user_set) {
188                         die "GIT_DIR=$ENV{GIT_DIR} explicitly set, ",
189                             "but it is not a directory\n";
190                 }
191                 my $git_dir = delete $ENV{GIT_DIR};
192                 chomp(my $cdup = command_oneline(qw/rev-parse --show-cdup/));
193                 unless (length $cdup) {
194                         die "Already at toplevel, but $git_dir ",
195                             "not found '$cdup'\n";
196                 }
197                 chdir $cdup or die "Unable to chdir up to '$cdup'\n";
198                 unless (-d $git_dir) {
199                         die "$git_dir still not found after going to ",
200                             "'$cdup'\n";
201                 }
202                 $ENV{GIT_DIR} = $git_dir;
203         }
205 unless ($cmd =~ /^(?:clone|init|multi-init|commit-diff)$/) {
206         Git::SVN::Migration::migration_check();
208 Git::SVN::init_vars();
209 eval {
210         Git::SVN::verify_remotes_sanity();
211         $cmd{$cmd}->[0]->(@ARGV);
212 };
213 fatal $@ if $@;
214 post_fetch_checkout();
215 exit 0;
217 ####################### primary functions ######################
218 sub usage {
219         my $exit = shift || 0;
220         my $fd = $exit ? \*STDERR : \*STDOUT;
221         print $fd <<"";
222 git-svn - bidirectional operations between a single Subversion tree and git
223 Usage: $0 <command> [options] [arguments]\n
225         print $fd "Available commands:\n" unless $cmd;
227         foreach (sort keys %cmd) {
228                 next if $cmd && $cmd ne $_;
229                 next if /^multi-/; # don't show deprecated commands
230                 print $fd '  ',pack('A17',$_),$cmd{$_}->[1],"\n";
231                 foreach (keys %{$cmd{$_}->[2]}) {
232                         # prints out arguments as they should be passed:
233                         my $x = s#[:=]s$## ? '<arg>' : s#[:=]i$## ? '<num>' : '';
234                         print $fd ' ' x 21, join(', ', map { length $_ > 1 ?
235                                                         "--$_" : "-$_" }
236                                                 split /\|/,$_)," $x\n";
237                 }
238         }
239         print $fd <<"";
240 \nGIT_SVN_ID may be set in the environment or via the --id/-i switch to an
241 arbitrary identifier if you're tracking multiple SVN branches/repositories in
242 one git repository and want to keep them separate.  See git-svn(1) for more
243 information.
245         exit $exit;
248 sub version {
249         print "git-svn version $VERSION (svn $SVN::Core::VERSION)\n";
250         exit 0;
253 sub do_git_init_db {
254         unless (-d $ENV{GIT_DIR}) {
255                 my @init_db = ('init');
256                 push @init_db, "--template=$_template" if defined $_template;
257                 if (defined $_shared) {
258                         if ($_shared =~ /[a-z]/) {
259                                 push @init_db, "--shared=$_shared";
260                         } else {
261                                 push @init_db, "--shared";
262                         }
263                 }
264                 command_noisy(@init_db);
265         }
266         my $set;
267         my $pfx = "svn-remote.$Git::SVN::default_repo_id";
268         foreach my $i (keys %icv) {
269                 die "'$set' and '$i' cannot both be set\n" if $set;
270                 next unless defined $icv{$i};
271                 command_noisy('config', "$pfx.$i", $icv{$i});
272                 $set = $i;
273         }
276 sub init_subdir {
277         my $repo_path = shift or return;
278         mkpath([$repo_path]) unless -d $repo_path;
279         chdir $repo_path or die "Couldn't chdir to $repo_path: $!\n";
280         $ENV{GIT_DIR} = '.git';
283 sub cmd_clone {
284         my ($url, $path) = @_;
285         if (!defined $path &&
286             (defined $_trunk || defined $_branches || defined $_tags) &&
287             $url !~ m#^[a-z\+]+://#) {
288                 $path = $url;
289         }
290         $path = basename($url) if !defined $path || !length $path;
291         cmd_init($url, $path);
292         Git::SVN::fetch_all($Git::SVN::default_repo_id);
295 sub cmd_init {
296         if (defined $_trunk || defined $_branches || defined $_tags) {
297                 return cmd_multi_init(@_);
298         }
299         my $url = shift or die "SVN repository location required ",
300                                "as a command-line argument\n";
301         init_subdir(@_);
302         do_git_init_db();
304         Git::SVN->init($url);
307 sub cmd_fetch {
308         if (grep /^\d+=./, @_) {
309                 die "'<rev>=<commit>' fetch arguments are ",
310                     "no longer supported.\n";
311         }
312         my ($remote) = @_;
313         if (@_ > 1) {
314                 die "Usage: $0 fetch [--all] [svn-remote]\n";
315         }
316         $remote ||= $Git::SVN::default_repo_id;
317         if ($_fetch_all) {
318                 cmd_multi_fetch();
319         } else {
320                 Git::SVN::fetch_all($remote, Git::SVN::read_all_remotes());
321         }
324 sub cmd_set_tree {
325         my (@commits) = @_;
326         if ($_stdin || !@commits) {
327                 print "Reading from stdin...\n";
328                 @commits = ();
329                 while (<STDIN>) {
330                         if (/\b($sha1_short)\b/o) {
331                                 unshift @commits, $1;
332                         }
333                 }
334         }
335         my @revs;
336         foreach my $c (@commits) {
337                 my @tmp = command('rev-parse',$c);
338                 if (scalar @tmp == 1) {
339                         push @revs, $tmp[0];
340                 } elsif (scalar @tmp > 1) {
341                         push @revs, reverse(command('rev-list',@tmp));
342                 } else {
343                         fatal "Failed to rev-parse $c\n";
344                 }
345         }
346         my $gs = Git::SVN->new;
347         my ($r_last, $cmt_last) = $gs->last_rev_commit;
348         $gs->fetch;
349         if (defined $gs->{last_rev} && $r_last != $gs->{last_rev}) {
350                 fatal "There are new revisions that were fetched ",
351                       "and need to be merged (or acknowledged) ",
352                       "before committing.\nlast rev: $r_last\n",
353                       " current: $gs->{last_rev}\n";
354         }
355         $gs->set_tree($_) foreach @revs;
356         print "Done committing ",scalar @revs," revisions to SVN\n";
359 sub cmd_dcommit {
360         my $head = shift;
361         $head ||= 'HEAD';
362         my @refs;
363         my ($url, $rev, $uuid) = working_head_info($head, \@refs);
364         my $c = $refs[-1];
365         unless (defined $url && defined $rev && defined $uuid) {
366                 die "Unable to determine upstream SVN information from ",
367                     "$head history\n";
368         }
369         my $gs = Git::SVN->find_by_url($url);
370         my $last_rev;
371         foreach my $d (@refs) {
372                 if (!verify_ref("$d~1")) {
373                         fatal "Commit $d\n",
374                               "has no parent commit, and therefore ",
375                               "nothing to diff against.\n",
376                               "You should be working from a repository ",
377                               "originally created by git-svn\n";
378                 }
379                 unless (defined $last_rev) {
380                         (undef, $last_rev, undef) = cmt_metadata("$d~1");
381                         unless (defined $last_rev) {
382                                 fatal "Unable to extract revision information ",
383                                       "from commit $d~1\n";
384                         }
385                 }
386                 if ($_dry_run) {
387                         print "diff-tree $d~1 $d\n";
388                 } else {
389                         my %ed_opts = ( r => $last_rev,
390                                         log => get_commit_entry($d)->{log},
391                                         ra => Git::SVN::Ra->new($url),
392                                         tree_a => "$d~1",
393                                         tree_b => $d,
394                                         editor_cb => sub {
395                                                print "Committed r$_[0]\n";
396                                                $last_rev = $_[0]; },
397                                         svn_path => '');
398                         if (!SVN::Git::Editor->new(\%ed_opts)->apply_diff) {
399                                 print "No changes\n$d~1 == $d\n";
400                         }
401                 }
402         }
403         return if $_dry_run;
404         unless ($gs) {
405                 warn "Could not determine fetch information for $url\n",
406                      "Will not attempt to fetch and rebase commits.\n",
407                      "This probably means you have useSvmProps and should\n",
408                      "now resync your SVN::Mirror repository.\n";
409                 return;
410         }
411         $_fetch_all ? $gs->fetch_all : $gs->fetch;
412         # we always want to rebase against the current HEAD, not any
413         # head that was passed to us
414         my @diff = command('diff-tree', 'HEAD', $gs->refname, '--');
415         my @finish;
416         if (@diff) {
417                 @finish = rebase_cmd();
418                 print STDERR "W: HEAD and ", $gs->refname, " differ, ",
419                              "using @finish:\n", "@diff";
420         } else {
421                 print "No changes between current HEAD and ",
422                       $gs->refname, "\nResetting to the latest ",
423                       $gs->refname, "\n";
424                 @finish = qw/reset --mixed/;
425         }
426         command_noisy(@finish, $gs->refname);
429 sub cmd_rebase {
430         command_noisy(qw/update-index --refresh/);
431         my $url = (working_head_info('HEAD'))[0];
432         if (!defined $url) {
433                 die "Unable to determine upstream SVN information from ",
434                     "working tree history\n";
435         }
437         my $gs = Git::SVN->find_by_url($url);
438         unless ($gs) {
439                 die "Unable to determine remote information from URL: $url\n";
440         }
441         if (command(qw/diff-index HEAD --/)) {
442                 print STDERR "Cannot rebase with uncommited changes:\n";
443                 command_noisy('status');
444                 exit 1;
445         }
446         unless ($_local) {
447                 $_fetch_all ? $gs->fetch_all : $gs->fetch;
448         }
449         command_noisy(rebase_cmd(), $gs->refname);
452 sub cmd_show_ignore {
453         my $url = (::working_head_info('HEAD'))[0];
454         my $gs = Git::SVN->find_by_url($url) || Git::SVN->new;
455         my $r = (defined $_revision ? $_revision : $gs->ra->get_latest_revnum);
456         $gs->traverse_ignore(\*STDOUT, $gs->{path}, $r);
459 sub cmd_multi_init {
460         my $url = shift;
461         unless (defined $_trunk || defined $_branches || defined $_tags) {
462                 usage(1);
463         }
464         $_prefix = '' unless defined $_prefix;
465         if (defined $url) {
466                 $url =~ s#/+$##;
467                 init_subdir(@_);
468         }
469         do_git_init_db();
470         if (defined $_trunk) {
471                 my $trunk_ref = $_prefix . 'trunk';
472                 # try both old-style and new-style lookups:
473                 my $gs_trunk = eval { Git::SVN->new($trunk_ref) };
474                 unless ($gs_trunk) {
475                         my ($trunk_url, $trunk_path) =
476                                               complete_svn_url($url, $_trunk);
477                         $gs_trunk = Git::SVN->init($trunk_url, $trunk_path,
478                                                    undef, $trunk_ref);
479                 }
480         }
481         return unless defined $_branches || defined $_tags;
482         my $ra = $url ? Git::SVN::Ra->new($url) : undef;
483         complete_url_ls_init($ra, $_branches, '--branches/-b', $_prefix);
484         complete_url_ls_init($ra, $_tags, '--tags/-t', $_prefix . 'tags/');
487 sub cmd_multi_fetch {
488         my $remotes = Git::SVN::read_all_remotes();
489         foreach my $repo_id (sort keys %$remotes) {
490                 if ($remotes->{$repo_id}->{url}) {
491                         Git::SVN::fetch_all($repo_id, $remotes);
492                 }
493         }
496 # this command is special because it requires no metadata
497 sub cmd_commit_diff {
498         my ($ta, $tb, $url) = @_;
499         my $usage = "Usage: $0 commit-diff -r<revision> ".
500                     "<tree-ish> <tree-ish> [<URL>]\n";
501         fatal($usage) if (!defined $ta || !defined $tb);
502         my $svn_path;
503         if (!defined $url) {
504                 my $gs = eval { Git::SVN->new };
505                 if (!$gs) {
506                         fatal("Needed URL or usable git-svn --id in ",
507                               "the command-line\n", $usage);
508                 }
509                 $url = $gs->{url};
510                 $svn_path = $gs->{path};
511         }
512         unless (defined $_revision) {
513                 fatal("-r|--revision is a required argument\n", $usage);
514         }
515         if (defined $_message && defined $_file) {
516                 fatal("Both --message/-m and --file/-F specified ",
517                       "for the commit message.\n",
518                       "I have no idea what you mean\n");
519         }
520         if (defined $_file) {
521                 $_message = file_to_s($_file);
522         } else {
523                 $_message ||= get_commit_entry($tb)->{log};
524         }
525         my $ra ||= Git::SVN::Ra->new($url);
526         $svn_path ||= $ra->{svn_path};
527         my $r = $_revision;
528         if ($r eq 'HEAD') {
529                 $r = $ra->get_latest_revnum;
530         } elsif ($r !~ /^\d+$/) {
531                 die "revision argument: $r not understood by git-svn\n";
532         }
533         my %ed_opts = ( r => $r,
534                         log => $_message,
535                         ra => $ra,
536                         tree_a => $ta,
537                         tree_b => $tb,
538                         editor_cb => sub { print "Committed r$_[0]\n" },
539                         svn_path => $svn_path );
540         if (!SVN::Git::Editor->new(\%ed_opts)->apply_diff) {
541                 print "No changes\n$ta == $tb\n";
542         }
545 ########################### utility functions #########################
547 sub rebase_cmd {
548         my @cmd = qw/rebase/;
549         push @cmd, '-v' if $_verbose;
550         push @cmd, qw/--merge/ if $_merge;
551         push @cmd, "--strategy=$_strategy" if $_strategy;
552         @cmd;
555 sub post_fetch_checkout {
556         return if $_no_checkout;
557         my $gs = $Git::SVN::_head or return;
558         return if verify_ref('refs/heads/master^0');
560         my $valid_head = verify_ref('HEAD^0');
561         command_noisy(qw(update-ref refs/heads/master), $gs->refname);
562         return if ($valid_head || !verify_ref('HEAD^0'));
564         return if $ENV{GIT_DIR} !~ m#^(?:.*/)?\.git$#;
565         my $index = $ENV{GIT_INDEX_FILE} || "$ENV{GIT_DIR}/index";
566         return if -f $index;
568         chomp(my $bare = `git config --bool --get core.bare`);
569         return if $bare eq 'true';
570         return if command_oneline(qw/rev-parse --is-inside-git-dir/) eq 'true';
571         command_noisy(qw/read-tree -m -u -v HEAD HEAD/);
572         print STDERR "Checked out HEAD:\n  ",
573                      $gs->full_url, " r", $gs->last_rev, "\n";
576 sub complete_svn_url {
577         my ($url, $path) = @_;
578         $path =~ s#/+$##;
579         if ($path !~ m#^[a-z\+]+://#) {
580                 if (!defined $url || $url !~ m#^[a-z\+]+://#) {
581                         fatal("E: '$path' is not a complete URL ",
582                               "and a separate URL is not specified\n");
583                 }
584                 return ($url, $path);
585         }
586         return ($path, '');
589 sub complete_url_ls_init {
590         my ($ra, $repo_path, $switch, $pfx) = @_;
591         unless ($repo_path) {
592                 print STDERR "W: $switch not specified\n";
593                 return;
594         }
595         $repo_path =~ s#/+$##;
596         if ($repo_path =~ m#^[a-z\+]+://#) {
597                 $ra = Git::SVN::Ra->new($repo_path);
598                 $repo_path = '';
599         } else {
600                 $repo_path =~ s#^/+##;
601                 unless ($ra) {
602                         fatal("E: '$repo_path' is not a complete URL ",
603                               "and a separate URL is not specified\n");
604                 }
605         }
606         my $url = $ra->{url};
607         my $gs = Git::SVN->init($url, undef, undef, undef, 1);
608         my $k = "svn-remote.$gs->{repo_id}.url";
609         my $orig_url = eval { command_oneline(qw/config --get/, $k) };
610         if ($orig_url && ($orig_url ne $gs->{url})) {
611                 die "$k already set: $orig_url\n",
612                     "wanted to set to: $gs->{url}\n";
613         }
614         command_oneline('config', $k, $gs->{url}) unless $orig_url;
615         my $remote_path = "$ra->{svn_path}/$repo_path/*";
616         $remote_path =~ s#/+#/#g;
617         $remote_path =~ s#^/##g;
618         my ($n) = ($switch =~ /^--(\w+)/);
619         if (length $pfx && $pfx !~ m#/$#) {
620                 die "--prefix='$pfx' must have a trailing slash '/'\n";
621         }
622         command_noisy('config', "svn-remote.$gs->{repo_id}.$n",
623                                 "$remote_path:refs/remotes/$pfx*");
626 sub verify_ref {
627         my ($ref) = @_;
628         eval { command_oneline([ 'rev-parse', '--verify', $ref ],
629                                { STDERR => 0 }); };
632 sub get_tree_from_treeish {
633         my ($treeish) = @_;
634         # $treeish can be a symbolic ref, too:
635         my $type = command_oneline(qw/cat-file -t/, $treeish);
636         my $expected;
637         while ($type eq 'tag') {
638                 ($treeish, $type) = command(qw/cat-file tag/, $treeish);
639         }
640         if ($type eq 'commit') {
641                 $expected = (grep /^tree /, command(qw/cat-file commit/,
642                                                     $treeish))[0];
643                 ($expected) = ($expected =~ /^tree ($sha1)$/o);
644                 die "Unable to get tree from $treeish\n" unless $expected;
645         } elsif ($type eq 'tree') {
646                 $expected = $treeish;
647         } else {
648                 die "$treeish is a $type, expected tree, tag or commit\n";
649         }
650         return $expected;
653 sub get_commit_entry {
654         my ($treeish) = shift;
655         my %log_entry = ( log => '', tree => get_tree_from_treeish($treeish) );
656         my $commit_editmsg = "$ENV{GIT_DIR}/COMMIT_EDITMSG";
657         my $commit_msg = "$ENV{GIT_DIR}/COMMIT_MSG";
658         open my $log_fh, '>', $commit_editmsg or croak $!;
660         my $type = command_oneline(qw/cat-file -t/, $treeish);
661         if ($type eq 'commit' || $type eq 'tag') {
662                 my ($msg_fh, $ctx) = command_output_pipe('cat-file',
663                                                          $type, $treeish);
664                 my $in_msg = 0;
665                 while (<$msg_fh>) {
666                         if (!$in_msg) {
667                                 $in_msg = 1 if (/^\s*$/);
668                         } elsif (/^git-svn-id: /) {
669                                 # skip this for now, we regenerate the
670                                 # correct one on re-fetch anyways
671                                 # TODO: set *:merge properties or like...
672                         } else {
673                                 print $log_fh $_ or croak $!;
674                         }
675                 }
676                 command_close_pipe($msg_fh, $ctx);
677         }
678         close $log_fh or croak $!;
680         if ($_edit || ($type eq 'tree')) {
681                 my $editor = $ENV{VISUAL} || $ENV{EDITOR} || 'vi';
682                 # TODO: strip out spaces, comments, like git-commit.sh
683                 system($editor, $commit_editmsg);
684         }
685         rename $commit_editmsg, $commit_msg or croak $!;
686         open $log_fh, '<', $commit_msg or croak $!;
687         { local $/; chomp($log_entry{log} = <$log_fh>); }
688         close $log_fh or croak $!;
689         unlink $commit_msg;
690         \%log_entry;
693 sub s_to_file {
694         my ($str, $file, $mode) = @_;
695         open my $fd,'>',$file or croak $!;
696         print $fd $str,"\n" or croak $!;
697         close $fd or croak $!;
698         chmod ($mode &~ umask, $file) if (defined $mode);
701 sub file_to_s {
702         my $file = shift;
703         open my $fd,'<',$file or croak "$!: file: $file\n";
704         local $/;
705         my $ret = <$fd>;
706         close $fd or croak $!;
707         $ret =~ s/\s*$//s;
708         return $ret;
711 # '<svn username> = real-name <email address>' mapping based on git-svnimport:
712 sub load_authors {
713         open my $authors, '<', $_authors or die "Can't open $_authors $!\n";
714         my $log = $cmd eq 'log';
715         while (<$authors>) {
716                 chomp;
717                 next unless /^(\S+?|\(no author\))\s*=\s*(.+?)\s*<(.+)>\s*$/;
718                 my ($user, $name, $email) = ($1, $2, $3);
719                 if ($log) {
720                         $Git::SVN::Log::rusers{"$name <$email>"} = $user;
721                 } else {
722                         $users{$user} = [$name, $email];
723                 }
724         }
725         close $authors or croak $!;
728 # convert GetOpt::Long specs for use by git-config
729 sub read_repo_config {
730         return unless -d $ENV{GIT_DIR};
731         my $opts = shift;
732         my @config_only;
733         foreach my $o (keys %$opts) {
734                 # if we have mixedCase and a long option-only, then
735                 # it's a config-only variable that we don't need for
736                 # the command-line.
737                 push @config_only, $o if ($o =~ /[A-Z]/ && $o =~ /^[a-z]+$/i);
738                 my $v = $opts->{$o};
739                 my ($key) = ($o =~ /^([a-zA-Z\-]+)/);
740                 $key =~ s/-//g;
741                 my $arg = 'git-config';
742                 $arg .= ' --int' if ($o =~ /[:=]i$/);
743                 $arg .= ' --bool' if ($o !~ /[:=][sfi]$/);
744                 if (ref $v eq 'ARRAY') {
745                         chomp(my @tmp = `$arg --get-all svn.$key`);
746                         @$v = @tmp if @tmp;
747                 } else {
748                         chomp(my $tmp = `$arg --get svn.$key`);
749                         if ($tmp && !($arg =~ / --bool/ && $tmp eq 'false')) {
750                                 $$v = $tmp;
751                         }
752                 }
753         }
754         delete @$opts{@config_only} if @config_only;
757 sub extract_metadata {
758         my $id = shift or return (undef, undef, undef);
759         my ($url, $rev, $uuid) = ($id =~ /^git-svn-id:\s(\S+?)\@(\d+)
760                                                         \s([a-f\d\-]+)$/x);
761         if (!defined $rev || !$uuid || !$url) {
762                 # some of the original repositories I made had
763                 # identifiers like this:
764                 ($rev, $uuid) = ($id =~/^git-svn-id:\s(\d+)\@([a-f\d\-]+)/);
765         }
766         return ($url, $rev, $uuid);
769 sub cmt_metadata {
770         return extract_metadata((grep(/^git-svn-id: /,
771                 command(qw/cat-file commit/, shift)))[-1]);
774 sub working_head_info {
775         my ($head, $refs) = @_;
776         my ($url, $rev, $uuid);
777         my ($fh, $ctx) = command_output_pipe('rev-list', $head);
778         while (<$fh>) {
779                 chomp;
780                 ($url, $rev, $uuid) = cmt_metadata($_);
781                 last if (defined $url && defined $rev && defined $uuid);
782                 unshift @$refs, $_ if $refs;
783         }
784         close $fh; # break the pipe
785         ($url, $rev, $uuid);
788 package Git::SVN;
789 use strict;
790 use warnings;
791 use vars qw/$default_repo_id $default_ref_id $_no_metadata $_follow_parent
792             $_repack $_repack_flags $_use_svm_props $_head
793             $_use_svnsync_props $no_reuse_existing/;
794 use Carp qw/croak/;
795 use File::Path qw/mkpath/;
796 use File::Copy qw/copy/;
797 use IPC::Open3;
799 my $_repack_nr;
800 # properties that we do not log:
801 my %SKIP_PROP;
802 BEGIN {
803         %SKIP_PROP = map { $_ => 1 } qw/svn:wc:ra_dav:version-url
804                                         svn:special svn:executable
805                                         svn:entry:committed-rev
806                                         svn:entry:last-author
807                                         svn:entry:uuid
808                                         svn:entry:committed-date/;
810         # some options are read globally, but can be overridden locally
811         # per [svn-remote "..."] section.  Command-line options will *NOT*
812         # override options set in an [svn-remote "..."] section
813         my $e;
814         foreach (qw/follow_parent no_metadata use_svm_props
815                     use_svnsync_props/) {
816                 my $key = $_;
817                 $key =~ tr/_//d;
818                 $e .= "sub $_ {
819                         my (\$self) = \@_;
820                         return \$self->{-$_} if exists \$self->{-$_};
821                         my \$k = \"svn-remote.\$self->{repo_id}\.$key\";
822                         eval { command_oneline(qw/config --get/, \$k) };
823                         if (\$@) {
824                                 \$self->{-$_} = \$Git::SVN::_$_;
825                         } else {
826                                 my \$v = command_oneline(qw/config --bool/,\$k);
827                                 \$self->{-$_} = \$v eq 'false' ? 0 : 1;
828                         }
829                         return \$self->{-$_} }\n";
830         }
831         $e .= "1;\n";
832         eval $e or die $@;
835 my %LOCKFILES;
836 END { unlink keys %LOCKFILES if %LOCKFILES }
838 sub resolve_local_globs {
839         my ($url, $fetch, $glob_spec) = @_;
840         return unless defined $glob_spec;
841         my $ref = $glob_spec->{ref};
842         my $path = $glob_spec->{path};
843         foreach (command(qw#for-each-ref --format=%(refname) refs/remotes#)) {
844                 next unless m#^refs/remotes/$ref->{regex}$#;
845                 my $p = $1;
846                 my $pathname = $path->full_path($p);
847                 my $refname = $ref->full_path($p);
848                 if (my $existing = $fetch->{$pathname}) {
849                         if ($existing ne $refname) {
850                                 die "Refspec conflict:\n",
851                                     "existing: refs/remotes/$existing\n",
852                                     " globbed: refs/remotes/$refname\n";
853                         }
854                         my $u = (::cmt_metadata("refs/remotes/$refname"))[0];
855                         $u =~ s!^\Q$url\E(/|$)!! or die
856                           "refs/remotes/$refname: '$url' not found in '$u'\n";
857                         if ($pathname ne $u) {
858                                 warn "W: Refspec glob conflict ",
859                                      "(ref: refs/remotes/$refname):\n",
860                                      "expected path: $pathname\n",
861                                      "    real path: $u\n",
862                                      "Continuing ahead with $u\n";
863                                 next;
864                         }
865                 } else {
866                         $fetch->{$pathname} = $refname;
867                 }
868         }
871 sub parse_revision_argument {
872         my ($base, $head) = @_;
873         if (!defined $::_revision || $::_revision eq 'BASE:HEAD') {
874                 return ($base, $head);
875         }
876         return ($1, $2) if ($::_revision =~ /^(\d+):(\d+)$/);
877         return ($::_revision, $::_revision) if ($::_revision =~ /^\d+$/);
878         return ($head, $head) if ($::_revision eq 'HEAD');
879         return ($base, $1) if ($::_revision =~ /^BASE:(\d+)$/);
880         return ($1, $head) if ($::_revision =~ /^(\d+):HEAD$/);
881         die "revision argument: $::_revision not understood by git-svn\n";
884 sub fetch_all {
885         my ($repo_id, $remotes) = @_;
886         if (ref $repo_id) {
887                 my $gs = $repo_id;
888                 $repo_id = undef;
889                 $repo_id = $gs->{repo_id};
890         }
891         $remotes ||= read_all_remotes();
892         my $remote = $remotes->{$repo_id} or
893                      die "[svn-remote \"$repo_id\"] unknown\n";
894         my $fetch = $remote->{fetch};
895         my $url = $remote->{url} or die "svn-remote.$repo_id.url not defined\n";
896         my (@gs, @globs);
897         my $ra = Git::SVN::Ra->new($url);
898         my $uuid = $ra->get_uuid;
899         my $head = $ra->get_latest_revnum;
900         my $base = defined $fetch ? $head : 0;
902         # read the max revs for wildcard expansion (branches/*, tags/*)
903         foreach my $t (qw/branches tags/) {
904                 defined $remote->{$t} or next;
905                 push @globs, $remote->{$t};
906                 my $max_rev = eval { tmp_config(qw/--int --get/,
907                                          "svn-remote.$repo_id.${t}-maxRev") };
908                 if (defined $max_rev && ($max_rev < $base)) {
909                         $base = $max_rev;
910                 } elsif (!defined $max_rev) {
911                         $base = 0;
912                 }
913         }
915         if ($fetch) {
916                 foreach my $p (sort keys %$fetch) {
917                         my $gs = Git::SVN->new($fetch->{$p}, $repo_id, $p);
918                         my $lr = $gs->rev_db_max;
919                         if (defined $lr) {
920                                 $base = $lr if ($lr < $base);
921                         }
922                         push @gs, $gs;
923                 }
924         }
926         ($base, $head) = parse_revision_argument($base, $head);
927         $ra->gs_fetch_loop_common($base, $head, \@gs, \@globs);
930 sub read_all_remotes {
931         my $r = {};
932         foreach (grep { s/^svn-remote\.// } command(qw/config -l/)) {
933                 if (m!^(.+)\.fetch=\s*(.*)\s*:\s*refs/remotes/(.+)\s*$!) {
934                         $r->{$1}->{fetch}->{$2} = $3;
935                 } elsif (m!^(.+)\.url=\s*(.*)\s*$!) {
936                         $r->{$1}->{url} = $2;
937                 } elsif (m!^(.+)\.(branches|tags)=
938                            (.*):refs/remotes/(.+)\s*$/!x) {
939                         my ($p, $g) = ($3, $4);
940                         my $rs = $r->{$1}->{$2} = {
941                                           t => $2,
942                                           remote => $1,
943                                           path => Git::SVN::GlobSpec->new($p),
944                                           ref => Git::SVN::GlobSpec->new($g) };
945                         if (length($rs->{ref}->{right}) != 0) {
946                                 die "The '*' glob character must be the last ",
947                                     "character of '$g'\n";
948                         }
949                 }
950         }
951         $r;
954 sub init_vars {
955         if (defined $_repack) {
956                 $_repack = 1000 if ($_repack <= 0);
957                 $_repack_nr = $_repack;
958                 $_repack_flags ||= '-d';
959         }
962 sub verify_remotes_sanity {
963         return unless -d $ENV{GIT_DIR};
964         my %seen;
965         foreach (command(qw/config -l/)) {
966                 if (m!^svn-remote\.(?:.+)\.fetch=.*:refs/remotes/(\S+)\s*$!) {
967                         if ($seen{$1}) {
968                                 die "Remote ref refs/remote/$1 is tracked by",
969                                     "\n  \"$_\"\nand\n  \"$seen{$1}\"\n",
970                                     "Please resolve this ambiguity in ",
971                                     "your git configuration file before ",
972                                     "continuing\n";
973                         }
974                         $seen{$1} = $_;
975                 }
976         }
979 # we allow more chars than remotes2config.sh...
980 sub sanitize_remote_name {
981         my ($name) = @_;
982         $name =~ tr{A-Za-z0-9:,/+-}{.}c;
983         $name;
986 sub find_existing_remote {
987         my ($url, $remotes) = @_;
988         return undef if $no_reuse_existing;
989         my $existing;
990         foreach my $repo_id (keys %$remotes) {
991                 my $u = $remotes->{$repo_id}->{url} or next;
992                 next if $u ne $url;
993                 $existing = $repo_id;
994                 last;
995         }
996         $existing;
999 sub init_remote_config {
1000         my ($self, $url, $no_write) = @_;
1001         $url =~ s!/+$!!; # strip trailing slash
1002         my $r = read_all_remotes();
1003         my $existing = find_existing_remote($url, $r);
1004         if ($existing) {
1005                 unless ($no_write) {
1006                         print STDERR "Using existing ",
1007                                      "[svn-remote \"$existing\"]\n";
1008                 }
1009                 $self->{repo_id} = $existing;
1010         } else {
1011                 my $min_url = Git::SVN::Ra->new($url)->minimize_url;
1012                 $existing = find_existing_remote($min_url, $r);
1013                 if ($existing) {
1014                         unless ($no_write) {
1015                                 print STDERR "Using existing ",
1016                                              "[svn-remote \"$existing\"]\n";
1017                         }
1018                         $self->{repo_id} = $existing;
1019                 }
1020                 if ($min_url ne $url) {
1021                         unless ($no_write) {
1022                                 print STDERR "Using higher level of URL: ",
1023                                              "$url => $min_url\n";
1024                         }
1025                         my $old_path = $self->{path};
1026                         $self->{path} = $url;
1027                         $self->{path} =~ s!^\Q$min_url\E(/|$)!!;
1028                         if (length $old_path) {
1029                                 $self->{path} .= "/$old_path";
1030                         }
1031                         $url = $min_url;
1032                 }
1033         }
1034         my $orig_url;
1035         if (!$existing) {
1036                 # verify that we aren't overwriting anything:
1037                 $orig_url = eval {
1038                         command_oneline('config', '--get',
1039                                         "svn-remote.$self->{repo_id}.url")
1040                 };
1041                 if ($orig_url && ($orig_url ne $url)) {
1042                         die "svn-remote.$self->{repo_id}.url already set: ",
1043                             "$orig_url\nwanted to set to: $url\n";
1044                 }
1045         }
1046         my ($xrepo_id, $xpath) = find_ref($self->refname);
1047         if (defined $xpath) {
1048                 die "svn-remote.$xrepo_id.fetch already set to track ",
1049                     "$xpath:refs/remotes/", $self->refname, "\n";
1050         }
1051         unless ($no_write) {
1052                 command_noisy('config',
1053                               "svn-remote.$self->{repo_id}.url", $url);
1054                 command_noisy('config', '--add',
1055                               "svn-remote.$self->{repo_id}.fetch",
1056                               "$self->{path}:".$self->refname);
1057         }
1058         $self->{url} = $url;
1061 sub find_by_url { # repos_root and, path are optional
1062         my ($class, $full_url, $repos_root, $path) = @_;
1063         return undef unless defined $full_url;
1064         my $remotes = read_all_remotes();
1065         if (defined $full_url && defined $repos_root && !defined $path) {
1066                 $path = $full_url;
1067                 $path =~ s#^\Q$repos_root\E(?:/|$)##;
1068         }
1069         foreach my $repo_id (keys %$remotes) {
1070                 my $u = $remotes->{$repo_id}->{url} or next;
1071                 next if defined $repos_root && $repos_root ne $u;
1073                 my $fetch = $remotes->{$repo_id}->{fetch} || {};
1074                 foreach (qw/branches tags/) {
1075                         resolve_local_globs($u, $fetch,
1076                                             $remotes->{$repo_id}->{$_});
1077                 }
1078                 my $p = $path;
1079                 unless (defined $p) {
1080                         $p = $full_url;
1081                         $p =~ s#^\Q$u\E(?:/|$)## or next;
1082                 }
1083                 foreach my $f (keys %$fetch) {
1084                         next if $f ne $p;
1085                         return Git::SVN->new($fetch->{$f}, $repo_id, $f);
1086                 }
1087         }
1088         undef;
1091 sub init {
1092         my ($class, $url, $path, $repo_id, $ref_id, $no_write) = @_;
1093         my $self = _new($class, $repo_id, $ref_id, $path);
1094         if (defined $url) {
1095                 $self->init_remote_config($url, $no_write);
1096         }
1097         $self;
1100 sub find_ref {
1101         my ($ref_id) = @_;
1102         foreach (command(qw/config -l/)) {
1103                 next unless m!^svn-remote\.(.+)\.fetch=
1104                               \s*(.*)\s*:\s*refs/remotes/(.+)\s*$!x;
1105                 my ($repo_id, $path, $ref) = ($1, $2, $3);
1106                 if ($ref eq $ref_id) {
1107                         $path = '' if ($path =~ m#^\./?#);
1108                         return ($repo_id, $path);
1109                 }
1110         }
1111         (undef, undef, undef);
1114 sub new {
1115         my ($class, $ref_id, $repo_id, $path) = @_;
1116         if (defined $ref_id && !defined $repo_id && !defined $path) {
1117                 ($repo_id, $path) = find_ref($ref_id);
1118                 if (!defined $repo_id) {
1119                         die "Could not find a \"svn-remote.*.fetch\" key ",
1120                             "in the repository configuration matching: ",
1121                             "refs/remotes/$ref_id\n";
1122                 }
1123         }
1124         my $self = _new($class, $repo_id, $ref_id, $path);
1125         if (!defined $self->{path} || !length $self->{path}) {
1126                 my $fetch = command_oneline('config', '--get',
1127                                             "svn-remote.$repo_id.fetch",
1128                                             ":refs/remotes/$ref_id\$") or
1129                      die "Failed to read \"svn-remote.$repo_id.fetch\" ",
1130                          "\":refs/remotes/$ref_id\$\" in config\n";
1131                 ($self->{path}, undef) = split(/\s*:\s*/, $fetch);
1132         }
1133         $self->{url} = command_oneline('config', '--get',
1134                                        "svn-remote.$repo_id.url") or
1135                   die "Failed to read \"svn-remote.$repo_id.url\" in config\n";
1136         $self->rebuild;
1137         $self;
1140 sub refname { "refs/remotes/$_[0]->{ref_id}" }
1142 sub svm_uuid {
1143         my ($self) = @_;
1144         return $self->{svm}->{uuid} if $self->svm;
1145         $self->ra;
1146         unless ($self->{svm}) {
1147                 die "SVM UUID not cached, and reading remotely failed\n";
1148         }
1149         $self->{svm}->{uuid};
1152 sub svm {
1153         my ($self) = @_;
1154         return $self->{svm} if $self->{svm};
1155         my $svm;
1156         # see if we have it in our config, first:
1157         eval {
1158                 my $section = "svn-remote.$self->{repo_id}";
1159                 $svm = {
1160                   source => tmp_config('--get', "$section.svm-source"),
1161                   uuid => tmp_config('--get', "$section.svm-uuid"),
1162                   replace => tmp_config('--get', "$section.svm-replace"),
1163                 }
1164         };
1165         if ($svm && $svm->{source} && $svm->{uuid} && $svm->{replace}) {
1166                 $self->{svm} = $svm;
1167         }
1168         $self->{svm};
1171 sub _set_svm_vars {
1172         my ($self, $ra) = @_;
1173         return $ra if $self->svm;
1175         my @err = ( "useSvmProps set, but failed to read SVM properties\n",
1176                     "(svm:source, svm:uuid) ",
1177                     "from the following URLs:\n" );
1178         sub read_svm_props {
1179                 my ($self, $ra, $path, $r) = @_;
1180                 my $props = ($ra->get_dir($path, $r))[2];
1181                 my $src = $props->{'svm:source'};
1182                 my $uuid = $props->{'svm:uuid'};
1183                 return undef if (!$src || !$uuid);
1185                 chomp($src, $uuid);
1187                 $uuid =~ m{^[0-9a-f\-]{30,}$}
1188                     or die "doesn't look right - svm:uuid is '$uuid'\n";
1190                 # the '!' is used to mark the repos_root!/relative/path
1191                 $src =~ s{/?!/?}{/};
1192                 $src =~ s{/+$}{}; # no trailing slashes please
1193                 # username is of no interest
1194                 $src =~ s{(^[a-z\+]*://)[^/@]*@}{$1};
1196                 my $replace = $ra->{url};
1197                 $replace .= "/$path" if length $path;
1199                 my $section = "svn-remote.$self->{repo_id}";
1200                 tmp_config("$section.svm-source", $src);
1201                 tmp_config("$section.svm-replace", $replace);
1202                 tmp_config("$section.svm-uuid", $uuid);
1203                 $self->{svm} = {
1204                         source => $src,
1205                         uuid => $uuid,
1206                         replace => $replace
1207                 };
1208         }
1210         my $r = $ra->get_latest_revnum;
1211         my $path = $self->{path};
1212         my %tried;
1213         while (length $path) {
1214                 unless ($tried{"$self->{url}/$path"}) {
1215                         return $ra if $self->read_svm_props($ra, $path, $r);
1216                         $tried{"$self->{url}/$path"} = 1;
1217                 }
1218                 $path =~ s#/?[^/]+$##;
1219         }
1220         die "Path: '$path' should be ''\n" if $path ne '';
1221         return $ra if $self->read_svm_props($ra, $path, $r);
1222         $tried{"$self->{url}/$path"} = 1;
1224         if ($ra->{repos_root} eq $self->{url}) {
1225                 die @err, (map { "  $_\n" } keys %tried), "\n";
1226         }
1228         # nope, make sure we're connected to the repository root:
1229         my $ok;
1230         my @tried_b;
1231         $path = $ra->{svn_path};
1232         $ra = Git::SVN::Ra->new($ra->{repos_root});
1233         while (length $path) {
1234                 unless ($tried{"$ra->{url}/$path"}) {
1235                         $ok = $self->read_svm_props($ra, $path, $r);
1236                         last if $ok;
1237                         $tried{"$ra->{url}/$path"} = 1;
1238                 }
1239                 $path =~ s#/?[^/]+$##;
1240         }
1241         die "Path: '$path' should be ''\n" if $path ne '';
1242         $ok ||= $self->read_svm_props($ra, $path, $r);
1243         $tried{"$ra->{url}/$path"} = 1;
1244         if (!$ok) {
1245                 die @err, (map { "  $_\n" } keys %tried), "\n";
1246         }
1247         Git::SVN::Ra->new($self->{url});
1250 sub svnsync {
1251         my ($self) = @_;
1252         return $self->{svnsync} if $self->{svnsync};
1254         if ($self->no_metadata) {
1255                 die "Can't have both 'noMetadata' and ",
1256                     "'useSvnsyncProps' options set!\n";
1257         }
1258         if ($self->rewrite_root) {
1259                 die "Can't have both 'useSvnsyncProps' and 'rewriteRoot' ",
1260                     "options set!\n";
1261         }
1263         my $svnsync;
1264         # see if we have it in our config, first:
1265         eval {
1266                 my $section = "svn-remote.$self->{repo_id}";
1267                 $svnsync = {
1268                   url => tmp_config('--get', "$section.svnsync-url"),
1269                   uuid => tmp_config('--get', "$section.svnsync-uuid"),
1270                 }
1271         };
1272         if ($svnsync && $svnsync->{url} && $svnsync->{uuid}) {
1273                 return $self->{svnsync} = $svnsync;
1274         }
1276         my $err = "useSvnsyncProps set, but failed to read " .
1277                   "svnsync property: svn:sync-from-";
1278         my $rp = $self->ra->rev_proplist(0);
1280         my $url = $rp->{'svn:sync-from-url'} or die $err . "url\n";
1281         $url =~ m{^[a-z\+]+://} or
1282                    die "doesn't look right - svn:sync-from-url is '$url'\n";
1284         my $uuid = $rp->{'svn:sync-from-uuid'} or die $err . "uuid\n";
1285         $uuid =~ m{^[0-9a-f\-]{30,}$} or
1286                    die "doesn't look right - svn:sync-from-uuid is '$uuid'\n";
1288         my $section = "svn-remote.$self->{repo_id}";
1289         tmp_config('--add', "$section.svnsync-uuid", $uuid);
1290         tmp_config('--add', "$section.svnsync-url", $url);
1291         return $self->{svnsync} = { url => $url, uuid => $uuid };
1294 # this allows us to memoize our SVN::Ra UUID locally and avoid a
1295 # remote lookup (useful for 'git svn log').
1296 sub ra_uuid {
1297         my ($self) = @_;
1298         unless ($self->{ra_uuid}) {
1299                 my $key = "svn-remote.$self->{repo_id}.uuid";
1300                 my $uuid = eval { tmp_config('--get', $key) };
1301                 if (!$@ && $uuid && $uuid =~ /^([a-f\d\-]{30,})$/) {
1302                         $self->{ra_uuid} = $uuid;
1303                 } else {
1304                         die "ra_uuid called without URL\n" unless $self->{url};
1305                         $self->{ra_uuid} = $self->ra->get_uuid;
1306                         tmp_config('--add', $key, $self->{ra_uuid});
1307                 }
1308         }
1309         $self->{ra_uuid};
1312 sub ra {
1313         my ($self) = shift;
1314         my $ra = Git::SVN::Ra->new($self->{url});
1315         if ($self->use_svm_props && !$self->{svm}) {
1316                 if ($self->no_metadata) {
1317                         die "Can't have both 'noMetadata' and ",
1318                             "'useSvmProps' options set!\n";
1319                 } elsif ($self->use_svnsync_props) {
1320                         die "Can't have both 'useSvnsyncProps' and ",
1321                             "'useSvmProps' options set!\n";
1322                 }
1323                 $ra = $self->_set_svm_vars($ra);
1324                 $self->{-want_revprops} = 1;
1325         }
1326         $ra;
1329 sub rel_path {
1330         my ($self) = @_;
1331         my $repos_root = $self->ra->{repos_root};
1332         return $self->{path} if ($self->{url} eq $repos_root);
1333         my $url = $self->{url} .
1334                   (length $self->{path} ? "/$self->{path}" : $self->{path});
1335         $url =~ s!^\Q$repos_root\E(?:/+|$)!!g;
1336         $url;
1339 sub traverse_ignore {
1340         my ($self, $fh, $path, $r) = @_;
1341         $path =~ s#^/+##g;
1342         my $ra = $self->ra;
1343         my ($dirent, undef, $props) = $ra->get_dir($path, $r);
1344         my $p = $path;
1345         $p =~ s#^\Q$self->{path}\E(/|$)##;
1346         print $fh length $p ? "\n# $p\n" : "\n# /\n";
1347         if (my $s = $props->{'svn:ignore'}) {
1348                 $s =~ s/[\r\n]+/\n/g;
1349                 chomp $s;
1350                 if (length $p == 0) {
1351                         $s =~ s#\n#\n/$p#g;
1352                         print $fh "/$s\n";
1353                 } else {
1354                         $s =~ s#\n#\n/$p/#g;
1355                         print $fh "/$p/$s\n";
1356                 }
1357         }
1358         foreach (sort keys %$dirent) {
1359                 next if $dirent->{$_}->kind != $SVN::Node::dir;
1360                 $self->traverse_ignore($fh, "$path/$_", $r);
1361         }
1364 sub last_rev { ($_[0]->last_rev_commit)[0] }
1365 sub last_commit { ($_[0]->last_rev_commit)[1] }
1367 # returns the newest SVN revision number and newest commit SHA1
1368 sub last_rev_commit {
1369         my ($self) = @_;
1370         if (defined $self->{last_rev} && defined $self->{last_commit}) {
1371                 return ($self->{last_rev}, $self->{last_commit});
1372         }
1373         my $c = ::verify_ref($self->refname.'^0');
1374         if ($c && !$self->use_svm_props && !$self->no_metadata) {
1375                 my $rev = (::cmt_metadata($c))[1];
1376                 if (defined $rev) {
1377                         ($self->{last_rev}, $self->{last_commit}) = ($rev, $c);
1378                         return ($rev, $c);
1379                 }
1380         }
1381         my $db_path = $self->db_path;
1382         unless (-e $db_path) {
1383                 ($self->{last_rev}, $self->{last_commit}) = (undef, undef);
1384                 return (undef, undef);
1385         }
1386         my $offset = -41; # from tail
1387         my $rl;
1388         open my $fh, '<', $db_path or croak "$db_path not readable: $!\n";
1389         sysseek($fh, $offset, 2); # don't care for errors
1390         sysread($fh, $rl, 41) == 41 or return (undef, undef);
1391         chomp $rl;
1392         while (('0' x40) eq $rl && sysseek($fh, 0, 1) != 0) {
1393                 $offset -= 41;
1394                 sysseek($fh, $offset, 2); # don't care for errors
1395                 sysread($fh, $rl, 41) == 41 or return (undef, undef);
1396                 chomp $rl;
1397         }
1398         if ($c && $c ne $rl) {
1399                 die "$db_path and ", $self->refname,
1400                     " inconsistent!:\n$c != $rl\n";
1401         }
1402         my $rev = sysseek($fh, 0, 1) or croak $!;
1403         $rev =  ($rev - 41) / 41;
1404         close $fh or croak $!;
1405         ($self->{last_rev}, $self->{last_commit}) = ($rev, $c);
1406         return ($rev, $c);
1409 sub get_fetch_range {
1410         my ($self, $min, $max) = @_;
1411         $max ||= $self->ra->get_latest_revnum;
1412         $min ||= $self->rev_db_max;
1413         (++$min, $max);
1416 sub tmp_config {
1417         my (@args) = @_;
1418         my $old_def_config = "$ENV{GIT_DIR}/svn/config";
1419         my $config = "$ENV{GIT_DIR}/svn/.metadata";
1420         if (-e $old_def_config && ! -e $config) {
1421                 rename $old_def_config, $config or
1422                        die "Failed rename $old_def_config => $config: $!\n";
1423         }
1424         my $old_config = $ENV{GIT_CONFIG};
1425         $ENV{GIT_CONFIG} = $config;
1426         $@ = undef;
1427         my @ret = eval {
1428                 unless (-f $config) {
1429                         mkfile($config);
1430                         open my $fh, '>', $config or
1431                             die "Can't open $config: $!\n";
1432                         print $fh "; This file is used internally by ",
1433                                   "git-svn\n" or die
1434                                   "Couldn't write to $config: $!\n";
1435                         print $fh "; You should not have to edit it\n" or
1436                               die "Couldn't write to $config: $!\n";
1437                         close $fh or die "Couldn't close $config: $!\n";
1438                 }
1439                 command('config', @args);
1440         };
1441         my $err = $@;
1442         if (defined $old_config) {
1443                 $ENV{GIT_CONFIG} = $old_config;
1444         } else {
1445                 delete $ENV{GIT_CONFIG};
1446         }
1447         die $err if $err;
1448         wantarray ? @ret : $ret[0];
1451 sub tmp_index_do {
1452         my ($self, $sub) = @_;
1453         my $old_index = $ENV{GIT_INDEX_FILE};
1454         $ENV{GIT_INDEX_FILE} = $self->{index};
1455         $@ = undef;
1456         my @ret = eval {
1457                 my ($dir, $base) = ($self->{index} =~ m#^(.*?)/?([^/]+)$#);
1458                 mkpath([$dir]) unless -d $dir;
1459                 &$sub;
1460         };
1461         my $err = $@;
1462         if (defined $old_index) {
1463                 $ENV{GIT_INDEX_FILE} = $old_index;
1464         } else {
1465                 delete $ENV{GIT_INDEX_FILE};
1466         }
1467         die $err if $err;
1468         wantarray ? @ret : $ret[0];
1471 sub assert_index_clean {
1472         my ($self, $treeish) = @_;
1474         $self->tmp_index_do(sub {
1475                 command_noisy('read-tree', $treeish) unless -e $self->{index};
1476                 my $x = command_oneline('write-tree');
1477                 my ($y) = (command(qw/cat-file commit/, $treeish) =~
1478                            /^tree ($::sha1)/mo);
1479                 return if $y eq $x;
1481                 warn "Index mismatch: $y != $x\nrereading $treeish\n";
1482                 unlink $self->{index} or die "unlink $self->{index}: $!\n";
1483                 command_noisy('read-tree', $treeish);
1484                 $x = command_oneline('write-tree');
1485                 if ($y ne $x) {
1486                         ::fatal "trees ($treeish) $y != $x\n",
1487                                 "Something is seriously wrong...\n";
1488                 }
1489         });
1492 sub get_commit_parents {
1493         my ($self, $log_entry) = @_;
1494         my (%seen, @ret, @tmp);
1495         # legacy support for 'set-tree'; this is only used by set_tree_cb:
1496         if (my $ip = $self->{inject_parents}) {
1497                 if (my $commit = delete $ip->{$log_entry->{revision}}) {
1498                         push @tmp, $commit;
1499                 }
1500         }
1501         if (my $cur = ::verify_ref($self->refname.'^0')) {
1502                 push @tmp, $cur;
1503         }
1504         push @tmp, $_ foreach (@{$log_entry->{parents}}, @tmp);
1505         while (my $p = shift @tmp) {
1506                 next if $seen{$p};
1507                 $seen{$p} = 1;
1508                 push @ret, $p;
1509                 # MAXPARENT is defined to 16 in commit-tree.c:
1510                 last if @ret >= 16;
1511         }
1512         if (@tmp) {
1513                 die "r$log_entry->{revision}: No room for parents:\n\t",
1514                     join("\n\t", @tmp), "\n";
1515         }
1516         @ret;
1519 sub rewrite_root {
1520         my ($self) = @_;
1521         return $self->{-rewrite_root} if exists $self->{-rewrite_root};
1522         my $k = "svn-remote.$self->{repo_id}.rewriteRoot";
1523         my $rwr = eval { command_oneline(qw/config --get/, $k) };
1524         if ($rwr) {
1525                 $rwr =~ s#/+$##;
1526                 if ($rwr !~ m#^[a-z\+]+://#) {
1527                         die "$rwr is not a valid URL (key: $k)\n";
1528                 }
1529         }
1530         $self->{-rewrite_root} = $rwr;
1533 sub metadata_url {
1534         my ($self) = @_;
1535         ($self->rewrite_root || $self->{url}) .
1536            (length $self->{path} ? '/' . $self->{path} : '');
1539 sub full_url {
1540         my ($self) = @_;
1541         $self->{url} . (length $self->{path} ? '/' . $self->{path} : '');
1544 sub do_git_commit {
1545         my ($self, $log_entry) = @_;
1546         my $lr = $self->last_rev;
1547         if (defined $lr && $lr >= $log_entry->{revision}) {
1548                 die "Last fetched revision of ", $self->refname,
1549                     " was r$lr, but we are about to fetch: ",
1550                     "r$log_entry->{revision}!\n";
1551         }
1552         if (my $c = $self->rev_db_get($log_entry->{revision})) {
1553                 croak "$log_entry->{revision} = $c already exists! ",
1554                       "Why are we refetching it?\n";
1555         }
1556         $ENV{GIT_AUTHOR_NAME} = $ENV{GIT_COMMITTER_NAME} = $log_entry->{name};
1557         $ENV{GIT_AUTHOR_EMAIL} = $ENV{GIT_COMMITTER_EMAIL} =
1558                                                           $log_entry->{email};
1559         $ENV{GIT_AUTHOR_DATE} = $ENV{GIT_COMMITTER_DATE} = $log_entry->{date};
1561         my $tree = $log_entry->{tree};
1562         if (!defined $tree) {
1563                 $tree = $self->tmp_index_do(sub {
1564                                             command_oneline('write-tree') });
1565         }
1566         die "Tree is not a valid sha1: $tree\n" if $tree !~ /^$::sha1$/o;
1568         my @exec = ('git-commit-tree', $tree);
1569         foreach ($self->get_commit_parents($log_entry)) {
1570                 push @exec, '-p', $_;
1571         }
1572         defined(my $pid = open3(my $msg_fh, my $out_fh, '>&STDERR', @exec))
1573                                                                    or croak $!;
1574         print $msg_fh $log_entry->{log} or croak $!;
1575         unless ($self->no_metadata) {
1576                 print $msg_fh "\ngit-svn-id: $log_entry->{metadata}\n"
1577                               or croak $!;
1578         }
1579         $msg_fh->flush == 0 or croak $!;
1580         close $msg_fh or croak $!;
1581         chomp(my $commit = do { local $/; <$out_fh> });
1582         close $out_fh or croak $!;
1583         waitpid $pid, 0;
1584         croak $? if $?;
1585         if ($commit !~ /^$::sha1$/o) {
1586                 die "Failed to commit, invalid sha1: $commit\n";
1587         }
1589         $self->rev_db_set($log_entry->{revision}, $commit, 1);
1591         $self->{last_rev} = $log_entry->{revision};
1592         $self->{last_commit} = $commit;
1593         print "r$log_entry->{revision}";
1594         if (defined $log_entry->{svm_revision}) {
1595                  print " (\@$log_entry->{svm_revision})";
1596                  $self->rev_db_set($log_entry->{svm_revision}, $commit,
1597                                    0, $self->svm_uuid);
1598         }
1599         print " = $commit ($self->{ref_id})\n";
1600         if (defined $_repack && (--$_repack_nr == 0)) {
1601                 $_repack_nr = $_repack;
1602                 # repack doesn't use any arguments with spaces in them, does it?
1603                 print "Running git repack $_repack_flags ...\n";
1604                 command_noisy('repack', split(/\s+/, $_repack_flags));
1605                 print "Done repacking\n";
1606         }
1607         return $commit;
1610 sub match_paths {
1611         my ($self, $paths, $r) = @_;
1612         return 1 if $self->{path} eq '';
1613         if (my $path = $paths->{"/$self->{path}"}) {
1614                 return ($path->{action} eq 'D') ? 0 : 1;
1615         }
1616         $self->{path_regex} ||= qr/^\/\Q$self->{path}\E\//;
1617         if (grep /$self->{path_regex}/, keys %$paths) {
1618                 return 1;
1619         }
1620         my $c = '';
1621         foreach (split m#/#, $self->{path}) {
1622                 $c .= "/$_";
1623                 next unless ($paths->{$c} &&
1624                              ($paths->{$c}->{action} =~ /^[AR]$/));
1625                 if ($self->ra->check_path($self->{path}, $r) ==
1626                     $SVN::Node::dir) {
1627                         return 1;
1628                 }
1629         }
1630         return 0;
1633 sub find_parent_branch {
1634         my ($self, $paths, $rev) = @_;
1635         return undef unless $self->follow_parent;
1636         unless (defined $paths) {
1637                 my $err_handler = $SVN::Error::handler;
1638                 $SVN::Error::handler = \&Git::SVN::Ra::skip_unknown_revs;
1639                 $self->ra->get_log([$self->{path}], $rev, $rev, 0, 1, 1, sub {
1640                                    $paths =
1641                                       Git::SVN::Ra::dup_changed_paths($_[0]) });
1642                 $SVN::Error::handler = $err_handler;
1643         }
1644         return undef unless defined $paths;
1646         # look for a parent from another branch:
1647         my @b_path_components = split m#/#, $self->rel_path;
1648         my @a_path_components;
1649         my $i;
1650         while (@b_path_components) {
1651                 $i = $paths->{'/'.join('/', @b_path_components)};
1652                 last if $i && defined $i->{copyfrom_path};
1653                 unshift(@a_path_components, pop(@b_path_components));
1654         }
1655         return undef unless defined $i && defined $i->{copyfrom_path};
1656         my $branch_from = $i->{copyfrom_path};
1657         if (@a_path_components) {
1658                 print STDERR "branch_from: $branch_from => ";
1659                 $branch_from .= '/'.join('/', @a_path_components);
1660                 print STDERR $branch_from, "\n";
1661         }
1662         my $r = $i->{copyfrom_rev};
1663         my $repos_root = $self->ra->{repos_root};
1664         my $url = $self->ra->{url};
1665         my $new_url = $repos_root . $branch_from;
1666         print STDERR  "Found possible branch point: ",
1667                       "$new_url => ", $self->full_url, ", $r\n";
1668         $branch_from =~ s#^/##;
1669         my $gs = Git::SVN->find_by_url($new_url, $repos_root, $branch_from);
1670         unless ($gs) {
1671                 my $ref_id = $self->{ref_id};
1672                 $ref_id =~ s/\@\d+$//;
1673                 $ref_id .= "\@$r";
1674                 # just grow a tail if we're not unique enough :x
1675                 $ref_id .= '-' while find_ref($ref_id);
1676                 print STDERR "Initializing parent: $ref_id\n";
1677                 $gs = Git::SVN->init($new_url, '', $ref_id, $ref_id, 1);
1678         }
1679         my ($r0, $parent) = $gs->find_rev_before($r, 1);
1680         if (!defined $r0 || !defined $parent) {
1681                 $gs->fetch(0, $r);
1682                 ($r0, $parent) = $gs->last_rev_commit;
1683         }
1684         if (defined $r0 && defined $parent) {
1685                 print STDERR "Found branch parent: ($self->{ref_id}) $parent\n";
1686                 my $ed;
1687                 if ($self->ra->can_do_switch) {
1688                         $self->assert_index_clean($parent);
1689                         print STDERR "Following parent with do_switch\n";
1690                         # do_switch works with svn/trunk >= r22312, but that
1691                         # is not included with SVN 1.4.3 (the latest version
1692                         # at the moment), so we can't rely on it
1693                         $self->{last_commit} = $parent;
1694                         $ed = SVN::Git::Fetcher->new($self);
1695                         $gs->ra->gs_do_switch($r0, $rev, $gs,
1696                                               $self->full_url, $ed)
1697                           or die "SVN connection failed somewhere...\n";
1698                 } else {
1699                         print STDERR "Following parent with do_update\n";
1700                         $ed = SVN::Git::Fetcher->new($self);
1701                         $self->ra->gs_do_update($rev, $rev, $self, $ed)
1702                           or die "SVN connection failed somewhere...\n";
1703                 }
1704                 print STDERR "Successfully followed parent\n";
1705                 return $self->make_log_entry($rev, [$parent], $ed);
1706         }
1707         return undef;
1710 sub do_fetch {
1711         my ($self, $paths, $rev) = @_;
1712         my $ed;
1713         my ($last_rev, @parents);
1714         if (my $lc = $self->last_commit) {
1715                 # we can have a branch that was deleted, then re-added
1716                 # under the same name but copied from another path, in
1717                 # which case we'll have multiple parents (we don't
1718                 # want to break the original ref, nor lose copypath info):
1719                 if (my $log_entry = $self->find_parent_branch($paths, $rev)) {
1720                         push @{$log_entry->{parents}}, $lc;
1721                         return $log_entry;
1722                 }
1723                 $ed = SVN::Git::Fetcher->new($self);
1724                 $last_rev = $self->{last_rev};
1725                 $ed->{c} = $lc;
1726                 @parents = ($lc);
1727         } else {
1728                 $last_rev = $rev;
1729                 if (my $log_entry = $self->find_parent_branch($paths, $rev)) {
1730                         return $log_entry;
1731                 }
1732                 $ed = SVN::Git::Fetcher->new($self);
1733         }
1734         unless ($self->ra->gs_do_update($last_rev, $rev, $self, $ed)) {
1735                 die "SVN connection failed somewhere...\n";
1736         }
1737         $self->make_log_entry($rev, \@parents, $ed);
1740 sub get_untracked {
1741         my ($self, $ed) = @_;
1742         my @out;
1743         my $h = $ed->{empty};
1744         foreach (sort keys %$h) {
1745                 my $act = $h->{$_} ? '+empty_dir' : '-empty_dir';
1746                 push @out, "  $act: " . uri_encode($_);
1747                 warn "W: $act: $_\n";
1748         }
1749         foreach my $t (qw/dir_prop file_prop/) {
1750                 $h = $ed->{$t} or next;
1751                 foreach my $path (sort keys %$h) {
1752                         my $ppath = $path eq '' ? '.' : $path;
1753                         foreach my $prop (sort keys %{$h->{$path}}) {
1754                                 next if $SKIP_PROP{$prop};
1755                                 my $v = $h->{$path}->{$prop};
1756                                 my $t_ppath_prop = "$t: " .
1757                                                     uri_encode($ppath) . ' ' .
1758                                                     uri_encode($prop);
1759                                 if (defined $v) {
1760                                         push @out, "  +$t_ppath_prop " .
1761                                                    uri_encode($v);
1762                                 } else {
1763                                         push @out, "  -$t_ppath_prop";
1764                                 }
1765                         }
1766                 }
1767         }
1768         foreach my $t (qw/absent_file absent_directory/) {
1769                 $h = $ed->{$t} or next;
1770                 foreach my $parent (sort keys %$h) {
1771                         foreach my $path (sort @{$h->{$parent}}) {
1772                                 push @out, "  $t: " .
1773                                            uri_encode("$parent/$path");
1774                                 warn "W: $t: $parent/$path ",
1775                                      "Insufficient permissions?\n";
1776                         }
1777                 }
1778         }
1779         \@out;
1782 sub parse_svn_date {
1783         my $date = shift || return '+0000 1970-01-01 00:00:00';
1784         my ($Y,$m,$d,$H,$M,$S) = ($date =~ /^(\d{4})\-(\d\d)\-(\d\d)T
1785                                             (\d\d)\:(\d\d)\:(\d\d).\d+Z$/x) or
1786                                          croak "Unable to parse date: $date\n";
1787         "+0000 $Y-$m-$d $H:$M:$S";
1790 sub check_author {
1791         my ($author) = @_;
1792         if (!defined $author || length $author == 0) {
1793                 $author = '(no author)';
1794         }
1795         if (defined $::_authors && ! defined $::users{$author}) {
1796                 die "Author: $author not defined in $::_authors file\n";
1797         }
1798         $author;
1801 sub make_log_entry {
1802         my ($self, $rev, $parents, $ed) = @_;
1803         my $untracked = $self->get_untracked($ed);
1805         open my $un, '>>', "$self->{dir}/unhandled.log" or croak $!;
1806         print $un "r$rev\n" or croak $!;
1807         print $un $_, "\n" foreach @$untracked;
1808         my %log_entry = ( parents => $parents || [], revision => $rev,
1809                           log => '');
1811         my $headrev;
1812         my $logged = delete $self->{logged_rev_props};
1813         if (!$logged || $self->{-want_revprops}) {
1814                 my $rp = $self->ra->rev_proplist($rev);
1815                 foreach (sort keys %$rp) {
1816                         my $v = $rp->{$_};
1817                         if (/^svn:(author|date|log)$/) {
1818                                 $log_entry{$1} = $v;
1819                         } elsif ($_ eq 'svm:headrev') {
1820                                 $headrev = $v;
1821                         } else {
1822                                 print $un "  rev_prop: ", uri_encode($_), ' ',
1823                                           uri_encode($v), "\n";
1824                         }
1825                 }
1826         } else {
1827                 map { $log_entry{$_} = $logged->{$_} } keys %$logged;
1828         }
1829         close $un or croak $!;
1831         $log_entry{date} = parse_svn_date($log_entry{date});
1832         $log_entry{log} .= "\n";
1833         my $author = $log_entry{author} = check_author($log_entry{author});
1834         my ($name, $email) = defined $::users{$author} ? @{$::users{$author}}
1835                                                        : ($author, undef);
1836         if (defined $headrev && $self->use_svm_props) {
1837                 if ($self->rewrite_root) {
1838                         die "Can't have both 'useSvmProps' and 'rewriteRoot' ",
1839                             "options set!\n";
1840                 }
1841                 my ($uuid, $r) = $headrev =~ m{^([a-f\d\-]{30,}):(\d+)$};
1842                 # we don't want "SVM: initializing mirror for junk" ...
1843                 return undef if $r == 0;
1844                 my $svm = $self->svm;
1845                 if ($uuid ne $svm->{uuid}) {
1846                         die "UUID mismatch on SVM path:\n",
1847                             "expected: $svm->{uuid}\n",
1848                             "     got: $uuid\n";
1849                 }
1850                 my $full_url = $self->full_url;
1851                 $full_url =~ s#^\Q$svm->{replace}\E(/|$)#$svm->{source}$1# or
1852                              die "Failed to replace '$svm->{replace}' with ",
1853                                  "'$svm->{source}' in $full_url\n";
1854                 # throw away username for storing in records
1855                 remove_username($full_url);
1856                 $log_entry{metadata} = "$full_url\@$r $uuid";
1857                 $log_entry{svm_revision} = $r;
1858                 $email ||= "$author\@$uuid"
1859         } elsif ($self->use_svnsync_props) {
1860                 my $full_url = $self->svnsync->{url};
1861                 $full_url .= "/$self->{path}" if length $self->{path};
1862                 my $uuid = $self->svnsync->{uuid};
1863                 $log_entry{metadata} = "$full_url\@$rev $uuid";
1864                 $email ||= "$author\@$uuid"
1865         } else {
1866                 $log_entry{metadata} = $self->metadata_url. "\@$rev " .
1867                                        $self->ra->get_uuid;
1868                 $email ||= "$author\@" . $self->ra->get_uuid;
1869         }
1870         $log_entry{name} = $name;
1871         $log_entry{email} = $email;
1872         \%log_entry;
1875 sub fetch {
1876         my ($self, $min_rev, $max_rev, @parents) = @_;
1877         my ($last_rev, $last_commit) = $self->last_rev_commit;
1878         my ($base, $head) = $self->get_fetch_range($min_rev, $max_rev);
1879         $self->ra->gs_fetch_loop_common($base, $head, [$self]);
1882 sub set_tree_cb {
1883         my ($self, $log_entry, $tree, $rev, $date, $author) = @_;
1884         $self->{inject_parents} = { $rev => $tree };
1885         $self->fetch(undef, undef);
1888 sub set_tree {
1889         my ($self, $tree) = (shift, shift);
1890         my $log_entry = ::get_commit_entry($tree);
1891         unless ($self->{last_rev}) {
1892                 fatal("Must have an existing revision to commit\n");
1893         }
1894         my %ed_opts = ( r => $self->{last_rev},
1895                         log => $log_entry->{log},
1896                         ra => $self->ra,
1897                         tree_a => $self->{last_commit},
1898                         tree_b => $tree,
1899                         editor_cb => sub {
1900                                $self->set_tree_cb($log_entry, $tree, @_) },
1901                         svn_path => $self->{path} );
1902         if (!SVN::Git::Editor->new(\%ed_opts)->apply_diff) {
1903                 print "No changes\nr$self->{last_rev} = $tree\n";
1904         }
1907 sub rebuild {
1908         my ($self) = @_;
1909         my $db_path = $self->db_path;
1910         return if (-e $db_path && ! -z $db_path);
1911         return unless ::verify_ref($self->refname.'^0');
1912         if (-f $self->{db_root}) {
1913                 rename $self->{db_root}, $db_path or die
1914                      "rename $self->{db_root} => $db_path failed: $!\n";
1915                 my ($dir, $base) = ($db_path =~ m#^(.*?)/?([^/]+)$#);
1916                 symlink $base, $self->{db_root} or die
1917                      "symlink $base => $self->{db_root} failed: $!\n";
1918                 return;
1919         }
1920         print "Rebuilding $db_path ...\n";
1921         my ($rev_list, $ctx) = command_output_pipe("rev-list", $self->refname);
1922         my $latest;
1923         my $full_url = $self->full_url;
1924         remove_username($full_url);
1925         my $svn_uuid;
1926         while (<$rev_list>) {
1927                 chomp;
1928                 my $c = $_;
1929                 die "Non-SHA1: $c\n" unless $c =~ /^$::sha1$/o;
1930                 my ($url, $rev, $uuid) = ::cmt_metadata($c);
1931                 remove_username($url);
1933                 # ignore merges (from set-tree)
1934                 next if (!defined $rev || !$uuid);
1936                 # if we merged or otherwise started elsewhere, this is
1937                 # how we break out of it
1938                 if ((defined $svn_uuid && ($uuid ne $svn_uuid)) ||
1939                     ($full_url && $url && ($url ne $full_url))) {
1940                         next;
1941                 }
1942                 $latest ||= $rev;
1943                 $svn_uuid ||= $uuid;
1945                 $self->rev_db_set($rev, $c);
1946                 print "r$rev = $c\n";
1947         }
1948         command_close_pipe($rev_list, $ctx);
1949         print "Done rebuilding $db_path\n";
1952 # rev_db:
1953 # Tie::File seems to be prone to offset errors if revisions get sparse,
1954 # it's not that fast, either.  Tie::File is also not in Perl 5.6.  So
1955 # one of my favorite modules is out :<  Next up would be one of the DBM
1956 # modules, but I'm not sure which is most portable...  So I'll just
1957 # go with something that's plain-text, but still capable of
1958 # being randomly accessed.  So here's my ultra-simple fixed-width
1959 # database.  All records are 40 characters + "\n", so it's easy to seek
1960 # to a revision: (41 * rev) is the byte offset.
1961 # A record of 40 0s denotes an empty revision.
1962 # And yes, it's still pretty fast (faster than Tie::File).
1963 # These files are disposable unless noMetadata or useSvmProps is set
1965 sub _rev_db_set {
1966         my ($fh, $rev, $commit) = @_;
1967         my $offset = $rev * 41;
1968         # assume that append is the common case:
1969         seek $fh, 0, 2 or croak $!;
1970         my $pos = tell $fh;
1971         if ($pos < $offset) {
1972                 for (1 .. (($offset - $pos) / 41)) {
1973                         print $fh (('0' x 40),"\n") or croak $!;
1974                 }
1975         }
1976         seek $fh, $offset, 0 or croak $!;
1977         print $fh $commit,"\n" or croak $!;
1980 sub mkfile {
1981         my ($path) = @_;
1982         unless (-e $path) {
1983                 my ($dir, $base) = ($path =~ m#^(.*?)/?([^/]+)$#);
1984                 mkpath([$dir]) unless -d $dir;
1985                 open my $fh, '>>', $path or die "Couldn't create $path: $!\n";
1986                 close $fh or die "Couldn't close (create) $path: $!\n";
1987         }
1990 sub rev_db_set {
1991         my ($self, $rev, $commit, $update_ref, $uuid) = @_;
1992         length $commit == 40 or die "arg3 must be a full SHA1 hexsum\n";
1993         my $db = $self->db_path($uuid);
1994         my $db_lock = "$db.lock";
1995         my $sig;
1996         if ($update_ref) {
1997                 $SIG{INT} = $SIG{HUP} = $SIG{TERM} = $SIG{ALRM} = $SIG{PIPE} =
1998                             $SIG{USR1} = $SIG{USR2} = sub { $sig = $_[0] };
1999         }
2000         mkfile($db);
2002         $LOCKFILES{$db_lock} = 1;
2003         my $sync;
2004         # both of these options make our .rev_db file very, very important
2005         # and we can't afford to lose it because rebuild() won't work
2006         if ($self->use_svm_props || $self->no_metadata) {
2007                 $sync = 1;
2008                 copy($db, $db_lock) or die "rev_db_set(@_): ",
2009                                            "Failed to copy: ",
2010                                            "$db => $db_lock ($!)\n";
2011         } else {
2012                 rename $db, $db_lock or die "rev_db_set(@_): ",
2013                                             "Failed to rename: ",
2014                                             "$db => $db_lock ($!)\n";
2015         }
2016         open my $fh, '+<', $db_lock or die "Couldn't open $db_lock: $!\n";
2017         _rev_db_set($fh, $rev, $commit);
2018         if ($sync) {
2019                 $fh->flush or die "Couldn't flush $db_lock: $!\n";
2020                 $fh->sync or die "Couldn't sync $db_lock: $!\n";
2021         }
2022         close $fh or croak $!;
2023         if ($update_ref) {
2024                 $_head = $self;
2025                 command_noisy('update-ref', '-m', "r$rev",
2026                               $self->refname, $commit);
2027         }
2028         rename $db_lock, $db or die "rev_db_set(@_): ", "Failed to rename: ",
2029                                     "$db_lock => $db ($!)\n";
2030         delete $LOCKFILES{$db_lock};
2031         if ($update_ref) {
2032                 $SIG{INT} = $SIG{HUP} = $SIG{TERM} = $SIG{ALRM} = $SIG{PIPE} =
2033                             $SIG{USR1} = $SIG{USR2} = 'DEFAULT';
2034                 kill $sig, $$ if defined $sig;
2035         }
2038 sub rev_db_max {
2039         my ($self) = @_;
2040         $self->rebuild;
2041         my $db_path = $self->db_path;
2042         my @stat = stat $db_path or return 0;
2043         ($stat[7] % 41) == 0 or die "$db_path inconsistent size: $stat[7]\n";
2044         my $max = $stat[7] / 41;
2045         (($max > 0) ? $max - 1 : 0);
2048 sub rev_db_get {
2049         my ($self, $rev, $uuid) = @_;
2050         my $ret;
2051         my $offset = $rev * 41;
2052         my $db_path = $self->db_path($uuid);
2053         return undef unless -e $db_path;
2054         open my $fh, '<', $db_path or croak $!;
2055         if (sysseek($fh, $offset, 0) == $offset) {
2056                 my $read = sysread($fh, $ret, 40);
2057                 $ret = undef if ($read != 40 || $ret eq ('0'x40));
2058         }
2059         close $fh or croak $!;
2060         $ret;
2063 sub find_rev_before {
2064         my ($self, $rev, $eq_ok) = @_;
2065         --$rev unless $eq_ok;
2066         while ($rev > 0) {
2067                 if (my $c = $self->rev_db_get($rev)) {
2068                         return ($rev, $c);
2069                 }
2070                 --$rev;
2071         }
2072         return (undef, undef);
2075 sub _new {
2076         my ($class, $repo_id, $ref_id, $path) = @_;
2077         unless (defined $repo_id && length $repo_id) {
2078                 $repo_id = $Git::SVN::default_repo_id;
2079         }
2080         unless (defined $ref_id && length $ref_id) {
2081                 $_[2] = $ref_id = $Git::SVN::default_ref_id;
2082         }
2083         $_[1] = $repo_id = sanitize_remote_name($repo_id);
2084         my $dir = "$ENV{GIT_DIR}/svn/$ref_id";
2085         $_[3] = $path = '' unless (defined $path);
2086         mkpath(["$ENV{GIT_DIR}/svn"]);
2087         bless {
2088                 ref_id => $ref_id, dir => $dir, index => "$dir/index",
2089                 path => $path, config => "$ENV{GIT_DIR}/svn/config",
2090                 db_root => "$dir/.rev_db", repo_id => $repo_id }, $class;
2093 sub db_path {
2094         my ($self, $uuid) = @_;
2095         $uuid ||= $self->ra_uuid;
2096         "$self->{db_root}.$uuid";
2099 sub uri_encode {
2100         my ($f) = @_;
2101         $f =~ s#([^a-zA-Z0-9\*!\:_\./\-])#uc sprintf("%%%02x",ord($1))#eg;
2102         $f
2105 sub remove_username {
2106         $_[0] =~ s{^([^:]*://)[^@]+@}{$1};
2109 package Git::SVN::Prompt;
2110 use strict;
2111 use warnings;
2112 require SVN::Core;
2113 use vars qw/$_no_auth_cache $_username/;
2115 sub simple {
2116         my ($cred, $realm, $default_username, $may_save, $pool) = @_;
2117         $may_save = undef if $_no_auth_cache;
2118         $default_username = $_username if defined $_username;
2119         if (defined $default_username && length $default_username) {
2120                 if (defined $realm && length $realm) {
2121                         print STDERR "Authentication realm: $realm\n";
2122                         STDERR->flush;
2123                 }
2124                 $cred->username($default_username);
2125         } else {
2126                 username($cred, $realm, $may_save, $pool);
2127         }
2128         $cred->password(_read_password("Password for '" .
2129                                        $cred->username . "': ", $realm));
2130         $cred->may_save($may_save);
2131         $SVN::_Core::SVN_NO_ERROR;
2134 sub ssl_server_trust {
2135         my ($cred, $realm, $failures, $cert_info, $may_save, $pool) = @_;
2136         $may_save = undef if $_no_auth_cache;
2137         print STDERR "Error validating server certificate for '$realm':\n";
2138         if ($failures & $SVN::Auth::SSL::UNKNOWNCA) {
2139                 print STDERR " - The certificate is not issued by a trusted ",
2140                       "authority. Use the\n",
2141                       "   fingerprint to validate the certificate manually!\n";
2142         }
2143         if ($failures & $SVN::Auth::SSL::CNMISMATCH) {
2144                 print STDERR " - The certificate hostname does not match.\n";
2145         }
2146         if ($failures & $SVN::Auth::SSL::NOTYETVALID) {
2147                 print STDERR " - The certificate is not yet valid.\n";
2148         }
2149         if ($failures & $SVN::Auth::SSL::EXPIRED) {
2150                 print STDERR " - The certificate has expired.\n";
2151         }
2152         if ($failures & $SVN::Auth::SSL::OTHER) {
2153                 print STDERR " - The certificate has an unknown error.\n";
2154         }
2155         printf STDERR
2156                 "Certificate information:\n".
2157                 " - Hostname: %s\n".
2158                 " - Valid: from %s until %s\n".
2159                 " - Issuer: %s\n".
2160                 " - Fingerprint: %s\n",
2161                 map $cert_info->$_, qw(hostname valid_from valid_until
2162                                        issuer_dname fingerprint);
2163         my $choice;
2164 prompt:
2165         print STDERR $may_save ?
2166               "(R)eject, accept (t)emporarily or accept (p)ermanently? " :
2167               "(R)eject or accept (t)emporarily? ";
2168         STDERR->flush;
2169         $choice = lc(substr(<STDIN> || 'R', 0, 1));
2170         if ($choice =~ /^t$/i) {
2171                 $cred->may_save(undef);
2172         } elsif ($choice =~ /^r$/i) {
2173                 return -1;
2174         } elsif ($may_save && $choice =~ /^p$/i) {
2175                 $cred->may_save($may_save);
2176         } else {
2177                 goto prompt;
2178         }
2179         $cred->accepted_failures($failures);
2180         $SVN::_Core::SVN_NO_ERROR;
2183 sub ssl_client_cert {
2184         my ($cred, $realm, $may_save, $pool) = @_;
2185         $may_save = undef if $_no_auth_cache;
2186         print STDERR "Client certificate filename: ";
2187         STDERR->flush;
2188         chomp(my $filename = <STDIN>);
2189         $cred->cert_file($filename);
2190         $cred->may_save($may_save);
2191         $SVN::_Core::SVN_NO_ERROR;
2194 sub ssl_client_cert_pw {
2195         my ($cred, $realm, $may_save, $pool) = @_;
2196         $may_save = undef if $_no_auth_cache;
2197         $cred->password(_read_password("Password: ", $realm));
2198         $cred->may_save($may_save);
2199         $SVN::_Core::SVN_NO_ERROR;
2202 sub username {
2203         my ($cred, $realm, $may_save, $pool) = @_;
2204         $may_save = undef if $_no_auth_cache;
2205         if (defined $realm && length $realm) {
2206                 print STDERR "Authentication realm: $realm\n";
2207         }
2208         my $username;
2209         if (defined $_username) {
2210                 $username = $_username;
2211         } else {
2212                 print STDERR "Username: ";
2213                 STDERR->flush;
2214                 chomp($username = <STDIN>);
2215         }
2216         $cred->username($username);
2217         $cred->may_save($may_save);
2218         $SVN::_Core::SVN_NO_ERROR;
2221 sub _read_password {
2222         my ($prompt, $realm) = @_;
2223         print STDERR $prompt;
2224         STDERR->flush;
2225         require Term::ReadKey;
2226         Term::ReadKey::ReadMode('noecho');
2227         my $password = '';
2228         while (defined(my $key = Term::ReadKey::ReadKey(0))) {
2229                 last if $key =~ /[\012\015]/; # \n\r
2230                 $password .= $key;
2231         }
2232         Term::ReadKey::ReadMode('restore');
2233         print STDERR "\n";
2234         STDERR->flush;
2235         $password;
2238 package main;
2241         my $kill_stupid_warnings = $SVN::Node::none.$SVN::Node::file.
2242                                 $SVN::Node::dir.$SVN::Node::unknown.
2243                                 $SVN::Node::none.$SVN::Node::file.
2244                                 $SVN::Node::dir.$SVN::Node::unknown.
2245                                 $SVN::Auth::SSL::CNMISMATCH.
2246                                 $SVN::Auth::SSL::NOTYETVALID.
2247                                 $SVN::Auth::SSL::EXPIRED.
2248                                 $SVN::Auth::SSL::UNKNOWNCA.
2249                                 $SVN::Auth::SSL::OTHER;
2252 package SVN::Git::Fetcher;
2253 use vars qw/@ISA/;
2254 use strict;
2255 use warnings;
2256 use Carp qw/croak/;
2257 use IO::File qw//;
2258 use Digest::MD5;
2260 # file baton members: path, mode_a, mode_b, pool, fh, blob, base
2261 sub new {
2262         my ($class, $git_svn) = @_;
2263         my $self = SVN::Delta::Editor->new;
2264         bless $self, $class;
2265         $self->{c} = $git_svn->{last_commit} if exists $git_svn->{last_commit};
2266         $self->{empty} = {};
2267         $self->{dir_prop} = {};
2268         $self->{file_prop} = {};
2269         $self->{absent_dir} = {};
2270         $self->{absent_file} = {};
2271         $self->{gii} = $git_svn->tmp_index_do(sub { Git::IndexInfo->new });
2272         $self;
2275 sub set_path_strip {
2276         my ($self, $path) = @_;
2277         $self->{path_strip} = qr/^\Q$path\E(\/|$)/ if length $path;
2280 sub open_root {
2281         { path => '' };
2284 sub open_directory {
2285         my ($self, $path, $pb, $rev) = @_;
2286         { path => $path };
2289 sub git_path {
2290         my ($self, $path) = @_;
2291         if ($self->{path_strip}) {
2292                 $path =~ s!$self->{path_strip}!! or
2293                   die "Failed to strip path '$path' ($self->{path_strip})\n";
2294         }
2295         $path;
2298 sub delete_entry {
2299         my ($self, $path, $rev, $pb) = @_;
2301         my $gpath = $self->git_path($path);
2302         return undef if ($gpath eq '');
2304         # remove entire directories.
2305         if (command('ls-tree', $self->{c}, '--', $gpath) =~ /^040000 tree/) {
2306                 my ($ls, $ctx) = command_output_pipe(qw/ls-tree
2307                                                      -r --name-only -z/,
2308                                                      $self->{c}, '--', $gpath);
2309                 local $/ = "\0";
2310                 while (<$ls>) {
2311                         chomp;
2312                         $self->{gii}->remove($_);
2313                         print "\tD\t$_\n" unless $::_q;
2314                 }
2315                 print "\tD\t$gpath/\n" unless $::_q;
2316                 command_close_pipe($ls, $ctx);
2317                 $self->{empty}->{$path} = 0
2318         } else {
2319                 $self->{gii}->remove($gpath);
2320                 print "\tD\t$gpath\n" unless $::_q;
2321         }
2322         undef;
2325 sub open_file {
2326         my ($self, $path, $pb, $rev) = @_;
2327         my $gpath = $self->git_path($path);
2328         my ($mode, $blob) = (command('ls-tree', $self->{c}, '--', $gpath)
2329                              =~ /^(\d{6}) blob ([a-f\d]{40})\t/);
2330         unless (defined $mode && defined $blob) {
2331                 die "$path was not found in commit $self->{c} (r$rev)\n";
2332         }
2333         { path => $path, mode_a => $mode, mode_b => $mode, blob => $blob,
2334           pool => SVN::Pool->new, action => 'M' };
2337 sub add_file {
2338         my ($self, $path, $pb, $cp_path, $cp_rev) = @_;
2339         my ($dir, $file) = ($path =~ m#^(.*?)/?([^/]+)$#);
2340         delete $self->{empty}->{$dir};
2341         { path => $path, mode_a => 100644, mode_b => 100644,
2342           pool => SVN::Pool->new, action => 'A' };
2345 sub add_directory {
2346         my ($self, $path, $cp_path, $cp_rev) = @_;
2347         my ($dir, $file) = ($path =~ m#^(.*?)/?([^/]+)$#);
2348         delete $self->{empty}->{$dir};
2349         $self->{empty}->{$path} = 1;
2350         { path => $path };
2353 sub change_dir_prop {
2354         my ($self, $db, $prop, $value) = @_;
2355         $self->{dir_prop}->{$db->{path}} ||= {};
2356         $self->{dir_prop}->{$db->{path}}->{$prop} = $value;
2357         undef;
2360 sub absent_directory {
2361         my ($self, $path, $pb) = @_;
2362         $self->{absent_dir}->{$pb->{path}} ||= [];
2363         push @{$self->{absent_dir}->{$pb->{path}}}, $path;
2364         undef;
2367 sub absent_file {
2368         my ($self, $path, $pb) = @_;
2369         $self->{absent_file}->{$pb->{path}} ||= [];
2370         push @{$self->{absent_file}->{$pb->{path}}}, $path;
2371         undef;
2374 sub change_file_prop {
2375         my ($self, $fb, $prop, $value) = @_;
2376         if ($prop eq 'svn:executable') {
2377                 if ($fb->{mode_b} != 120000) {
2378                         $fb->{mode_b} = defined $value ? 100755 : 100644;
2379                 }
2380         } elsif ($prop eq 'svn:special') {
2381                 $fb->{mode_b} = defined $value ? 120000 : 100644;
2382         } else {
2383                 $self->{file_prop}->{$fb->{path}} ||= {};
2384                 $self->{file_prop}->{$fb->{path}}->{$prop} = $value;
2385         }
2386         undef;
2389 sub apply_textdelta {
2390         my ($self, $fb, $exp) = @_;
2391         my $fh = IO::File->new_tmpfile;
2392         $fh->autoflush(1);
2393         # $fh gets auto-closed() by SVN::TxDelta::apply(),
2394         # (but $base does not,) so dup() it for reading in close_file
2395         open my $dup, '<&', $fh or croak $!;
2396         my $base = IO::File->new_tmpfile;
2397         $base->autoflush(1);
2398         if ($fb->{blob}) {
2399                 defined (my $pid = fork) or croak $!;
2400                 if (!$pid) {
2401                         open STDOUT, '>&', $base or croak $!;
2402                         print STDOUT 'link ' if ($fb->{mode_a} == 120000);
2403                         exec qw/git-cat-file blob/, $fb->{blob} or croak $!;
2404                 }
2405                 waitpid $pid, 0;
2406                 croak $? if $?;
2408                 if (defined $exp) {
2409                         seek $base, 0, 0 or croak $!;
2410                         my $md5 = Digest::MD5->new;
2411                         $md5->addfile($base);
2412                         my $got = $md5->hexdigest;
2413                         die "Checksum mismatch: $fb->{path} $fb->{blob}\n",
2414                             "expected: $exp\n",
2415                             "     got: $got\n" if ($got ne $exp);
2416                 }
2417         }
2418         seek $base, 0, 0 or croak $!;
2419         $fb->{fh} = $dup;
2420         $fb->{base} = $base;
2421         [ SVN::TxDelta::apply($base, $fh, undef, $fb->{path}, $fb->{pool}) ];
2424 sub close_file {
2425         my ($self, $fb, $exp) = @_;
2426         my $hash;
2427         my $path = $self->git_path($fb->{path});
2428         if (my $fh = $fb->{fh}) {
2429                 seek($fh, 0, 0) or croak $!;
2430                 my $md5 = Digest::MD5->new;
2431                 $md5->addfile($fh);
2432                 my $got = $md5->hexdigest;
2433                 die "Checksum mismatch: $path\n",
2434                     "expected: $exp\n    got: $got\n" if ($got ne $exp);
2435                 seek($fh, 0, 0) or croak $!;
2436                 if ($fb->{mode_b} == 120000) {
2437                         read($fh, my $buf, 5) == 5 or croak $!;
2438                         $buf eq 'link ' or die "$path has mode 120000",
2439                                                "but is not a link\n";
2440                 }
2441                 defined(my $pid = open my $out,'-|') or die "Can't fork: $!\n";
2442                 if (!$pid) {
2443                         open STDIN, '<&', $fh or croak $!;
2444                         exec qw/git-hash-object -w --stdin/ or croak $!;
2445                 }
2446                 chomp($hash = do { local $/; <$out> });
2447                 close $out or croak $!;
2448                 close $fh or croak $!;
2449                 $hash =~ /^[a-f\d]{40}$/ or die "not a sha1: $hash\n";
2450                 close $fb->{base} or croak $!;
2451         } else {
2452                 $hash = $fb->{blob} or die "no blob information\n";
2453         }
2454         $fb->{pool}->clear;
2455         $self->{gii}->update($fb->{mode_b}, $hash, $path) or croak $!;
2456         print "\t$fb->{action}\t$path\n" if $fb->{action} && ! $::_q;
2457         undef;
2460 sub abort_edit {
2461         my $self = shift;
2462         $self->{nr} = $self->{gii}->{nr};
2463         delete $self->{gii};
2464         $self->SUPER::abort_edit(@_);
2467 sub close_edit {
2468         my $self = shift;
2469         $self->{git_commit_ok} = 1;
2470         $self->{nr} = $self->{gii}->{nr};
2471         delete $self->{gii};
2472         $self->SUPER::close_edit(@_);
2475 package SVN::Git::Editor;
2476 use vars qw/@ISA $_rmdir $_cp_similarity $_find_copies_harder $_rename_limit/;
2477 use strict;
2478 use warnings;
2479 use Carp qw/croak/;
2480 use IO::File;
2481 use Digest::MD5;
2483 sub new {
2484         my ($class, $opts) = @_;
2485         foreach (qw/svn_path r ra tree_a tree_b log editor_cb/) {
2486                 die "$_ required!\n" unless (defined $opts->{$_});
2487         }
2489         my $pool = SVN::Pool->new;
2490         my $mods = generate_diff($opts->{tree_a}, $opts->{tree_b});
2491         my $types = check_diff_paths($opts->{ra}, $opts->{svn_path},
2492                                      $opts->{r}, $mods);
2494         # $opts->{ra} functions should not be used after this:
2495         my @ce  = $opts->{ra}->get_commit_editor($opts->{log},
2496                                                 $opts->{editor_cb}, $pool);
2497         my $self = SVN::Delta::Editor->new(@ce, $pool);
2498         bless $self, $class;
2499         foreach (qw/svn_path r tree_a tree_b/) {
2500                 $self->{$_} = $opts->{$_};
2501         }
2502         $self->{url} = $opts->{ra}->{url};
2503         $self->{mods} = $mods;
2504         $self->{types} = $types;
2505         $self->{pool} = $pool;
2506         $self->{bat} = { '' => $self->open_root($self->{r}, $self->{pool}) };
2507         $self->{rm} = { };
2508         $self->{path_prefix} = length $self->{svn_path} ?
2509                                "$self->{svn_path}/" : '';
2510         return $self;
2513 sub generate_diff {
2514         my ($tree_a, $tree_b) = @_;
2515         my @diff_tree = qw(diff-tree -z -r);
2516         if ($_cp_similarity) {
2517                 push @diff_tree, "-C$_cp_similarity";
2518         } else {
2519                 push @diff_tree, '-C';
2520         }
2521         push @diff_tree, '--find-copies-harder' if $_find_copies_harder;
2522         push @diff_tree, "-l$_rename_limit" if defined $_rename_limit;
2523         push @diff_tree, $tree_a, $tree_b;
2524         my ($diff_fh, $ctx) = command_output_pipe(@diff_tree);
2525         local $/ = "\0";
2526         my $state = 'meta';
2527         my @mods;
2528         while (<$diff_fh>) {
2529                 chomp $_; # this gets rid of the trailing "\0"
2530                 if ($state eq 'meta' && /^:(\d{6})\s(\d{6})\s
2531                                         $::sha1\s($::sha1)\s
2532                                         ([MTCRAD])\d*$/xo) {
2533                         push @mods, {   mode_a => $1, mode_b => $2,
2534                                         sha1_b => $3, chg => $4 };
2535                         if ($4 =~ /^(?:C|R)$/) {
2536                                 $state = 'file_a';
2537                         } else {
2538                                 $state = 'file_b';
2539                         }
2540                 } elsif ($state eq 'file_a') {
2541                         my $x = $mods[$#mods] or croak "Empty array\n";
2542                         if ($x->{chg} !~ /^(?:C|R)$/) {
2543                                 croak "Error parsing $_, $x->{chg}\n";
2544                         }
2545                         $x->{file_a} = $_;
2546                         $state = 'file_b';
2547                 } elsif ($state eq 'file_b') {
2548                         my $x = $mods[$#mods] or croak "Empty array\n";
2549                         if (exists $x->{file_a} && $x->{chg} !~ /^(?:C|R)$/) {
2550                                 croak "Error parsing $_, $x->{chg}\n";
2551                         }
2552                         if (!exists $x->{file_a} && $x->{chg} =~ /^(?:C|R)$/) {
2553                                 croak "Error parsing $_, $x->{chg}\n";
2554                         }
2555                         $x->{file_b} = $_;
2556                         $state = 'meta';
2557                 } else {
2558                         croak "Error parsing $_\n";
2559                 }
2560         }
2561         command_close_pipe($diff_fh, $ctx);
2562         \@mods;
2565 sub check_diff_paths {
2566         my ($ra, $pfx, $rev, $mods) = @_;
2567         my %types;
2568         $pfx .= '/' if length $pfx;
2570         sub type_diff_paths {
2571                 my ($ra, $types, $path, $rev) = @_;
2572                 my @p = split m#/+#, $path;
2573                 my $c = shift @p;
2574                 unless (defined $types->{$c}) {
2575                         $types->{$c} = $ra->check_path($c, $rev);
2576                 }
2577                 while (@p) {
2578                         $c .= '/' . shift @p;
2579                         next if defined $types->{$c};
2580                         $types->{$c} = $ra->check_path($c, $rev);
2581                 }
2582         }
2584         foreach my $m (@$mods) {
2585                 foreach my $f (qw/file_a file_b/) {
2586                         next unless defined $m->{$f};
2587                         my ($dir) = ($m->{$f} =~ m#^(.*?)/?(?:[^/]+)$#);
2588                         if (length $pfx.$dir && ! defined $types{$dir}) {
2589                                 type_diff_paths($ra, \%types, $pfx.$dir, $rev);
2590                         }
2591                 }
2592         }
2593         \%types;
2596 sub split_path {
2597         return ($_[0] =~ m#^(.*?)/?([^/]+)$#);
2600 sub repo_path {
2601         my ($self, $path) = @_;
2602         $self->{path_prefix}.(defined $path ? $path : '');
2605 sub url_path {
2606         my ($self, $path) = @_;
2607         $self->{url} . '/' . $self->repo_path($path);
2610 sub rmdirs {
2611         my ($self) = @_;
2612         my $rm = $self->{rm};
2613         delete $rm->{''}; # we never delete the url we're tracking
2614         return unless %$rm;
2616         foreach (keys %$rm) {
2617                 my @d = split m#/#, $_;
2618                 my $c = shift @d;
2619                 $rm->{$c} = 1;
2620                 while (@d) {
2621                         $c .= '/' . shift @d;
2622                         $rm->{$c} = 1;
2623                 }
2624         }
2625         delete $rm->{$self->{svn_path}};
2626         delete $rm->{''}; # we never delete the url we're tracking
2627         return unless %$rm;
2629         my ($fh, $ctx) = command_output_pipe(qw/ls-tree --name-only -r -z/,
2630                                              $self->{tree_b});
2631         local $/ = "\0";
2632         while (<$fh>) {
2633                 chomp;
2634                 my @dn = split m#/#, $_;
2635                 while (pop @dn) {
2636                         delete $rm->{join '/', @dn};
2637                 }
2638                 unless (%$rm) {
2639                         close $fh;
2640                         return;
2641                 }
2642         }
2643         command_close_pipe($fh, $ctx);
2645         my ($r, $p, $bat) = ($self->{r}, $self->{pool}, $self->{bat});
2646         foreach my $d (sort { $b =~ tr#/#/# <=> $a =~ tr#/#/# } keys %$rm) {
2647                 $self->close_directory($bat->{$d}, $p);
2648                 my ($dn) = ($d =~ m#^(.*?)/?(?:[^/]+)$#);
2649                 print "\tD+\t$d/\n" unless $::_q;
2650                 $self->SUPER::delete_entry($d, $r, $bat->{$dn}, $p);
2651                 delete $bat->{$d};
2652         }
2655 sub open_or_add_dir {
2656         my ($self, $full_path, $baton) = @_;
2657         my $t = $self->{types}->{$full_path};
2658         if (!defined $t) {
2659                 die "$full_path not known in r$self->{r} or we have a bug!\n";
2660         }
2661         if ($t == $SVN::Node::none) {
2662                 return $self->add_directory($full_path, $baton,
2663                                                 undef, -1, $self->{pool});
2664         } elsif ($t == $SVN::Node::dir) {
2665                 return $self->open_directory($full_path, $baton,
2666                                                 $self->{r}, $self->{pool});
2667         }
2668         print STDERR "$full_path already exists in repository at ",
2669                 "r$self->{r} and it is not a directory (",
2670                 ($t == $SVN::Node::file ? 'file' : 'unknown'),"/$t)\n";
2671         exit 1;
2674 sub ensure_path {
2675         my ($self, $path) = @_;
2676         my $bat = $self->{bat};
2677         my $repo_path = $self->repo_path($path);
2678         return $bat->{''} unless (length $repo_path);
2679         my @p = split m#/+#, $repo_path;
2680         my $c = shift @p;
2681         $bat->{$c} ||= $self->open_or_add_dir($c, $bat->{''});
2682         while (@p) {
2683                 my $c0 = $c;
2684                 $c .= '/' . shift @p;
2685                 $bat->{$c} ||= $self->open_or_add_dir($c, $bat->{$c0});
2686         }
2687         return $bat->{$c};
2690 sub A {
2691         my ($self, $m) = @_;
2692         my ($dir, $file) = split_path($m->{file_b});
2693         my $pbat = $self->ensure_path($dir);
2694         my $fbat = $self->add_file($self->repo_path($m->{file_b}), $pbat,
2695                                         undef, -1);
2696         print "\tA\t$m->{file_b}\n" unless $::_q;
2697         $self->chg_file($fbat, $m);
2698         $self->close_file($fbat,undef,$self->{pool});
2701 sub C {
2702         my ($self, $m) = @_;
2703         my ($dir, $file) = split_path($m->{file_b});
2704         my $pbat = $self->ensure_path($dir);
2705         my $fbat = $self->add_file($self->repo_path($m->{file_b}), $pbat,
2706                                 $self->url_path($m->{file_a}), $self->{r});
2707         print "\tC\t$m->{file_a} => $m->{file_b}\n" unless $::_q;
2708         $self->chg_file($fbat, $m);
2709         $self->close_file($fbat,undef,$self->{pool});
2712 sub delete_entry {
2713         my ($self, $path, $pbat) = @_;
2714         my $rpath = $self->repo_path($path);
2715         my ($dir, $file) = split_path($rpath);
2716         $self->{rm}->{$dir} = 1;
2717         $self->SUPER::delete_entry($rpath, $self->{r}, $pbat, $self->{pool});
2720 sub R {
2721         my ($self, $m) = @_;
2722         my ($dir, $file) = split_path($m->{file_b});
2723         my $pbat = $self->ensure_path($dir);
2724         my $fbat = $self->add_file($self->repo_path($m->{file_b}), $pbat,
2725                                 $self->url_path($m->{file_a}), $self->{r});
2726         print "\tR\t$m->{file_a} => $m->{file_b}\n" unless $::_q;
2727         $self->chg_file($fbat, $m);
2728         $self->close_file($fbat,undef,$self->{pool});
2730         ($dir, $file) = split_path($m->{file_a});
2731         $pbat = $self->ensure_path($dir);
2732         $self->delete_entry($m->{file_a}, $pbat);
2735 sub M {
2736         my ($self, $m) = @_;
2737         my ($dir, $file) = split_path($m->{file_b});
2738         my $pbat = $self->ensure_path($dir);
2739         my $fbat = $self->open_file($self->repo_path($m->{file_b}),
2740                                 $pbat,$self->{r},$self->{pool});
2741         print "\t$m->{chg}\t$m->{file_b}\n" unless $::_q;
2742         $self->chg_file($fbat, $m);
2743         $self->close_file($fbat,undef,$self->{pool});
2746 sub T { shift->M(@_) }
2748 sub change_file_prop {
2749         my ($self, $fbat, $pname, $pval) = @_;
2750         $self->SUPER::change_file_prop($fbat, $pname, $pval, $self->{pool});
2753 sub chg_file {
2754         my ($self, $fbat, $m) = @_;
2755         if ($m->{mode_b} =~ /755$/ && $m->{mode_a} !~ /755$/) {
2756                 $self->change_file_prop($fbat,'svn:executable','*');
2757         } elsif ($m->{mode_b} !~ /755$/ && $m->{mode_a} =~ /755$/) {
2758                 $self->change_file_prop($fbat,'svn:executable',undef);
2759         }
2760         my $fh = IO::File->new_tmpfile or croak $!;
2761         if ($m->{mode_b} =~ /^120/) {
2762                 print $fh 'link ' or croak $!;
2763                 $self->change_file_prop($fbat,'svn:special','*');
2764         } elsif ($m->{mode_a} =~ /^120/ && $m->{mode_b} !~ /^120/) {
2765                 $self->change_file_prop($fbat,'svn:special',undef);
2766         }
2767         defined(my $pid = fork) or croak $!;
2768         if (!$pid) {
2769                 open STDOUT, '>&', $fh or croak $!;
2770                 exec qw/git-cat-file blob/, $m->{sha1_b} or croak $!;
2771         }
2772         waitpid $pid, 0;
2773         croak $? if $?;
2774         $fh->flush == 0 or croak $!;
2775         seek $fh, 0, 0 or croak $!;
2777         my $md5 = Digest::MD5->new;
2778         $md5->addfile($fh) or croak $!;
2779         seek $fh, 0, 0 or croak $!;
2781         my $exp = $md5->hexdigest;
2782         my $pool = SVN::Pool->new;
2783         my $atd = $self->apply_textdelta($fbat, undef, $pool);
2784         my $got = SVN::TxDelta::send_stream($fh, @$atd, $pool);
2785         die "Checksum mismatch\nexpected: $exp\ngot: $got\n" if ($got ne $exp);
2786         $pool->clear;
2788         close $fh or croak $!;
2791 sub D {
2792         my ($self, $m) = @_;
2793         my ($dir, $file) = split_path($m->{file_b});
2794         my $pbat = $self->ensure_path($dir);
2795         print "\tD\t$m->{file_b}\n" unless $::_q;
2796         $self->delete_entry($m->{file_b}, $pbat);
2799 sub close_edit {
2800         my ($self) = @_;
2801         my ($p,$bat) = ($self->{pool}, $self->{bat});
2802         foreach (sort { $b =~ tr#/#/# <=> $a =~ tr#/#/# } keys %$bat) {
2803                 $self->close_directory($bat->{$_}, $p);
2804         }
2805         $self->SUPER::close_edit($p);
2806         $p->clear;
2809 sub abort_edit {
2810         my ($self) = @_;
2811         $self->SUPER::abort_edit($self->{pool});
2814 sub DESTROY {
2815         my $self = shift;
2816         $self->SUPER::DESTROY(@_);
2817         $self->{pool}->clear;
2820 # this drives the editor
2821 sub apply_diff {
2822         my ($self) = @_;
2823         my $mods = $self->{mods};
2824         my %o = ( D => 1, R => 0, C => -1, A => 3, M => 3, T => 3 );
2825         foreach my $m (sort { $o{$a->{chg}} <=> $o{$b->{chg}} } @$mods) {
2826                 my $f = $m->{chg};
2827                 if (defined $o{$f}) {
2828                         $self->$f($m);
2829                 } else {
2830                         fatal("Invalid change type: $f\n");
2831                 }
2832         }
2833         $self->rmdirs if $_rmdir;
2834         if (@$mods == 0) {
2835                 $self->abort_edit;
2836         } else {
2837                 $self->close_edit;
2838         }
2839         return scalar @$mods;
2842 package Git::SVN::Ra;
2843 use vars qw/@ISA $config_dir $_log_window_size/;
2844 use strict;
2845 use warnings;
2846 my ($can_do_switch, %ignored_err, $RA);
2848 BEGIN {
2849         # enforce temporary pool usage for some simple functions
2850         my $e;
2851         foreach (qw/get_latest_revnum get_uuid get_repos_root/) {
2852                 $e .= "sub $_ {
2853                         my \$self = shift;
2854                         my \$pool = SVN::Pool->new;
2855                         my \@ret = \$self->SUPER::$_(\@_,\$pool);
2856                         \$pool->clear;
2857                         wantarray ? \@ret : \$ret[0]; }\n";
2858         }
2860         # get_dir needs $pool held in cache for dirents to work,
2861         # check_path is cacheable and rev_proplist is close enough
2862         # for our purposes.
2863         foreach (qw/check_path get_dir rev_proplist/) {
2864                 $e .= "my \%${_}_cache; my \$${_}_rev = 0; sub $_ {
2865                         my \$self = shift;
2866                         my \$r = pop;
2867                         my \$k = join(\"\\0\", \@_);
2868                         if (my \$x = \$${_}_cache{\$r}->{\$k}) {
2869                                 return wantarray ? \@\$x : \$x->[0];
2870                         }
2871                         my \$pool = SVN::Pool->new;
2872                         my \@ret = \$self->SUPER::$_(\@_, \$r, \$pool);
2873                         if (\$r != \$${_}_rev) {
2874                                 \%${_}_cache = ( pool => [] );
2875                                 \$${_}_rev = \$r;
2876                         }
2877                         \$${_}_cache{\$r}->{\$k} = \\\@ret;
2878                         push \@{\$${_}_cache{pool}}, \$pool;
2879                         wantarray ? \@ret : \$ret[0]; }\n";
2880         }
2881         $e .= "\n1;";
2882         eval $e or die $@;
2885 sub new {
2886         my ($class, $url) = @_;
2887         $url =~ s!/+$!!;
2888         return $RA if ($RA && $RA->{url} eq $url);
2889         $RA->{pool}->clear if $RA;
2891         SVN::_Core::svn_config_ensure($config_dir, undef);
2892         my ($baton, $callbacks) = SVN::Core::auth_open_helper([
2893             SVN::Client::get_simple_provider(),
2894             SVN::Client::get_ssl_server_trust_file_provider(),
2895             SVN::Client::get_simple_prompt_provider(
2896               \&Git::SVN::Prompt::simple, 2),
2897             SVN::Client::get_ssl_client_cert_prompt_provider(
2898               \&Git::SVN::Prompt::ssl_client_cert, 2),
2899             SVN::Client::get_ssl_client_cert_pw_prompt_provider(
2900               \&Git::SVN::Prompt::ssl_client_cert_pw, 2),
2901             SVN::Client::get_username_provider(),
2902             SVN::Client::get_ssl_server_trust_prompt_provider(
2903               \&Git::SVN::Prompt::ssl_server_trust),
2904             SVN::Client::get_username_prompt_provider(
2905               \&Git::SVN::Prompt::username, 2),
2906           ]);
2907         my $config = SVN::Core::config_get_config($config_dir);
2908         my $self = SVN::Ra->new(url => $url, auth => $baton,
2909                               config => $config,
2910                               pool => SVN::Pool->new,
2911                               auth_provider_callbacks => $callbacks);
2912         $self->{svn_path} = $url;
2913         $self->{repos_root} = $self->get_repos_root;
2914         $self->{svn_path} =~ s#^\Q$self->{repos_root}\E(/|$)##;
2915         $RA = bless $self, $class;
2918 sub DESTROY {
2919         # do not call the real DESTROY since we store ourselves in $RA
2922 sub get_log {
2923         my ($self, @args) = @_;
2924         my $pool = SVN::Pool->new;
2925         splice(@args, 3, 1) if ($SVN::Core::VERSION le '1.2.0');
2926         my $ret = $self->SUPER::get_log(@args, $pool);
2927         $pool->clear;
2928         $ret;
2931 sub get_commit_editor {
2932         my ($self, $log, $cb, $pool) = @_;
2933         my @lock = $SVN::Core::VERSION ge '1.2.0' ? (undef, 0) : ();
2934         $self->SUPER::get_commit_editor($log, $cb, @lock, $pool);
2937 sub gs_do_update {
2938         my ($self, $rev_a, $rev_b, $gs, $editor) = @_;
2939         my $new = ($rev_a == $rev_b);
2940         my $path = $gs->{path};
2942         if ($new && -e $gs->{index}) {
2943                 unlink $gs->{index} or die
2944                   "Couldn't unlink index: $gs->{index}: $!\n";
2945         }
2946         my $pool = SVN::Pool->new;
2947         $editor->set_path_strip($path);
2948         my (@pc) = split m#/#, $path;
2949         my $reporter = $self->do_update($rev_b, (@pc ? shift @pc : ''),
2950                                         1, $editor, $pool);
2951         my @lock = $SVN::Core::VERSION ge '1.2.0' ? (undef) : ();
2953         # Since we can't rely on svn_ra_reparent being available, we'll
2954         # just have to do some magic with set_path to make it so
2955         # we only want a partial path.
2956         my $sp = '';
2957         my $final = join('/', @pc);
2958         while (@pc) {
2959                 $reporter->set_path($sp, $rev_b, 0, @lock, $pool);
2960                 $sp .= '/' if length $sp;
2961                 $sp .= shift @pc;
2962         }
2963         die "BUG: '$sp' != '$final'\n" if ($sp ne $final);
2965         $reporter->set_path($sp, $rev_a, $new, @lock, $pool);
2967         $reporter->finish_report($pool);
2968         $pool->clear;
2969         $editor->{git_commit_ok};
2972 # this requires SVN 1.4.3 or later (do_switch didn't work before 1.4.3, and
2973 # svn_ra_reparent didn't work before 1.4)
2974 sub gs_do_switch {
2975         my ($self, $rev_a, $rev_b, $gs, $url_b, $editor) = @_;
2976         my $path = $gs->{path};
2977         my $pool = SVN::Pool->new;
2979         my $full_url = $self->{url};
2980         my $old_url = $full_url;
2981         $full_url .= "/$path" if length $path;
2982         my ($ra, $reparented);
2983         if ($old_url ne $full_url) {
2984                 if ($old_url !~ m#^svn(\+ssh)?://#) {
2985                         SVN::_Ra::svn_ra_reparent($self->{session}, $full_url,
2986                                                   $pool);
2987                         $self->{url} = $full_url;
2988                         $reparented = 1;
2989                 } else {
2990                         $ra = Git::SVN::Ra->new($full_url);
2991                 }
2992         }
2993         $ra ||= $self;
2994         my $reporter = $ra->do_switch($rev_b, '', 1, $url_b, $editor, $pool);
2995         my @lock = $SVN::Core::VERSION ge '1.2.0' ? (undef) : ();
2996         $reporter->set_path('', $rev_a, 0, @lock, $pool);
2997         $reporter->finish_report($pool);
2999         if ($reparented) {
3000                 SVN::_Ra::svn_ra_reparent($self->{session}, $old_url, $pool);
3001                 $self->{url} = $old_url;
3002         }
3004         $pool->clear;
3005         $editor->{git_commit_ok};
3008 sub gs_fetch_loop_common {
3009         my ($self, $base, $head, $gsv, $globs) = @_;
3010         return if ($base > $head);
3011         my $inc = $_log_window_size;
3012         my ($min, $max) = ($base, $head < $base + $inc ? $head : $base + $inc);
3013         my %common;
3014         my $common_max = scalar @$gsv;
3016         foreach my $gs (@$gsv) {
3017                 my @tmp = split m#/#, $gs->{path};
3018                 my $p = '';
3019                 foreach (@tmp) {
3020                         $p .= length($p) ? "/$_" : $_;
3021                         $common{$p} ||= 0;
3022                         $common{$p}++;
3023                 }
3024         }
3025         $globs ||= [];
3026         $common_max += scalar @$globs;
3027         foreach my $glob (@$globs) {
3028                 my @tmp = split m#/#, $glob->{path}->{left};
3029                 my $p = '';
3030                 foreach (@tmp) {
3031                         $p .= length($p) ? "/$_" : $_;
3032                         $common{$p} ||= 0;
3033                         $common{$p}++;
3034                 }
3035         }
3037         my $longest_path = '';
3038         foreach (sort {length $b <=> length $a} keys %common) {
3039                 if ($common{$_} == $common_max) {
3040                         $longest_path = $_;
3041                         last;
3042                 }
3043         }
3044         while (1) {
3045                 my %revs;
3046                 my $err;
3047                 my $err_handler = $SVN::Error::handler;
3048                 $SVN::Error::handler = sub {
3049                         ($err) = @_;
3050                         skip_unknown_revs($err);
3051                 };
3052                 sub _cb {
3053                         my ($paths, $r, $author, $date, $log) = @_;
3054                         [ dup_changed_paths($paths),
3055                           { author => $author, date => $date, log => $log } ];
3056                 }
3057                 $self->get_log([$longest_path], $min, $max, 0, 1, 1,
3058                                sub { $revs{$_[1]} = _cb(@_) });
3059                 if ($err && $max >= $head) {
3060                         print STDERR "Path '$longest_path' ",
3061                                      "was probably deleted:\n",
3062                                      $err->expanded_message,
3063                                      "\nWill attempt to follow ",
3064                                      "revisions r$min .. r$max ",
3065                                      "committed before the deletion\n";
3066                         my $hi = $max;
3067                         while (--$hi >= $min) {
3068                                 my $ok;
3069                                 $self->get_log([$longest_path], $min, $hi,
3070                                                0, 1, 1, sub {
3071                                                $ok ||= $_[1];
3072                                                $revs{$_[1]} = _cb(@_) });
3073                                 if ($ok) {
3074                                         print STDERR "r$min .. r$ok OK\n";
3075                                         last;
3076                                 }
3077                         }
3078                 }
3079                 $SVN::Error::handler = $err_handler;
3081                 my %exists = map { $_->{path} => $_ } @$gsv;
3082                 foreach my $r (sort {$a <=> $b} keys %revs) {
3083                         my ($paths, $logged) = @{$revs{$r}};
3085                         foreach my $gs ($self->match_globs(\%exists, $paths,
3086                                                            $globs, $r)) {
3087                                 if ($gs->rev_db_max >= $r) {
3088                                         next;
3089                                 }
3090                                 next unless $gs->match_paths($paths, $r);
3091                                 $gs->{logged_rev_props} = $logged;
3092                                 if (my $last_commit = $gs->last_commit) {
3093                                         $gs->assert_index_clean($last_commit);
3094                                 }
3095                                 my $log_entry = $gs->do_fetch($paths, $r);
3096                                 if ($log_entry) {
3097                                         $gs->do_git_commit($log_entry);
3098                                 }
3099                         }
3100                         foreach my $g (@$globs) {
3101                                 my $k = "svn-remote.$g->{remote}." .
3102                                         "$g->{t}-maxRev";
3103                                 Git::SVN::tmp_config($k, $r);
3104                         }
3105                 }
3106                 # pre-fill the .rev_db since it'll eventually get filled in
3107                 # with '0' x40 if something new gets committed
3108                 foreach my $gs (@$gsv) {
3109                         next if defined $gs->rev_db_get($max);
3110                         $gs->rev_db_set($max, 0 x40);
3111                 }
3112                 foreach my $g (@$globs) {
3113                         my $k = "svn-remote.$g->{remote}.$g->{t}-maxRev";
3114                         Git::SVN::tmp_config($k, $max);
3115                 }
3116                 last if $max >= $head;
3117                 $min = $max + 1;
3118                 $max += $inc;
3119                 $max = $head if ($max > $head);
3120         }
3123 sub match_globs {
3124         my ($self, $exists, $paths, $globs, $r) = @_;
3126         sub get_dir_check {
3127                 my ($self, $exists, $g, $r) = @_;
3128                 my @x = eval { $self->get_dir($g->{path}->{left}, $r) };
3129                 return unless scalar @x == 3;
3130                 my $dirents = $x[0];
3131                 foreach my $de (keys %$dirents) {
3132                         next if $dirents->{$de}->kind != $SVN::Node::dir;
3133                         my $p = $g->{path}->full_path($de);
3134                         next if $exists->{$p};
3135                         next if (length $g->{path}->{right} &&
3136                                  ($self->check_path($p, $r) !=
3137                                   $SVN::Node::dir));
3138                         $exists->{$p} = Git::SVN->init($self->{url}, $p, undef,
3139                                          $g->{ref}->full_path($de), 1);
3140                 }
3141         }
3142         foreach my $g (@$globs) {
3143                 if (my $path = $paths->{"/$g->{path}->{left}"}) {
3144                         if ($path->{action} =~ /^[AR]$/) {
3145                                 get_dir_check($self, $exists, $g, $r);
3146                         }
3147                 }
3148                 foreach (keys %$paths) {
3149                         if (/$g->{path}->{left_regex}/ &&
3150                             !/$g->{path}->{regex}/) {
3151                                 next if $paths->{$_}->{action} !~ /^[AR]$/;
3152                                 get_dir_check($self, $exists, $g, $r);
3153                         }
3154                         next unless /$g->{path}->{regex}/;
3155                         my $p = $1;
3156                         my $pathname = $g->{path}->full_path($p);
3157                         next if $exists->{$pathname};
3158                         $exists->{$pathname} = Git::SVN->init(
3159                                               $self->{url}, $pathname, undef,
3160                                               $g->{ref}->full_path($p), 1);
3161                 }
3162                 my $c = '';
3163                 foreach (split m#/#, $g->{path}->{left}) {
3164                         $c .= "/$_";
3165                         next unless ($paths->{$c} &&
3166                                      ($paths->{$c}->{action} =~ /^[AR]$/));
3167                         get_dir_check($self, $exists, $g, $r);
3168                 }
3169         }
3170         values %$exists;
3173 sub minimize_url {
3174         my ($self) = @_;
3175         return $self->{url} if ($self->{url} eq $self->{repos_root});
3176         my $url = $self->{repos_root};
3177         my @components = split(m!/!, $self->{svn_path});
3178         my $c = '';
3179         do {
3180                 $url .= "/$c" if length $c;
3181                 eval { (ref $self)->new($url)->get_latest_revnum };
3182         } while ($@ && ($c = shift @components));
3183         $url;
3186 sub can_do_switch {
3187         my $self = shift;
3188         unless (defined $can_do_switch) {
3189                 my $pool = SVN::Pool->new;
3190                 my $rep = eval {
3191                         $self->do_switch(1, '', 0, $self->{url},
3192                                          SVN::Delta::Editor->new, $pool);
3193                 };
3194                 if ($@) {
3195                         $can_do_switch = 0;
3196                 } else {
3197                         $rep->abort_report($pool);
3198                         $can_do_switch = 1;
3199                 }
3200                 $pool->clear;
3201         }
3202         $can_do_switch;
3205 sub skip_unknown_revs {
3206         my ($err) = @_;
3207         my $errno = $err->apr_err();
3208         # Maybe the branch we're tracking didn't
3209         # exist when the repo started, so it's
3210         # not an error if it doesn't, just continue
3211         #
3212         # Wonderfully consistent library, eh?
3213         # 160013 - svn:// and file://
3214         # 175002 - http(s)://
3215         # 175007 - http(s):// (this repo required authorization, too...)
3216         #   More codes may be discovered later...
3217         if ($errno == 175007 || $errno == 175002 || $errno == 160013) {
3218                 my $err_key = $err->expanded_message;
3219                 # revision numbers change every time, filter them out
3220                 $err_key =~ s/\d+/\0/g;
3221                 $err_key = "$errno\0$err_key";
3222                 unless ($ignored_err{$err_key}) {
3223                         warn "W: Ignoring error from SVN, path probably ",
3224                              "does not exist: ($errno): ",
3225                              $err->expanded_message,"\n";
3226                         $ignored_err{$err_key} = 1;
3227                 }
3228                 return;
3229         }
3230         die "Error from SVN, ($errno): ", $err->expanded_message,"\n";
3233 # svn_log_changed_path_t objects passed to get_log are likely to be
3234 # overwritten even if only the refs are copied to an external variable,
3235 # so we should dup the structures in their entirety.  Using an externally
3236 # passed pool (instead of our temporary and quickly cleared pool in
3237 # Git::SVN::Ra) does not help matters at all...
3238 sub dup_changed_paths {
3239         my ($paths) = @_;
3240         return undef unless $paths;
3241         my %ret;
3242         foreach my $p (keys %$paths) {
3243                 my $i = $paths->{$p};
3244                 my %s = map { $_ => $i->$_ }
3245                               qw/copyfrom_path copyfrom_rev action/;
3246                 $ret{$p} = \%s;
3247         }
3248         \%ret;
3251 package Git::SVN::Log;
3252 use strict;
3253 use warnings;
3254 use POSIX qw/strftime/;
3255 use vars qw/$TZ $limit $color $pager $non_recursive $verbose $oneline
3256             %rusers $show_commit $incremental/;
3257 my $l_fmt;
3259 sub cmt_showable {
3260         my ($c) = @_;
3261         return 1 if defined $c->{r};
3262         if ($c->{l} && $c->{l}->[-1] eq "...\n" &&
3263                                 $c->{a_raw} =~ /\@([a-f\d\-]+)>$/) {
3264                 my @log = command(qw/cat-file commit/, $c->{c});
3265                 shift @log while ($log[0] ne "\n");
3266                 shift @log;
3267                 @{$c->{l}} = grep !/^git-svn-id: /, @log;
3269                 (undef, $c->{r}, undef) = ::extract_metadata(
3270                                 (grep(/^git-svn-id: /, @log))[-1]);
3271         }
3272         return defined $c->{r};
3275 sub log_use_color {
3276         return 1 if $color;
3277         my ($dc, $dcvar);
3278         $dcvar = 'color.diff';
3279         $dc = `git-config --get $dcvar`;
3280         if ($dc eq '') {
3281                 # nothing at all; fallback to "diff.color"
3282                 $dcvar = 'diff.color';
3283                 $dc = `git-config --get $dcvar`;
3284         }
3285         chomp($dc);
3286         if ($dc eq 'auto') {
3287                 my $pc;
3288                 $pc = `git-config --get color.pager`;
3289                 if ($pc eq '') {
3290                         # does not have it -- fallback to pager.color
3291                         $pc = `git-config --bool --get pager.color`;
3292                 }
3293                 else {
3294                         $pc = `git-config --bool --get color.pager`;
3295                         if ($?) {
3296                                 $pc = 'false';
3297                         }
3298                 }
3299                 chomp($pc);
3300                 if (-t *STDOUT || (defined $pager && $pc eq 'true')) {
3301                         return ($ENV{TERM} && $ENV{TERM} ne 'dumb');
3302                 }
3303                 return 0;
3304         }
3305         return 0 if $dc eq 'never';
3306         return 1 if $dc eq 'always';
3307         chomp($dc = `git-config --bool --get $dcvar`);
3308         return ($dc eq 'true');
3311 sub git_svn_log_cmd {
3312         my ($r_min, $r_max, @args) = @_;
3313         my $head = 'HEAD';
3314         foreach my $x (@args) {
3315                 last if $x eq '--';
3316                 next unless ::verify_ref("$x^0");
3317                 $head = $x;
3318                 last;
3319         }
3321         my $url = (::working_head_info($head))[0];
3322         my $gs = Git::SVN->find_by_url($url) || Git::SVN->_new;
3323         my @cmd = (qw/log --abbrev-commit --pretty=raw --default/,
3324                    $gs->refname);
3325         push @cmd, '-r' unless $non_recursive;
3326         push @cmd, qw/--raw --name-status/ if $verbose;
3327         push @cmd, '--color' if log_use_color();
3328         return @cmd unless defined $r_max;
3329         if ($r_max == $r_min) {
3330                 push @cmd, '--max-count=1';
3331                 if (my $c = $gs->rev_db_get($r_max)) {
3332                         push @cmd, $c;
3333                 }
3334         } else {
3335                 my ($c_min, $c_max);
3336                 $c_max = $gs->rev_db_get($r_max);
3337                 $c_min = $gs->rev_db_get($r_min);
3338                 if (defined $c_min && defined $c_max) {
3339                         if ($r_max > $r_max) {
3340                                 push @cmd, "$c_min..$c_max";
3341                         } else {
3342                                 push @cmd, "$c_max..$c_min";
3343                         }
3344                 } elsif ($r_max > $r_min) {
3345                         push @cmd, $c_max;
3346                 } else {
3347                         push @cmd, $c_min;
3348                 }
3349         }
3350         return @cmd;
3353 # adapted from pager.c
3354 sub config_pager {
3355         $pager ||= $ENV{GIT_PAGER} || $ENV{PAGER};
3356         if (!defined $pager) {
3357                 $pager = 'less';
3358         } elsif (length $pager == 0 || $pager eq 'cat') {
3359                 $pager = undef;
3360         }
3363 sub run_pager {
3364         return unless -t *STDOUT;
3365         pipe my $rfd, my $wfd or return;
3366         defined(my $pid = fork) or ::fatal "Can't fork: $!\n";
3367         if (!$pid) {
3368                 open STDOUT, '>&', $wfd or
3369                                      ::fatal "Can't redirect to stdout: $!\n";
3370                 return;
3371         }
3372         open STDIN, '<&', $rfd or ::fatal "Can't redirect stdin: $!\n";
3373         $ENV{LESS} ||= 'FRSX';
3374         exec $pager or ::fatal "Can't run pager: $! ($pager)\n";
3377 sub tz_to_s_offset {
3378         my ($tz) = @_;
3379         $tz =~ s/(\d\d)$//;
3380         return ($1 * 60) + ($tz * 3600);
3383 sub get_author_info {
3384         my ($dest, $author, $t, $tz) = @_;
3385         $author =~ s/(?:^\s*|\s*$)//g;
3386         $dest->{a_raw} = $author;
3387         my $au;
3388         if ($::_authors) {
3389                 $au = $rusers{$author} || undef;
3390         }
3391         if (!$au) {
3392                 ($au) = ($author =~ /<([^>]+)\@[^>]+>$/);
3393         }
3394         $dest->{t} = $t;
3395         $dest->{tz} = $tz;
3396         $dest->{a} = $au;
3397         # Date::Parse isn't in the standard Perl distro :(
3398         if ($tz =~ s/^\+//) {
3399                 $t += tz_to_s_offset($tz);
3400         } elsif ($tz =~ s/^\-//) {
3401                 $t -= tz_to_s_offset($tz);
3402         }
3403         $dest->{t_utc} = $t;
3406 sub process_commit {
3407         my ($c, $r_min, $r_max, $defer) = @_;
3408         if (defined $r_min && defined $r_max) {
3409                 if ($r_min == $c->{r} && $r_min == $r_max) {
3410                         show_commit($c);
3411                         return 0;
3412                 }
3413                 return 1 if $r_min == $r_max;
3414                 if ($r_min < $r_max) {
3415                         # we need to reverse the print order
3416                         return 0 if (defined $limit && --$limit < 0);
3417                         push @$defer, $c;
3418                         return 1;
3419                 }
3420                 if ($r_min != $r_max) {
3421                         return 1 if ($r_min < $c->{r});
3422                         return 1 if ($r_max > $c->{r});
3423                 }
3424         }
3425         return 0 if (defined $limit && --$limit < 0);
3426         show_commit($c);
3427         return 1;
3430 sub show_commit {
3431         my $c = shift;
3432         if ($oneline) {
3433                 my $x = "\n";
3434                 if (my $l = $c->{l}) {
3435                         while ($l->[0] =~ /^\s*$/) { shift @$l }
3436                         $x = $l->[0];
3437                 }
3438                 $l_fmt ||= 'A' . length($c->{r});
3439                 print 'r',pack($l_fmt, $c->{r}),' | ';
3440                 print "$c->{c} | " if $show_commit;
3441                 print $x;
3442         } else {
3443                 show_commit_normal($c);
3444         }
3447 sub show_commit_changed_paths {
3448         my ($c) = @_;
3449         return unless $c->{changed};
3450         print "Changed paths:\n", @{$c->{changed}};
3453 sub show_commit_normal {
3454         my ($c) = @_;
3455         print '-' x72, "\nr$c->{r} | ";
3456         print "$c->{c} | " if $show_commit;
3457         print "$c->{a} | ", strftime("%Y-%m-%d %H:%M:%S %z (%a, %d %b %Y)",
3458                                  localtime($c->{t_utc})), ' | ';
3459         my $nr_line = 0;
3461         if (my $l = $c->{l}) {
3462                 while ($l->[$#$l] eq "\n" && $#$l > 0
3463                                           && $l->[($#$l - 1)] eq "\n") {
3464                         pop @$l;
3465                 }
3466                 $nr_line = scalar @$l;
3467                 if (!$nr_line) {
3468                         print "1 line\n\n\n";
3469                 } else {
3470                         if ($nr_line == 1) {
3471                                 $nr_line = '1 line';
3472                         } else {
3473                                 $nr_line .= ' lines';
3474                         }
3475                         print $nr_line, "\n";
3476                         show_commit_changed_paths($c);
3477                         print "\n";
3478                         print $_ foreach @$l;
3479                 }
3480         } else {
3481                 print "1 line\n";
3482                 show_commit_changed_paths($c);
3483                 print "\n";
3485         }
3486         foreach my $x (qw/raw stat diff/) {
3487                 if ($c->{$x}) {
3488                         print "\n";
3489                         print $_ foreach @{$c->{$x}}
3490                 }
3491         }
3494 sub cmd_show_log {
3495         my (@args) = @_;
3496         my ($r_min, $r_max);
3497         my $r_last = -1; # prevent dupes
3498         if (defined $TZ) {
3499                 $ENV{TZ} = $TZ;
3500         } else {
3501                 delete $ENV{TZ};
3502         }
3503         if (defined $::_revision) {
3504                 if ($::_revision =~ /^(\d+):(\d+)$/) {
3505                         ($r_min, $r_max) = ($1, $2);
3506                 } elsif ($::_revision =~ /^\d+$/) {
3507                         $r_min = $r_max = $::_revision;
3508                 } else {
3509                         ::fatal "-r$::_revision is not supported, use ",
3510                                 "standard \'git log\' arguments instead\n";
3511                 }
3512         }
3514         config_pager();
3515         @args = (git_svn_log_cmd($r_min, $r_max, @args), @args);
3516         my $log = command_output_pipe(@args);
3517         run_pager();
3518         my (@k, $c, $d, $stat);
3519         my $esc_color = qr/(?:\033\[(?:(?:\d+;)*\d*)?m)*/;
3520         while (<$log>) {
3521                 if (/^${esc_color}commit ($::sha1_short)/o) {
3522                         my $cmt = $1;
3523                         if ($c && cmt_showable($c) && $c->{r} != $r_last) {
3524                                 $r_last = $c->{r};
3525                                 process_commit($c, $r_min, $r_max, \@k) or
3526                                                                 goto out;
3527                         }
3528                         $d = undef;
3529                         $c = { c => $cmt };
3530                 } elsif (/^${esc_color}author (.+) (\d+) ([\-\+]?\d+)$/o) {
3531                         get_author_info($c, $1, $2, $3);
3532                 } elsif (/^${esc_color}(?:tree|parent|committer) /o) {
3533                         # ignore
3534                 } elsif (/^${esc_color}:\d{6} \d{6} $::sha1_short/o) {
3535                         push @{$c->{raw}}, $_;
3536                 } elsif (/^${esc_color}[ACRMDT]\t/) {
3537                         # we could add $SVN->{svn_path} here, but that requires
3538                         # remote access at the moment (repo_path_split)...
3539                         s#^(${esc_color})([ACRMDT])\t#$1   $2 #o;
3540                         push @{$c->{changed}}, $_;
3541                 } elsif (/^${esc_color}diff /o) {
3542                         $d = 1;
3543                         push @{$c->{diff}}, $_;
3544                 } elsif ($d) {
3545                         push @{$c->{diff}}, $_;
3546                 } elsif (/^\ .+\ \|\s*\d+\ $esc_color[\+\-]*
3547                           $esc_color*[\+\-]*$esc_color$/x) {
3548                         $stat = 1;
3549                         push @{$c->{stat}}, $_;
3550                 } elsif ($stat && /^ \d+ files changed, \d+ insertions/) {
3551                         push @{$c->{stat}}, $_;
3552                         $stat = undef;
3553                 } elsif (/^${esc_color}    (git-svn-id:.+)$/o) {
3554                         ($c->{url}, $c->{r}, undef) = ::extract_metadata($1);
3555                 } elsif (s/^${esc_color}    //o) {
3556                         push @{$c->{l}}, $_;
3557                 }
3558         }
3559         if ($c && defined $c->{r} && $c->{r} != $r_last) {
3560                 $r_last = $c->{r};
3561                 process_commit($c, $r_min, $r_max, \@k);
3562         }
3563         if (@k) {
3564                 my $swap = $r_max;
3565                 $r_max = $r_min;
3566                 $r_min = $swap;
3567                 process_commit($_, $r_min, $r_max) foreach reverse @k;
3568         }
3569 out:
3570         close $log;
3571         print '-' x72,"\n" unless $incremental || $oneline;
3574 package Git::SVN::Migration;
3575 # these version numbers do NOT correspond to actual version numbers
3576 # of git nor git-svn.  They are just relative.
3578 # v0 layout: .git/$id/info/url, refs/heads/$id-HEAD
3580 # v1 layout: .git/$id/info/url, refs/remotes/$id
3582 # v2 layout: .git/svn/$id/info/url, refs/remotes/$id
3584 # v3 layout: .git/svn/$id, refs/remotes/$id
3585 #            - info/url may remain for backwards compatibility
3586 #            - this is what we migrate up to this layout automatically,
3587 #            - this will be used by git svn init on single branches
3588 # v3.1 layout (auto migrated):
3589 #            - .rev_db => .rev_db.$UUID, .rev_db will remain as a symlink
3590 #              for backwards compatibility
3592 # v4 layout: .git/svn/$repo_id/$id, refs/remotes/$repo_id/$id
3593 #            - this is only created for newly multi-init-ed
3594 #              repositories.  Similar in spirit to the
3595 #              --use-separate-remotes option in git-clone (now default)
3596 #            - we do not automatically migrate to this (following
3597 #              the example set by core git)
3598 use strict;
3599 use warnings;
3600 use Carp qw/croak/;
3601 use File::Path qw/mkpath/;
3602 use File::Basename qw/dirname basename/;
3603 use vars qw/$_minimize/;
3605 sub migrate_from_v0 {
3606         my $git_dir = $ENV{GIT_DIR};
3607         return undef unless -d $git_dir;
3608         my ($fh, $ctx) = command_output_pipe(qw/rev-parse --symbolic --all/);
3609         my $migrated = 0;
3610         while (<$fh>) {
3611                 chomp;
3612                 my ($id, $orig_ref) = ($_, $_);
3613                 next unless $id =~ s#^refs/heads/(.+)-HEAD$#$1#;
3614                 next unless -f "$git_dir/$id/info/url";
3615                 my $new_ref = "refs/remotes/$id";
3616                 if (::verify_ref("$new_ref^0")) {
3617                         print STDERR "W: $orig_ref is probably an old ",
3618                                      "branch used by an ancient version of ",
3619                                      "git-svn.\n",
3620                                      "However, $new_ref also exists.\n",
3621                                      "We will not be able ",
3622                                      "to use this branch until this ",
3623                                      "ambiguity is resolved.\n";
3624                         next;
3625                 }
3626                 print STDERR "Migrating from v0 layout...\n" if !$migrated;
3627                 print STDERR "Renaming ref: $orig_ref => $new_ref\n";
3628                 command_noisy('update-ref', $new_ref, $orig_ref);
3629                 command_noisy('update-ref', '-d', $orig_ref, $orig_ref);
3630                 $migrated++;
3631         }
3632         command_close_pipe($fh, $ctx);
3633         print STDERR "Done migrating from v0 layout...\n" if $migrated;
3634         $migrated;
3637 sub migrate_from_v1 {
3638         my $git_dir = $ENV{GIT_DIR};
3639         my $migrated = 0;
3640         return $migrated unless -d $git_dir;
3641         my $svn_dir = "$git_dir/svn";
3643         # just in case somebody used 'svn' as their $id at some point...
3644         return $migrated if -d $svn_dir && ! -f "$svn_dir/info/url";
3646         print STDERR "Migrating from a git-svn v1 layout...\n";
3647         mkpath([$svn_dir]);
3648         print STDERR "Data from a previous version of git-svn exists, but\n\t",
3649                      "$svn_dir\n\t(required for this version ",
3650                      "($::VERSION) of git-svn) does not. exist\n";
3651         my ($fh, $ctx) = command_output_pipe(qw/rev-parse --symbolic --all/);
3652         while (<$fh>) {
3653                 my $x = $_;
3654                 next unless $x =~ s#^refs/remotes/##;
3655                 chomp $x;
3656                 next unless -f "$git_dir/$x/info/url";
3657                 my $u = eval { ::file_to_s("$git_dir/$x/info/url") };
3658                 next unless $u;
3659                 my $dn = dirname("$git_dir/svn/$x");
3660                 mkpath([$dn]) unless -d $dn;
3661                 if ($x eq 'svn') { # they used 'svn' as GIT_SVN_ID:
3662                         mkpath(["$git_dir/svn/svn"]);
3663                         print STDERR " - $git_dir/$x/info => ",
3664                                         "$git_dir/svn/$x/info\n";
3665                         rename "$git_dir/$x/info", "$git_dir/svn/$x/info" or
3666                                croak "$!: $x";
3667                         # don't worry too much about these, they probably
3668                         # don't exist with repos this old (save for index,
3669                         # and we can easily regenerate that)
3670                         foreach my $f (qw/unhandled.log index .rev_db/) {
3671                                 rename "$git_dir/$x/$f", "$git_dir/svn/$x/$f";
3672                         }
3673                 } else {
3674                         print STDERR " - $git_dir/$x => $git_dir/svn/$x\n";
3675                         rename "$git_dir/$x", "$git_dir/svn/$x" or
3676                                croak "$!: $x";
3677                 }
3678                 $migrated++;
3679         }
3680         command_close_pipe($fh, $ctx);
3681         print STDERR "Done migrating from a git-svn v1 layout\n";
3682         $migrated;
3685 sub read_old_urls {
3686         my ($l_map, $pfx, $path) = @_;
3687         my @dir;
3688         foreach (<$path/*>) {
3689                 if (-r "$_/info/url") {
3690                         $pfx .= '/' if $pfx && $pfx !~ m!/$!;
3691                         my $ref_id = $pfx . basename $_;
3692                         my $url = ::file_to_s("$_/info/url");
3693                         $l_map->{$ref_id} = $url;
3694                 } elsif (-d $_) {
3695                         push @dir, $_;
3696                 }
3697         }
3698         foreach (@dir) {
3699                 my $x = $_;
3700                 $x =~ s!^\Q$ENV{GIT_DIR}\E/svn/!!o;
3701                 read_old_urls($l_map, $x, $_);
3702         }
3705 sub migrate_from_v2 {
3706         my @cfg = command(qw/config -l/);
3707         return if grep /^svn-remote\..+\.url=/, @cfg;
3708         my %l_map;
3709         read_old_urls(\%l_map, '', "$ENV{GIT_DIR}/svn");
3710         my $migrated = 0;
3712         foreach my $ref_id (sort keys %l_map) {
3713                 eval { Git::SVN->init($l_map{$ref_id}, '', undef, $ref_id) };
3714                 if ($@) {
3715                         Git::SVN->init($l_map{$ref_id}, '', $ref_id, $ref_id);
3716                 }
3717                 $migrated++;
3718         }
3719         $migrated;
3722 sub minimize_connections {
3723         my $r = Git::SVN::read_all_remotes();
3724         my $new_urls = {};
3725         my $root_repos = {};
3726         foreach my $repo_id (keys %$r) {
3727                 my $url = $r->{$repo_id}->{url} or next;
3728                 my $fetch = $r->{$repo_id}->{fetch} or next;
3729                 my $ra = Git::SVN::Ra->new($url);
3731                 # skip existing cases where we already connect to the root
3732                 if (($ra->{url} eq $ra->{repos_root}) ||
3733                     (Git::SVN::sanitize_remote_name($ra->{repos_root}) eq
3734                      $repo_id)) {
3735                         $root_repos->{$ra->{url}} = $repo_id;
3736                         next;
3737                 }
3739                 my $root_ra = Git::SVN::Ra->new($ra->{repos_root});
3740                 my $root_path = $ra->{url};
3741                 $root_path =~ s#^\Q$ra->{repos_root}\E(/|$)##;
3742                 foreach my $path (keys %$fetch) {
3743                         my $ref_id = $fetch->{$path};
3744                         my $gs = Git::SVN->new($ref_id, $repo_id, $path);
3746                         # make sure we can read when connecting to
3747                         # a higher level of a repository
3748                         my ($last_rev, undef) = $gs->last_rev_commit;
3749                         if (!defined $last_rev) {
3750                                 $last_rev = eval {
3751                                         $root_ra->get_latest_revnum;
3752                                 };
3753                                 next if $@;
3754                         }
3755                         my $new = $root_path;
3756                         $new .= length $path ? "/$path" : '';
3757                         eval {
3758                                 $root_ra->get_log([$new], $last_rev, $last_rev,
3759                                                   0, 0, 1, sub { });
3760                         };
3761                         next if $@;
3762                         $new_urls->{$ra->{repos_root}}->{$new} =
3763                                 { ref_id => $ref_id,
3764                                   old_repo_id => $repo_id,
3765                                   old_path => $path };
3766                 }
3767         }
3769         my @emptied;
3770         foreach my $url (keys %$new_urls) {
3771                 # see if we can re-use an existing [svn-remote "repo_id"]
3772                 # instead of creating a(n ugly) new section:
3773                 my $repo_id = $root_repos->{$url} ||
3774                               Git::SVN::sanitize_remote_name($url);
3776                 my $fetch = $new_urls->{$url};
3777                 foreach my $path (keys %$fetch) {
3778                         my $x = $fetch->{$path};
3779                         Git::SVN->init($url, $path, $repo_id, $x->{ref_id});
3780                         my $pfx = "svn-remote.$x->{old_repo_id}";
3782                         my $old_fetch = quotemeta("$x->{old_path}:".
3783                                                   "refs/remotes/$x->{ref_id}");
3784                         command_noisy(qw/config --unset/,
3785                                       "$pfx.fetch", '^'. $old_fetch . '$');
3786                         delete $r->{$x->{old_repo_id}}->
3787                                {fetch}->{$x->{old_path}};
3788                         if (!keys %{$r->{$x->{old_repo_id}}->{fetch}}) {
3789                                 command_noisy(qw/config --unset/,
3790                                               "$pfx.url");
3791                                 push @emptied, $x->{old_repo_id}
3792                         }
3793                 }
3794         }
3795         if (@emptied) {
3796                 my $file = $ENV{GIT_CONFIG} || $ENV{GIT_CONFIG_LOCAL} ||
3797                            "$ENV{GIT_DIR}/config";
3798                 print STDERR <<EOF;
3799 The following [svn-remote] sections in your config file ($file) are empty
3800 and can be safely removed:
3801 EOF
3802                 print STDERR "[svn-remote \"$_\"]\n" foreach @emptied;
3803         }
3806 sub migration_check {
3807         migrate_from_v0();
3808         migrate_from_v1();
3809         migrate_from_v2();
3810         minimize_connections() if $_minimize;
3813 package Git::IndexInfo;
3814 use strict;
3815 use warnings;
3816 use Git qw/command_input_pipe command_close_pipe/;
3818 sub new {
3819         my ($class) = @_;
3820         my ($gui, $ctx) = command_input_pipe(qw/update-index -z --index-info/);
3821         bless { gui => $gui, ctx => $ctx, nr => 0}, $class;
3824 sub remove {
3825         my ($self, $path) = @_;
3826         if (print { $self->{gui} } '0 ', 0 x 40, "\t", $path, "\0") {
3827                 return ++$self->{nr};
3828         }
3829         undef;
3832 sub update {
3833         my ($self, $mode, $hash, $path) = @_;
3834         if (print { $self->{gui} } $mode, ' ', $hash, "\t", $path, "\0") {
3835                 return ++$self->{nr};
3836         }
3837         undef;
3840 sub DESTROY {
3841         my ($self) = @_;
3842         command_close_pipe($self->{gui}, $self->{ctx});
3845 package Git::SVN::GlobSpec;
3846 use strict;
3847 use warnings;
3849 sub new {
3850         my ($class, $glob) = @_;
3851         my $re = $glob;
3852         $re =~ s!/+$!!g; # no need for trailing slashes
3853         my $nr = ($re =~ s!^(.*)\*(.*)$!\(\[^/\]+\)!g);
3854         my ($left, $right) = ($1, $2);
3855         if ($nr > 1) {
3856                 die "Only one '*' wildcard expansion ",
3857                     "is supported (got $nr): '$glob'\n";
3858         } elsif ($nr == 0) {
3859                 die "One '*' is needed for glob: '$glob'\n";
3860         }
3861         $re = quotemeta($left) . $re . quotemeta($right);
3862         if (length $left && !($left =~ s!/+$!!g)) {
3863                 die "Missing trailing '/' on left side of: '$glob' ($left)\n";
3864         }
3865         if (length $right && !($right =~ s!^/+!!g)) {
3866                 die "Missing leading '/' on right side of: '$glob' ($right)\n";
3867         }
3868         my $left_re = qr/^\/\Q$left\E(\/|$)/;
3869         bless { left => $left, right => $right, left_regex => $left_re,
3870                 regex => qr/$re/, glob => $glob }, $class;
3873 sub full_path {
3874         my ($self, $path) = @_;
3875         return (length $self->{left} ? "$self->{left}/" : '') .
3876                $path . (length $self->{right} ? "/$self->{right}" : '');
3879 __END__
3881 Data structures:
3884 $remotes = { # returned by read_all_remotes()
3885         'svn' => {
3886                 # svn-remote.svn.url=https://svn.musicpd.org
3887                 url => 'https://svn.musicpd.org',
3888                 # svn-remote.svn.fetch=mpd/trunk:trunk
3889                 fetch => {
3890                         'mpd/trunk' => 'trunk',
3891                 },
3892                 # svn-remote.svn.tags=mpd/tags/*:tags/*
3893                 tags => {
3894                         path => {
3895                                 left => 'mpd/tags',
3896                                 right => '',
3897                                 regex => qr!mpd/tags/([^/]+)$!,
3898                                 glob => 'tags/*',
3899                         },
3900                         ref => {
3901                                 left => 'tags',
3902                                 right => '',
3903                                 regex => qr!tags/([^/]+)$!,
3904                                 glob => 'tags/*',
3905                         },
3906                 }
3907         }
3908 };
3910 $log_entry hashref as returned by libsvn_log_entry()
3912         log => 'whitespace-formatted log entry
3913 ',                                              # trailing newline is preserved
3914         revision => '8',                        # integer
3915         date => '2004-02-24T17:01:44.108345Z',  # commit date
3916         author => 'committer name'
3917 };
3920 # this is generated by generate_diff();
3921 @mods = array of diff-index line hashes, each element represents one line
3922         of diff-index output
3924 diff-index line ($m hash)
3926         mode_a => first column of diff-index output, no leading ':',
3927         mode_b => second column of diff-index output,
3928         sha1_b => sha1sum of the final blob,
3929         chg => change type [MCRADT],
3930         file_a => original file name of a file (iff chg is 'C' or 'R')
3931         file_b => new/current file name of a file (any chg)
3935 # retval of read_url_paths{,_all}();
3936 $l_map = {
3937         # repository root url
3938         'https://svn.musicpd.org' => {
3939                 # repository path               # GIT_SVN_ID
3940                 'mpd/trunk'             =>      'trunk',
3941                 'mpd/tags/0.11.5'       =>      'tags/0.11.5',
3942         },
3945 Notes:
3946         I don't trust the each() function on unless I created %hash myself
3947         because the internal iterator may not have started at base.