Code

sha1_file.c (write_sha1_from_fd): Detect close failure.
[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         if (command(qw/diff-index HEAD --/)) {
439                 print STDERR "Cannot rebase with uncommited changes:\n";
440                 command_noisy('status');
441                 exit 1;
442         }
443         unless ($_local) {
444                 $_fetch_all ? $gs->fetch_all : $gs->fetch;
445         }
446         command_noisy(rebase_cmd(), $gs->refname);
449 sub cmd_show_ignore {
450         my $url = (::working_head_info('HEAD'))[0];
451         my $gs = Git::SVN->find_by_url($url) || Git::SVN->new;
452         my $r = (defined $_revision ? $_revision : $gs->ra->get_latest_revnum);
453         $gs->traverse_ignore(\*STDOUT, $gs->{path}, $r);
456 sub cmd_multi_init {
457         my $url = shift;
458         unless (defined $_trunk || defined $_branches || defined $_tags) {
459                 usage(1);
460         }
461         $_prefix = '' unless defined $_prefix;
462         if (defined $url) {
463                 $url =~ s#/+$##;
464                 init_subdir(@_);
465         }
466         do_git_init_db();
467         if (defined $_trunk) {
468                 my $trunk_ref = $_prefix . 'trunk';
469                 # try both old-style and new-style lookups:
470                 my $gs_trunk = eval { Git::SVN->new($trunk_ref) };
471                 unless ($gs_trunk) {
472                         my ($trunk_url, $trunk_path) =
473                                               complete_svn_url($url, $_trunk);
474                         $gs_trunk = Git::SVN->init($trunk_url, $trunk_path,
475                                                    undef, $trunk_ref);
476                 }
477         }
478         return unless defined $_branches || defined $_tags;
479         my $ra = $url ? Git::SVN::Ra->new($url) : undef;
480         complete_url_ls_init($ra, $_branches, '--branches/-b', $_prefix);
481         complete_url_ls_init($ra, $_tags, '--tags/-t', $_prefix . 'tags/');
484 sub cmd_multi_fetch {
485         my $remotes = Git::SVN::read_all_remotes();
486         foreach my $repo_id (sort keys %$remotes) {
487                 if ($remotes->{$repo_id}->{url}) {
488                         Git::SVN::fetch_all($repo_id, $remotes);
489                 }
490         }
493 # this command is special because it requires no metadata
494 sub cmd_commit_diff {
495         my ($ta, $tb, $url) = @_;
496         my $usage = "Usage: $0 commit-diff -r<revision> ".
497                     "<tree-ish> <tree-ish> [<URL>]\n";
498         fatal($usage) if (!defined $ta || !defined $tb);
499         my $svn_path;
500         if (!defined $url) {
501                 my $gs = eval { Git::SVN->new };
502                 if (!$gs) {
503                         fatal("Needed URL or usable git-svn --id in ",
504                               "the command-line\n", $usage);
505                 }
506                 $url = $gs->{url};
507                 $svn_path = $gs->{path};
508         }
509         unless (defined $_revision) {
510                 fatal("-r|--revision is a required argument\n", $usage);
511         }
512         if (defined $_message && defined $_file) {
513                 fatal("Both --message/-m and --file/-F specified ",
514                       "for the commit message.\n",
515                       "I have no idea what you mean\n");
516         }
517         if (defined $_file) {
518                 $_message = file_to_s($_file);
519         } else {
520                 $_message ||= get_commit_entry($tb)->{log};
521         }
522         my $ra ||= Git::SVN::Ra->new($url);
523         $svn_path ||= $ra->{svn_path};
524         my $r = $_revision;
525         if ($r eq 'HEAD') {
526                 $r = $ra->get_latest_revnum;
527         } elsif ($r !~ /^\d+$/) {
528                 die "revision argument: $r not understood by git-svn\n";
529         }
530         my %ed_opts = ( r => $r,
531                         log => $_message,
532                         ra => $ra,
533                         tree_a => $ta,
534                         tree_b => $tb,
535                         editor_cb => sub { print "Committed r$_[0]\n" },
536                         svn_path => $svn_path );
537         if (!SVN::Git::Editor->new(\%ed_opts)->apply_diff) {
538                 print "No changes\n$ta == $tb\n";
539         }
542 ########################### utility functions #########################
544 sub rebase_cmd {
545         my @cmd = qw/rebase/;
546         push @cmd, '-v' if $_verbose;
547         push @cmd, qw/--merge/ if $_merge;
548         push @cmd, "--strategy=$_strategy" if $_strategy;
549         @cmd;
552 sub post_fetch_checkout {
553         return if $_no_checkout;
554         my $gs = $Git::SVN::_head or return;
555         return if verify_ref('refs/heads/master^0');
557         my $valid_head = verify_ref('HEAD^0');
558         command_noisy(qw(update-ref refs/heads/master), $gs->refname);
559         return if ($valid_head || !verify_ref('HEAD^0'));
561         return if $ENV{GIT_DIR} !~ m#^(?:.*/)?\.git$#;
562         my $index = $ENV{GIT_INDEX_FILE} || "$ENV{GIT_DIR}/index";
563         return if -f $index;
565         chomp(my $bare = `git config --bool --get core.bare`);
566         return if $bare eq 'true';
567         return if command_oneline(qw/rev-parse --is-inside-git-dir/) eq 'true';
568         command_noisy(qw/read-tree -m -u -v HEAD HEAD/);
569         print STDERR "Checked out HEAD:\n  ",
570                      $gs->full_url, " r", $gs->last_rev, "\n";
573 sub complete_svn_url {
574         my ($url, $path) = @_;
575         $path =~ s#/+$##;
576         if ($path !~ m#^[a-z\+]+://#) {
577                 if (!defined $url || $url !~ m#^[a-z\+]+://#) {
578                         fatal("E: '$path' is not a complete URL ",
579                               "and a separate URL is not specified\n");
580                 }
581                 return ($url, $path);
582         }
583         return ($path, '');
586 sub complete_url_ls_init {
587         my ($ra, $repo_path, $switch, $pfx) = @_;
588         unless ($repo_path) {
589                 print STDERR "W: $switch not specified\n";
590                 return;
591         }
592         $repo_path =~ s#/+$##;
593         if ($repo_path =~ m#^[a-z\+]+://#) {
594                 $ra = Git::SVN::Ra->new($repo_path);
595                 $repo_path = '';
596         } else {
597                 $repo_path =~ s#^/+##;
598                 unless ($ra) {
599                         fatal("E: '$repo_path' is not a complete URL ",
600                               "and a separate URL is not specified\n");
601                 }
602         }
603         my $url = $ra->{url};
604         my $gs = Git::SVN->init($url, undef, undef, undef, 1);
605         my $k = "svn-remote.$gs->{repo_id}.url";
606         my $orig_url = eval { command_oneline(qw/config --get/, $k) };
607         if ($orig_url && ($orig_url ne $gs->{url})) {
608                 die "$k already set: $orig_url\n",
609                     "wanted to set to: $gs->{url}\n";
610         }
611         command_oneline('config', $k, $gs->{url}) unless $orig_url;
612         my $remote_path = "$ra->{svn_path}/$repo_path/*";
613         $remote_path =~ s#/+#/#g;
614         $remote_path =~ s#^/##g;
615         my ($n) = ($switch =~ /^--(\w+)/);
616         if (length $pfx && $pfx !~ m#/$#) {
617                 die "--prefix='$pfx' must have a trailing slash '/'\n";
618         }
619         command_noisy('config', "svn-remote.$gs->{repo_id}.$n",
620                                 "$remote_path:refs/remotes/$pfx*");
623 sub verify_ref {
624         my ($ref) = @_;
625         eval { command_oneline([ 'rev-parse', '--verify', $ref ],
626                                { STDERR => 0 }); };
629 sub get_tree_from_treeish {
630         my ($treeish) = @_;
631         # $treeish can be a symbolic ref, too:
632         my $type = command_oneline(qw/cat-file -t/, $treeish);
633         my $expected;
634         while ($type eq 'tag') {
635                 ($treeish, $type) = command(qw/cat-file tag/, $treeish);
636         }
637         if ($type eq 'commit') {
638                 $expected = (grep /^tree /, command(qw/cat-file commit/,
639                                                     $treeish))[0];
640                 ($expected) = ($expected =~ /^tree ($sha1)$/o);
641                 die "Unable to get tree from $treeish\n" unless $expected;
642         } elsif ($type eq 'tree') {
643                 $expected = $treeish;
644         } else {
645                 die "$treeish is a $type, expected tree, tag or commit\n";
646         }
647         return $expected;
650 sub get_commit_entry {
651         my ($treeish) = shift;
652         my %log_entry = ( log => '', tree => get_tree_from_treeish($treeish) );
653         my $commit_editmsg = "$ENV{GIT_DIR}/COMMIT_EDITMSG";
654         my $commit_msg = "$ENV{GIT_DIR}/COMMIT_MSG";
655         open my $log_fh, '>', $commit_editmsg or croak $!;
657         my $type = command_oneline(qw/cat-file -t/, $treeish);
658         if ($type eq 'commit' || $type eq 'tag') {
659                 my ($msg_fh, $ctx) = command_output_pipe('cat-file',
660                                                          $type, $treeish);
661                 my $in_msg = 0;
662                 while (<$msg_fh>) {
663                         if (!$in_msg) {
664                                 $in_msg = 1 if (/^\s*$/);
665                         } elsif (/^git-svn-id: /) {
666                                 # skip this for now, we regenerate the
667                                 # correct one on re-fetch anyways
668                                 # TODO: set *:merge properties or like...
669                         } else {
670                                 print $log_fh $_ or croak $!;
671                         }
672                 }
673                 command_close_pipe($msg_fh, $ctx);
674         }
675         close $log_fh or croak $!;
677         if ($_edit || ($type eq 'tree')) {
678                 my $editor = $ENV{VISUAL} || $ENV{EDITOR} || 'vi';
679                 # TODO: strip out spaces, comments, like git-commit.sh
680                 system($editor, $commit_editmsg);
681         }
682         rename $commit_editmsg, $commit_msg or croak $!;
683         open $log_fh, '<', $commit_msg or croak $!;
684         { local $/; chomp($log_entry{log} = <$log_fh>); }
685         close $log_fh or croak $!;
686         unlink $commit_msg;
687         \%log_entry;
690 sub s_to_file {
691         my ($str, $file, $mode) = @_;
692         open my $fd,'>',$file or croak $!;
693         print $fd $str,"\n" or croak $!;
694         close $fd or croak $!;
695         chmod ($mode &~ umask, $file) if (defined $mode);
698 sub file_to_s {
699         my $file = shift;
700         open my $fd,'<',$file or croak "$!: file: $file\n";
701         local $/;
702         my $ret = <$fd>;
703         close $fd or croak $!;
704         $ret =~ s/\s*$//s;
705         return $ret;
708 # '<svn username> = real-name <email address>' mapping based on git-svnimport:
709 sub load_authors {
710         open my $authors, '<', $_authors or die "Can't open $_authors $!\n";
711         my $log = $cmd eq 'log';
712         while (<$authors>) {
713                 chomp;
714                 next unless /^(\S+?|\(no author\))\s*=\s*(.+?)\s*<(.+)>\s*$/;
715                 my ($user, $name, $email) = ($1, $2, $3);
716                 if ($log) {
717                         $Git::SVN::Log::rusers{"$name <$email>"} = $user;
718                 } else {
719                         $users{$user} = [$name, $email];
720                 }
721         }
722         close $authors or croak $!;
725 # convert GetOpt::Long specs for use by git-config
726 sub read_repo_config {
727         return unless -d $ENV{GIT_DIR};
728         my $opts = shift;
729         my @config_only;
730         foreach my $o (keys %$opts) {
731                 # if we have mixedCase and a long option-only, then
732                 # it's a config-only variable that we don't need for
733                 # the command-line.
734                 push @config_only, $o if ($o =~ /[A-Z]/ && $o =~ /^[a-z]+$/i);
735                 my $v = $opts->{$o};
736                 my ($key) = ($o =~ /^([a-zA-Z\-]+)/);
737                 $key =~ s/-//g;
738                 my $arg = 'git-config';
739                 $arg .= ' --int' if ($o =~ /[:=]i$/);
740                 $arg .= ' --bool' if ($o !~ /[:=][sfi]$/);
741                 if (ref $v eq 'ARRAY') {
742                         chomp(my @tmp = `$arg --get-all svn.$key`);
743                         @$v = @tmp if @tmp;
744                 } else {
745                         chomp(my $tmp = `$arg --get svn.$key`);
746                         if ($tmp && !($arg =~ / --bool/ && $tmp eq 'false')) {
747                                 $$v = $tmp;
748                         }
749                 }
750         }
751         delete @$opts{@config_only} if @config_only;
754 sub extract_metadata {
755         my $id = shift or return (undef, undef, undef);
756         my ($url, $rev, $uuid) = ($id =~ /^git-svn-id:\s(\S+?)\@(\d+)
757                                                         \s([a-f\d\-]+)$/x);
758         if (!defined $rev || !$uuid || !$url) {
759                 # some of the original repositories I made had
760                 # identifiers like this:
761                 ($rev, $uuid) = ($id =~/^git-svn-id:\s(\d+)\@([a-f\d\-]+)/);
762         }
763         return ($url, $rev, $uuid);
766 sub cmt_metadata {
767         return extract_metadata((grep(/^git-svn-id: /,
768                 command(qw/cat-file commit/, shift)))[-1]);
771 sub working_head_info {
772         my ($head, $refs) = @_;
773         my ($url, $rev, $uuid);
774         my ($fh, $ctx) = command_output_pipe('rev-list', $head);
775         while (<$fh>) {
776                 chomp;
777                 ($url, $rev, $uuid) = cmt_metadata($_);
778                 last if (defined $url && defined $rev && defined $uuid);
779                 unshift @$refs, $_ if $refs;
780         }
781         close $fh; # break the pipe
782         ($url, $rev, $uuid);
785 package Git::SVN;
786 use strict;
787 use warnings;
788 use vars qw/$default_repo_id $default_ref_id $_no_metadata $_follow_parent
789             $_repack $_repack_flags $_use_svm_props $_head
790             $_use_svnsync_props $no_reuse_existing/;
791 use Carp qw/croak/;
792 use File::Path qw/mkpath/;
793 use File::Copy qw/copy/;
794 use IPC::Open3;
796 my $_repack_nr;
797 # properties that we do not log:
798 my %SKIP_PROP;
799 BEGIN {
800         %SKIP_PROP = map { $_ => 1 } qw/svn:wc:ra_dav:version-url
801                                         svn:special svn:executable
802                                         svn:entry:committed-rev
803                                         svn:entry:last-author
804                                         svn:entry:uuid
805                                         svn:entry:committed-date/;
807         # some options are read globally, but can be overridden locally
808         # per [svn-remote "..."] section.  Command-line options will *NOT*
809         # override options set in an [svn-remote "..."] section
810         my $e;
811         foreach (qw/follow_parent no_metadata use_svm_props
812                     use_svnsync_props/) {
813                 my $key = $_;
814                 $key =~ tr/_//d;
815                 $e .= "sub $_ {
816                         my (\$self) = \@_;
817                         return \$self->{-$_} if exists \$self->{-$_};
818                         my \$k = \"svn-remote.\$self->{repo_id}\.$key\";
819                         eval { command_oneline(qw/config --get/, \$k) };
820                         if (\$@) {
821                                 \$self->{-$_} = \$Git::SVN::_$_;
822                         } else {
823                                 my \$v = command_oneline(qw/config --bool/,\$k);
824                                 \$self->{-$_} = \$v eq 'false' ? 0 : 1;
825                         }
826                         return \$self->{-$_} }\n";
827         }
828         $e .= "1;\n";
829         eval $e or die $@;
832 my %LOCKFILES;
833 END { unlink keys %LOCKFILES if %LOCKFILES }
835 sub resolve_local_globs {
836         my ($url, $fetch, $glob_spec) = @_;
837         return unless defined $glob_spec;
838         my $ref = $glob_spec->{ref};
839         my $path = $glob_spec->{path};
840         foreach (command(qw#for-each-ref --format=%(refname) refs/remotes#)) {
841                 next unless m#^refs/remotes/$ref->{regex}$#;
842                 my $p = $1;
843                 my $pathname = $path->full_path($p);
844                 my $refname = $ref->full_path($p);
845                 if (my $existing = $fetch->{$pathname}) {
846                         if ($existing ne $refname) {
847                                 die "Refspec conflict:\n",
848                                     "existing: refs/remotes/$existing\n",
849                                     " globbed: refs/remotes/$refname\n";
850                         }
851                         my $u = (::cmt_metadata("refs/remotes/$refname"))[0];
852                         $u =~ s!^\Q$url\E(/|$)!! or die
853                           "refs/remotes/$refname: '$url' not found in '$u'\n";
854                         if ($pathname ne $u) {
855                                 warn "W: Refspec glob conflict ",
856                                      "(ref: refs/remotes/$refname):\n",
857                                      "expected path: $pathname\n",
858                                      "    real path: $u\n",
859                                      "Continuing ahead with $u\n";
860                                 next;
861                         }
862                 } else {
863                         $fetch->{$pathname} = $refname;
864                 }
865         }
868 sub parse_revision_argument {
869         my ($base, $head) = @_;
870         if (!defined $::_revision || $::_revision eq 'BASE:HEAD') {
871                 return ($base, $head);
872         }
873         return ($1, $2) if ($::_revision =~ /^(\d+):(\d+)$/);
874         return ($::_revision, $::_revision) if ($::_revision =~ /^\d+$/);
875         return ($head, $head) if ($::_revision eq 'HEAD');
876         return ($base, $1) if ($::_revision =~ /^BASE:(\d+)$/);
877         return ($1, $head) if ($::_revision =~ /^(\d+):HEAD$/);
878         die "revision argument: $::_revision not understood by git-svn\n";
881 sub fetch_all {
882         my ($repo_id, $remotes) = @_;
883         if (ref $repo_id) {
884                 my $gs = $repo_id;
885                 $repo_id = undef;
886                 $repo_id = $gs->{repo_id};
887         }
888         $remotes ||= read_all_remotes();
889         my $remote = $remotes->{$repo_id} or
890                      die "[svn-remote \"$repo_id\"] unknown\n";
891         my $fetch = $remote->{fetch};
892         my $url = $remote->{url} or die "svn-remote.$repo_id.url not defined\n";
893         my (@gs, @globs);
894         my $ra = Git::SVN::Ra->new($url);
895         my $uuid = $ra->get_uuid;
896         my $head = $ra->get_latest_revnum;
897         my $base = defined $fetch ? $head : 0;
899         # read the max revs for wildcard expansion (branches/*, tags/*)
900         foreach my $t (qw/branches tags/) {
901                 defined $remote->{$t} or next;
902                 push @globs, $remote->{$t};
903                 my $max_rev = eval { tmp_config(qw/--int --get/,
904                                          "svn-remote.$repo_id.${t}-maxRev") };
905                 if (defined $max_rev && ($max_rev < $base)) {
906                         $base = $max_rev;
907                 } elsif (!defined $max_rev) {
908                         $base = 0;
909                 }
910         }
912         if ($fetch) {
913                 foreach my $p (sort keys %$fetch) {
914                         my $gs = Git::SVN->new($fetch->{$p}, $repo_id, $p);
915                         my $lr = $gs->rev_db_max;
916                         if (defined $lr) {
917                                 $base = $lr if ($lr < $base);
918                         }
919                         push @gs, $gs;
920                 }
921         }
923         ($base, $head) = parse_revision_argument($base, $head);
924         $ra->gs_fetch_loop_common($base, $head, \@gs, \@globs);
927 sub read_all_remotes {
928         my $r = {};
929         foreach (grep { s/^svn-remote\.// } command(qw/config -l/)) {
930                 if (m!^(.+)\.fetch=\s*(.*)\s*:\s*refs/remotes/(.+)\s*$!) {
931                         $r->{$1}->{fetch}->{$2} = $3;
932                 } elsif (m!^(.+)\.url=\s*(.*)\s*$!) {
933                         $r->{$1}->{url} = $2;
934                 } elsif (m!^(.+)\.(branches|tags)=
935                            (.*):refs/remotes/(.+)\s*$/!x) {
936                         my ($p, $g) = ($3, $4);
937                         my $rs = $r->{$1}->{$2} = {
938                                           t => $2,
939                                           remote => $1,
940                                           path => Git::SVN::GlobSpec->new($p),
941                                           ref => Git::SVN::GlobSpec->new($g) };
942                         if (length($rs->{ref}->{right}) != 0) {
943                                 die "The '*' glob character must be the last ",
944                                     "character of '$g'\n";
945                         }
946                 }
947         }
948         $r;
951 sub init_vars {
952         if (defined $_repack) {
953                 $_repack = 1000 if ($_repack <= 0);
954                 $_repack_nr = $_repack;
955                 $_repack_flags ||= '-d';
956         }
959 sub verify_remotes_sanity {
960         return unless -d $ENV{GIT_DIR};
961         my %seen;
962         foreach (command(qw/config -l/)) {
963                 if (m!^svn-remote\.(?:.+)\.fetch=.*:refs/remotes/(\S+)\s*$!) {
964                         if ($seen{$1}) {
965                                 die "Remote ref refs/remote/$1 is tracked by",
966                                     "\n  \"$_\"\nand\n  \"$seen{$1}\"\n",
967                                     "Please resolve this ambiguity in ",
968                                     "your git configuration file before ",
969                                     "continuing\n";
970                         }
971                         $seen{$1} = $_;
972                 }
973         }
976 # we allow more chars than remotes2config.sh...
977 sub sanitize_remote_name {
978         my ($name) = @_;
979         $name =~ tr{A-Za-z0-9:,/+-}{.}c;
980         $name;
983 sub find_existing_remote {
984         my ($url, $remotes) = @_;
985         return undef if $no_reuse_existing;
986         my $existing;
987         foreach my $repo_id (keys %$remotes) {
988                 my $u = $remotes->{$repo_id}->{url} or next;
989                 next if $u ne $url;
990                 $existing = $repo_id;
991                 last;
992         }
993         $existing;
996 sub init_remote_config {
997         my ($self, $url, $no_write) = @_;
998         $url =~ s!/+$!!; # strip trailing slash
999         my $r = read_all_remotes();
1000         my $existing = find_existing_remote($url, $r);
1001         if ($existing) {
1002                 unless ($no_write) {
1003                         print STDERR "Using existing ",
1004                                      "[svn-remote \"$existing\"]\n";
1005                 }
1006                 $self->{repo_id} = $existing;
1007         } else {
1008                 my $min_url = Git::SVN::Ra->new($url)->minimize_url;
1009                 $existing = find_existing_remote($min_url, $r);
1010                 if ($existing) {
1011                         unless ($no_write) {
1012                                 print STDERR "Using existing ",
1013                                              "[svn-remote \"$existing\"]\n";
1014                         }
1015                         $self->{repo_id} = $existing;
1016                 }
1017                 if ($min_url ne $url) {
1018                         unless ($no_write) {
1019                                 print STDERR "Using higher level of URL: ",
1020                                              "$url => $min_url\n";
1021                         }
1022                         my $old_path = $self->{path};
1023                         $self->{path} = $url;
1024                         $self->{path} =~ s!^\Q$min_url\E(/|$)!!;
1025                         if (length $old_path) {
1026                                 $self->{path} .= "/$old_path";
1027                         }
1028                         $url = $min_url;
1029                 }
1030         }
1031         my $orig_url;
1032         if (!$existing) {
1033                 # verify that we aren't overwriting anything:
1034                 $orig_url = eval {
1035                         command_oneline('config', '--get',
1036                                         "svn-remote.$self->{repo_id}.url")
1037                 };
1038                 if ($orig_url && ($orig_url ne $url)) {
1039                         die "svn-remote.$self->{repo_id}.url already set: ",
1040                             "$orig_url\nwanted to set to: $url\n";
1041                 }
1042         }
1043         my ($xrepo_id, $xpath) = find_ref($self->refname);
1044         if (defined $xpath) {
1045                 die "svn-remote.$xrepo_id.fetch already set to track ",
1046                     "$xpath:refs/remotes/", $self->refname, "\n";
1047         }
1048         unless ($no_write) {
1049                 command_noisy('config',
1050                               "svn-remote.$self->{repo_id}.url", $url);
1051                 command_noisy('config', '--add',
1052                               "svn-remote.$self->{repo_id}.fetch",
1053                               "$self->{path}:".$self->refname);
1054         }
1055         $self->{url} = $url;
1058 sub find_by_url { # repos_root and, path are optional
1059         my ($class, $full_url, $repos_root, $path) = @_;
1060         return undef unless defined $full_url;
1061         my $remotes = read_all_remotes();
1062         if (defined $full_url && defined $repos_root && !defined $path) {
1063                 $path = $full_url;
1064                 $path =~ s#^\Q$repos_root\E(?:/|$)##;
1065         }
1066         foreach my $repo_id (keys %$remotes) {
1067                 my $u = $remotes->{$repo_id}->{url} or next;
1068                 next if defined $repos_root && $repos_root ne $u;
1070                 my $fetch = $remotes->{$repo_id}->{fetch} || {};
1071                 foreach (qw/branches tags/) {
1072                         resolve_local_globs($u, $fetch,
1073                                             $remotes->{$repo_id}->{$_});
1074                 }
1075                 my $p = $path;
1076                 unless (defined $p) {
1077                         $p = $full_url;
1078                         $p =~ s#^\Q$u\E(?:/|$)## or next;
1079                 }
1080                 foreach my $f (keys %$fetch) {
1081                         next if $f ne $p;
1082                         return Git::SVN->new($fetch->{$f}, $repo_id, $f);
1083                 }
1084         }
1085         undef;
1088 sub init {
1089         my ($class, $url, $path, $repo_id, $ref_id, $no_write) = @_;
1090         my $self = _new($class, $repo_id, $ref_id, $path);
1091         if (defined $url) {
1092                 $self->init_remote_config($url, $no_write);
1093         }
1094         $self;
1097 sub find_ref {
1098         my ($ref_id) = @_;
1099         foreach (command(qw/config -l/)) {
1100                 next unless m!^svn-remote\.(.+)\.fetch=
1101                               \s*(.*)\s*:\s*refs/remotes/(.+)\s*$!x;
1102                 my ($repo_id, $path, $ref) = ($1, $2, $3);
1103                 if ($ref eq $ref_id) {
1104                         $path = '' if ($path =~ m#^\./?#);
1105                         return ($repo_id, $path);
1106                 }
1107         }
1108         (undef, undef, undef);
1111 sub new {
1112         my ($class, $ref_id, $repo_id, $path) = @_;
1113         if (defined $ref_id && !defined $repo_id && !defined $path) {
1114                 ($repo_id, $path) = find_ref($ref_id);
1115                 if (!defined $repo_id) {
1116                         die "Could not find a \"svn-remote.*.fetch\" key ",
1117                             "in the repository configuration matching: ",
1118                             "refs/remotes/$ref_id\n";
1119                 }
1120         }
1121         my $self = _new($class, $repo_id, $ref_id, $path);
1122         if (!defined $self->{path} || !length $self->{path}) {
1123                 my $fetch = command_oneline('config', '--get',
1124                                             "svn-remote.$repo_id.fetch",
1125                                             ":refs/remotes/$ref_id\$") or
1126                      die "Failed to read \"svn-remote.$repo_id.fetch\" ",
1127                          "\":refs/remotes/$ref_id\$\" in config\n";
1128                 ($self->{path}, undef) = split(/\s*:\s*/, $fetch);
1129         }
1130         $self->{url} = command_oneline('config', '--get',
1131                                        "svn-remote.$repo_id.url") or
1132                   die "Failed to read \"svn-remote.$repo_id.url\" in config\n";
1133         $self->rebuild;
1134         $self;
1137 sub refname { "refs/remotes/$_[0]->{ref_id}" }
1139 sub svm_uuid {
1140         my ($self) = @_;
1141         return $self->{svm}->{uuid} if $self->svm;
1142         $self->ra;
1143         unless ($self->{svm}) {
1144                 die "SVM UUID not cached, and reading remotely failed\n";
1145         }
1146         $self->{svm}->{uuid};
1149 sub svm {
1150         my ($self) = @_;
1151         return $self->{svm} if $self->{svm};
1152         my $svm;
1153         # see if we have it in our config, first:
1154         eval {
1155                 my $section = "svn-remote.$self->{repo_id}";
1156                 $svm = {
1157                   source => tmp_config('--get', "$section.svm-source"),
1158                   uuid => tmp_config('--get', "$section.svm-uuid"),
1159                   replace => tmp_config('--get', "$section.svm-replace"),
1160                 }
1161         };
1162         if ($svm && $svm->{source} && $svm->{uuid} && $svm->{replace}) {
1163                 $self->{svm} = $svm;
1164         }
1165         $self->{svm};
1168 sub _set_svm_vars {
1169         my ($self, $ra) = @_;
1170         return $ra if $self->svm;
1172         my @err = ( "useSvmProps set, but failed to read SVM properties\n",
1173                     "(svm:source, svm:uuid) ",
1174                     "from the following URLs:\n" );
1175         sub read_svm_props {
1176                 my ($self, $ra, $path, $r) = @_;
1177                 my $props = ($ra->get_dir($path, $r))[2];
1178                 my $src = $props->{'svm:source'};
1179                 my $uuid = $props->{'svm:uuid'};
1180                 return undef if (!$src || !$uuid);
1182                 chomp($src, $uuid);
1184                 $uuid =~ m{^[0-9a-f\-]{30,}$}
1185                     or die "doesn't look right - svm:uuid is '$uuid'\n";
1187                 # the '!' is used to mark the repos_root!/relative/path
1188                 $src =~ s{/?!/?}{/};
1189                 $src =~ s{/+$}{}; # no trailing slashes please
1190                 # username is of no interest
1191                 $src =~ s{(^[a-z\+]*://)[^/@]*@}{$1};
1193                 my $replace = $ra->{url};
1194                 $replace .= "/$path" if length $path;
1196                 my $section = "svn-remote.$self->{repo_id}";
1197                 tmp_config("$section.svm-source", $src);
1198                 tmp_config("$section.svm-replace", $replace);
1199                 tmp_config("$section.svm-uuid", $uuid);
1200                 $self->{svm} = {
1201                         source => $src,
1202                         uuid => $uuid,
1203                         replace => $replace
1204                 };
1205         }
1207         my $r = $ra->get_latest_revnum;
1208         my $path = $self->{path};
1209         my %tried;
1210         while (length $path) {
1211                 unless ($tried{"$self->{url}/$path"}) {
1212                         return $ra if $self->read_svm_props($ra, $path, $r);
1213                         $tried{"$self->{url}/$path"} = 1;
1214                 }
1215                 $path =~ s#/?[^/]+$##;
1216         }
1217         die "Path: '$path' should be ''\n" if $path ne '';
1218         return $ra if $self->read_svm_props($ra, $path, $r);
1219         $tried{"$self->{url}/$path"} = 1;
1221         if ($ra->{repos_root} eq $self->{url}) {
1222                 die @err, (map { "  $_\n" } keys %tried), "\n";
1223         }
1225         # nope, make sure we're connected to the repository root:
1226         my $ok;
1227         my @tried_b;
1228         $path = $ra->{svn_path};
1229         $ra = Git::SVN::Ra->new($ra->{repos_root});
1230         while (length $path) {
1231                 unless ($tried{"$ra->{url}/$path"}) {
1232                         $ok = $self->read_svm_props($ra, $path, $r);
1233                         last if $ok;
1234                         $tried{"$ra->{url}/$path"} = 1;
1235                 }
1236                 $path =~ s#/?[^/]+$##;
1237         }
1238         die "Path: '$path' should be ''\n" if $path ne '';
1239         $ok ||= $self->read_svm_props($ra, $path, $r);
1240         $tried{"$ra->{url}/$path"} = 1;
1241         if (!$ok) {
1242                 die @err, (map { "  $_\n" } keys %tried), "\n";
1243         }
1244         Git::SVN::Ra->new($self->{url});
1247 sub svnsync {
1248         my ($self) = @_;
1249         return $self->{svnsync} if $self->{svnsync};
1251         if ($self->no_metadata) {
1252                 die "Can't have both 'noMetadata' and ",
1253                     "'useSvnsyncProps' options set!\n";
1254         }
1255         if ($self->rewrite_root) {
1256                 die "Can't have both 'useSvnsyncProps' and 'rewriteRoot' ",
1257                     "options set!\n";
1258         }
1260         my $svnsync;
1261         # see if we have it in our config, first:
1262         eval {
1263                 my $section = "svn-remote.$self->{repo_id}";
1264                 $svnsync = {
1265                   url => tmp_config('--get', "$section.svnsync-url"),
1266                   uuid => tmp_config('--get', "$section.svnsync-uuid"),
1267                 }
1268         };
1269         if ($svnsync && $svnsync->{url} && $svnsync->{uuid}) {
1270                 return $self->{svnsync} = $svnsync;
1271         }
1273         my $err = "useSvnsyncProps set, but failed to read " .
1274                   "svnsync property: svn:sync-from-";
1275         my $rp = $self->ra->rev_proplist(0);
1277         my $url = $rp->{'svn:sync-from-url'} or die $err . "url\n";
1278         $url =~ m{^[a-z\+]+://} or
1279                    die "doesn't look right - svn:sync-from-url is '$url'\n";
1281         my $uuid = $rp->{'svn:sync-from-uuid'} or die $err . "uuid\n";
1282         $uuid =~ m{^[0-9a-f\-]{30,}$} or
1283                    die "doesn't look right - svn:sync-from-uuid is '$uuid'\n";
1285         my $section = "svn-remote.$self->{repo_id}";
1286         tmp_config('--add', "$section.svnsync-uuid", $uuid);
1287         tmp_config('--add', "$section.svnsync-url", $url);
1288         return $self->{svnsync} = { url => $url, uuid => $uuid };
1291 # this allows us to memoize our SVN::Ra UUID locally and avoid a
1292 # remote lookup (useful for 'git svn log').
1293 sub ra_uuid {
1294         my ($self) = @_;
1295         unless ($self->{ra_uuid}) {
1296                 my $key = "svn-remote.$self->{repo_id}.uuid";
1297                 my $uuid = eval { tmp_config('--get', $key) };
1298                 if (!$@ && $uuid && $uuid =~ /^([a-f\d\-]{30,})$/) {
1299                         $self->{ra_uuid} = $uuid;
1300                 } else {
1301                         die "ra_uuid called without URL\n" unless $self->{url};
1302                         $self->{ra_uuid} = $self->ra->get_uuid;
1303                         tmp_config('--add', $key, $self->{ra_uuid});
1304                 }
1305         }
1306         $self->{ra_uuid};
1309 sub ra {
1310         my ($self) = shift;
1311         my $ra = Git::SVN::Ra->new($self->{url});
1312         if ($self->use_svm_props && !$self->{svm}) {
1313                 if ($self->no_metadata) {
1314                         die "Can't have both 'noMetadata' and ",
1315                             "'useSvmProps' options set!\n";
1316                 } elsif ($self->use_svnsync_props) {
1317                         die "Can't have both 'useSvnsyncProps' and ",
1318                             "'useSvmProps' options set!\n";
1319                 }
1320                 $ra = $self->_set_svm_vars($ra);
1321                 $self->{-want_revprops} = 1;
1322         }
1323         $ra;
1326 sub rel_path {
1327         my ($self) = @_;
1328         my $repos_root = $self->ra->{repos_root};
1329         return $self->{path} if ($self->{url} eq $repos_root);
1330         my $url = $self->{url} .
1331                   (length $self->{path} ? "/$self->{path}" : $self->{path});
1332         $url =~ s!^\Q$repos_root\E(?:/+|$)!!g;
1333         $url;
1336 sub traverse_ignore {
1337         my ($self, $fh, $path, $r) = @_;
1338         $path =~ s#^/+##g;
1339         my $ra = $self->ra;
1340         my ($dirent, undef, $props) = $ra->get_dir($path, $r);
1341         my $p = $path;
1342         $p =~ s#^\Q$self->{path}\E(/|$)##;
1343         print $fh length $p ? "\n# $p\n" : "\n# /\n";
1344         if (my $s = $props->{'svn:ignore'}) {
1345                 $s =~ s/[\r\n]+/\n/g;
1346                 chomp $s;
1347                 if (length $p == 0) {
1348                         $s =~ s#\n#\n/$p#g;
1349                         print $fh "/$s\n";
1350                 } else {
1351                         $s =~ s#\n#\n/$p/#g;
1352                         print $fh "/$p/$s\n";
1353                 }
1354         }
1355         foreach (sort keys %$dirent) {
1356                 next if $dirent->{$_}->kind != $SVN::Node::dir;
1357                 $self->traverse_ignore($fh, "$path/$_", $r);
1358         }
1361 sub last_rev { ($_[0]->last_rev_commit)[0] }
1362 sub last_commit { ($_[0]->last_rev_commit)[1] }
1364 # returns the newest SVN revision number and newest commit SHA1
1365 sub last_rev_commit {
1366         my ($self) = @_;
1367         if (defined $self->{last_rev} && defined $self->{last_commit}) {
1368                 return ($self->{last_rev}, $self->{last_commit});
1369         }
1370         my $c = ::verify_ref($self->refname.'^0');
1371         if ($c && !$self->use_svm_props && !$self->no_metadata) {
1372                 my $rev = (::cmt_metadata($c))[1];
1373                 if (defined $rev) {
1374                         ($self->{last_rev}, $self->{last_commit}) = ($rev, $c);
1375                         return ($rev, $c);
1376                 }
1377         }
1378         my $db_path = $self->db_path;
1379         unless (-e $db_path) {
1380                 ($self->{last_rev}, $self->{last_commit}) = (undef, undef);
1381                 return (undef, undef);
1382         }
1383         my $offset = -41; # from tail
1384         my $rl;
1385         open my $fh, '<', $db_path or croak "$db_path not readable: $!\n";
1386         sysseek($fh, $offset, 2); # don't care for errors
1387         sysread($fh, $rl, 41) == 41 or return (undef, undef);
1388         chomp $rl;
1389         while (('0' x40) eq $rl && sysseek($fh, 0, 1) != 0) {
1390                 $offset -= 41;
1391                 sysseek($fh, $offset, 2); # don't care for errors
1392                 sysread($fh, $rl, 41) == 41 or return (undef, undef);
1393                 chomp $rl;
1394         }
1395         if ($c && $c ne $rl) {
1396                 die "$db_path and ", $self->refname,
1397                     " inconsistent!:\n$c != $rl\n";
1398         }
1399         my $rev = sysseek($fh, 0, 1) or croak $!;
1400         $rev =  ($rev - 41) / 41;
1401         close $fh or croak $!;
1402         ($self->{last_rev}, $self->{last_commit}) = ($rev, $c);
1403         return ($rev, $c);
1406 sub get_fetch_range {
1407         my ($self, $min, $max) = @_;
1408         $max ||= $self->ra->get_latest_revnum;
1409         $min ||= $self->rev_db_max;
1410         (++$min, $max);
1413 sub tmp_config {
1414         my (@args) = @_;
1415         my $old_def_config = "$ENV{GIT_DIR}/svn/config";
1416         my $config = "$ENV{GIT_DIR}/svn/.metadata";
1417         if (-e $old_def_config && ! -e $config) {
1418                 rename $old_def_config, $config or
1419                        die "Failed rename $old_def_config => $config: $!\n";
1420         }
1421         my $old_config = $ENV{GIT_CONFIG};
1422         $ENV{GIT_CONFIG} = $config;
1423         $@ = undef;
1424         my @ret = eval {
1425                 unless (-f $config) {
1426                         mkfile($config);
1427                         open my $fh, '>', $config or
1428                             die "Can't open $config: $!\n";
1429                         print $fh "; This file is used internally by ",
1430                                   "git-svn\n" or die
1431                                   "Couldn't write to $config: $!\n";
1432                         print $fh "; You should not have to edit it\n" or
1433                               die "Couldn't write to $config: $!\n";
1434                         close $fh or die "Couldn't close $config: $!\n";
1435                 }
1436                 command('config', @args);
1437         };
1438         my $err = $@;
1439         if (defined $old_config) {
1440                 $ENV{GIT_CONFIG} = $old_config;
1441         } else {
1442                 delete $ENV{GIT_CONFIG};
1443         }
1444         die $err if $err;
1445         wantarray ? @ret : $ret[0];
1448 sub tmp_index_do {
1449         my ($self, $sub) = @_;
1450         my $old_index = $ENV{GIT_INDEX_FILE};
1451         $ENV{GIT_INDEX_FILE} = $self->{index};
1452         $@ = undef;
1453         my @ret = eval {
1454                 my ($dir, $base) = ($self->{index} =~ m#^(.*?)/?([^/]+)$#);
1455                 mkpath([$dir]) unless -d $dir;
1456                 &$sub;
1457         };
1458         my $err = $@;
1459         if (defined $old_index) {
1460                 $ENV{GIT_INDEX_FILE} = $old_index;
1461         } else {
1462                 delete $ENV{GIT_INDEX_FILE};
1463         }
1464         die $err if $err;
1465         wantarray ? @ret : $ret[0];
1468 sub assert_index_clean {
1469         my ($self, $treeish) = @_;
1471         $self->tmp_index_do(sub {
1472                 command_noisy('read-tree', $treeish) unless -e $self->{index};
1473                 my $x = command_oneline('write-tree');
1474                 my ($y) = (command(qw/cat-file commit/, $treeish) =~
1475                            /^tree ($::sha1)/mo);
1476                 return if $y eq $x;
1478                 warn "Index mismatch: $y != $x\nrereading $treeish\n";
1479                 unlink $self->{index} or die "unlink $self->{index}: $!\n";
1480                 command_noisy('read-tree', $treeish);
1481                 $x = command_oneline('write-tree');
1482                 if ($y ne $x) {
1483                         ::fatal "trees ($treeish) $y != $x\n",
1484                                 "Something is seriously wrong...\n";
1485                 }
1486         });
1489 sub get_commit_parents {
1490         my ($self, $log_entry) = @_;
1491         my (%seen, @ret, @tmp);
1492         # legacy support for 'set-tree'; this is only used by set_tree_cb:
1493         if (my $ip = $self->{inject_parents}) {
1494                 if (my $commit = delete $ip->{$log_entry->{revision}}) {
1495                         push @tmp, $commit;
1496                 }
1497         }
1498         if (my $cur = ::verify_ref($self->refname.'^0')) {
1499                 push @tmp, $cur;
1500         }
1501         push @tmp, $_ foreach (@{$log_entry->{parents}}, @tmp);
1502         while (my $p = shift @tmp) {
1503                 next if $seen{$p};
1504                 $seen{$p} = 1;
1505                 push @ret, $p;
1506                 # MAXPARENT is defined to 16 in commit-tree.c:
1507                 last if @ret >= 16;
1508         }
1509         if (@tmp) {
1510                 die "r$log_entry->{revision}: No room for parents:\n\t",
1511                     join("\n\t", @tmp), "\n";
1512         }
1513         @ret;
1516 sub rewrite_root {
1517         my ($self) = @_;
1518         return $self->{-rewrite_root} if exists $self->{-rewrite_root};
1519         my $k = "svn-remote.$self->{repo_id}.rewriteRoot";
1520         my $rwr = eval { command_oneline(qw/config --get/, $k) };
1521         if ($rwr) {
1522                 $rwr =~ s#/+$##;
1523                 if ($rwr !~ m#^[a-z\+]+://#) {
1524                         die "$rwr is not a valid URL (key: $k)\n";
1525                 }
1526         }
1527         $self->{-rewrite_root} = $rwr;
1530 sub metadata_url {
1531         my ($self) = @_;
1532         ($self->rewrite_root || $self->{url}) .
1533            (length $self->{path} ? '/' . $self->{path} : '');
1536 sub full_url {
1537         my ($self) = @_;
1538         $self->{url} . (length $self->{path} ? '/' . $self->{path} : '');
1541 sub do_git_commit {
1542         my ($self, $log_entry) = @_;
1543         my $lr = $self->last_rev;
1544         if (defined $lr && $lr >= $log_entry->{revision}) {
1545                 die "Last fetched revision of ", $self->refname,
1546                     " was r$lr, but we are about to fetch: ",
1547                     "r$log_entry->{revision}!\n";
1548         }
1549         if (my $c = $self->rev_db_get($log_entry->{revision})) {
1550                 croak "$log_entry->{revision} = $c already exists! ",
1551                       "Why are we refetching it?\n";
1552         }
1553         $ENV{GIT_AUTHOR_NAME} = $ENV{GIT_COMMITTER_NAME} = $log_entry->{name};
1554         $ENV{GIT_AUTHOR_EMAIL} = $ENV{GIT_COMMITTER_EMAIL} =
1555                                                           $log_entry->{email};
1556         $ENV{GIT_AUTHOR_DATE} = $ENV{GIT_COMMITTER_DATE} = $log_entry->{date};
1558         my $tree = $log_entry->{tree};
1559         if (!defined $tree) {
1560                 $tree = $self->tmp_index_do(sub {
1561                                             command_oneline('write-tree') });
1562         }
1563         die "Tree is not a valid sha1: $tree\n" if $tree !~ /^$::sha1$/o;
1565         my @exec = ('git-commit-tree', $tree);
1566         foreach ($self->get_commit_parents($log_entry)) {
1567                 push @exec, '-p', $_;
1568         }
1569         defined(my $pid = open3(my $msg_fh, my $out_fh, '>&STDERR', @exec))
1570                                                                    or croak $!;
1571         print $msg_fh $log_entry->{log} or croak $!;
1572         unless ($self->no_metadata) {
1573                 print $msg_fh "\ngit-svn-id: $log_entry->{metadata}\n"
1574                               or croak $!;
1575         }
1576         $msg_fh->flush == 0 or croak $!;
1577         close $msg_fh or croak $!;
1578         chomp(my $commit = do { local $/; <$out_fh> });
1579         close $out_fh or croak $!;
1580         waitpid $pid, 0;
1581         croak $? if $?;
1582         if ($commit !~ /^$::sha1$/o) {
1583                 die "Failed to commit, invalid sha1: $commit\n";
1584         }
1586         $self->rev_db_set($log_entry->{revision}, $commit, 1);
1588         $self->{last_rev} = $log_entry->{revision};
1589         $self->{last_commit} = $commit;
1590         print "r$log_entry->{revision}";
1591         if (defined $log_entry->{svm_revision}) {
1592                  print " (\@$log_entry->{svm_revision})";
1593                  $self->rev_db_set($log_entry->{svm_revision}, $commit,
1594                                    0, $self->svm_uuid);
1595         }
1596         print " = $commit ($self->{ref_id})\n";
1597         if (defined $_repack && (--$_repack_nr == 0)) {
1598                 $_repack_nr = $_repack;
1599                 # repack doesn't use any arguments with spaces in them, does it?
1600                 print "Running git repack $_repack_flags ...\n";
1601                 command_noisy('repack', split(/\s+/, $_repack_flags));
1602                 print "Done repacking\n";
1603         }
1604         return $commit;
1607 sub match_paths {
1608         my ($self, $paths, $r) = @_;
1609         return 1 if $self->{path} eq '';
1610         if (my $path = $paths->{"/$self->{path}"}) {
1611                 return ($path->{action} eq 'D') ? 0 : 1;
1612         }
1613         $self->{path_regex} ||= qr/^\/\Q$self->{path}\E\//;
1614         if (grep /$self->{path_regex}/, keys %$paths) {
1615                 return 1;
1616         }
1617         my $c = '';
1618         foreach (split m#/#, $self->{path}) {
1619                 $c .= "/$_";
1620                 next unless ($paths->{$c} &&
1621                              ($paths->{$c}->{action} =~ /^[AR]$/));
1622                 if ($self->ra->check_path($self->{path}, $r) ==
1623                     $SVN::Node::dir) {
1624                         return 1;
1625                 }
1626         }
1627         return 0;
1630 sub find_parent_branch {
1631         my ($self, $paths, $rev) = @_;
1632         return undef unless $self->follow_parent;
1633         unless (defined $paths) {
1634                 my $err_handler = $SVN::Error::handler;
1635                 $SVN::Error::handler = \&Git::SVN::Ra::skip_unknown_revs;
1636                 $self->ra->get_log([$self->{path}], $rev, $rev, 0, 1, 1, sub {
1637                                    $paths =
1638                                       Git::SVN::Ra::dup_changed_paths($_[0]) });
1639                 $SVN::Error::handler = $err_handler;
1640         }
1641         return undef unless defined $paths;
1643         # look for a parent from another branch:
1644         my @b_path_components = split m#/#, $self->rel_path;
1645         my @a_path_components;
1646         my $i;
1647         while (@b_path_components) {
1648                 $i = $paths->{'/'.join('/', @b_path_components)};
1649                 last if $i && defined $i->{copyfrom_path};
1650                 unshift(@a_path_components, pop(@b_path_components));
1651         }
1652         return undef unless defined $i && defined $i->{copyfrom_path};
1653         my $branch_from = $i->{copyfrom_path};
1654         if (@a_path_components) {
1655                 print STDERR "branch_from: $branch_from => ";
1656                 $branch_from .= '/'.join('/', @a_path_components);
1657                 print STDERR $branch_from, "\n";
1658         }
1659         my $r = $i->{copyfrom_rev};
1660         my $repos_root = $self->ra->{repos_root};
1661         my $url = $self->ra->{url};
1662         my $new_url = $repos_root . $branch_from;
1663         print STDERR  "Found possible branch point: ",
1664                       "$new_url => ", $self->full_url, ", $r\n";
1665         $branch_from =~ s#^/##;
1666         my $gs = Git::SVN->find_by_url($new_url, $repos_root, $branch_from);
1667         unless ($gs) {
1668                 my $ref_id = $self->{ref_id};
1669                 $ref_id =~ s/\@\d+$//;
1670                 $ref_id .= "\@$r";
1671                 # just grow a tail if we're not unique enough :x
1672                 $ref_id .= '-' while find_ref($ref_id);
1673                 print STDERR "Initializing parent: $ref_id\n";
1674                 $gs = Git::SVN->init($new_url, '', $ref_id, $ref_id, 1);
1675         }
1676         my ($r0, $parent) = $gs->find_rev_before($r, 1);
1677         if (!defined $r0 || !defined $parent) {
1678                 $gs->fetch(0, $r);
1679                 ($r0, $parent) = $gs->last_rev_commit;
1680         }
1681         if (defined $r0 && defined $parent) {
1682                 print STDERR "Found branch parent: ($self->{ref_id}) $parent\n";
1683                 my $ed;
1684                 if ($self->ra->can_do_switch) {
1685                         $self->assert_index_clean($parent);
1686                         print STDERR "Following parent with do_switch\n";
1687                         # do_switch works with svn/trunk >= r22312, but that
1688                         # is not included with SVN 1.4.3 (the latest version
1689                         # at the moment), so we can't rely on it
1690                         $self->{last_commit} = $parent;
1691                         $ed = SVN::Git::Fetcher->new($self);
1692                         $gs->ra->gs_do_switch($r0, $rev, $gs,
1693                                               $self->full_url, $ed)
1694                           or die "SVN connection failed somewhere...\n";
1695                 } else {
1696                         print STDERR "Following parent with do_update\n";
1697                         $ed = SVN::Git::Fetcher->new($self);
1698                         $self->ra->gs_do_update($rev, $rev, $self, $ed)
1699                           or die "SVN connection failed somewhere...\n";
1700                 }
1701                 print STDERR "Successfully followed parent\n";
1702                 return $self->make_log_entry($rev, [$parent], $ed);
1703         }
1704         return undef;
1707 sub do_fetch {
1708         my ($self, $paths, $rev) = @_;
1709         my $ed;
1710         my ($last_rev, @parents);
1711         if (my $lc = $self->last_commit) {
1712                 # we can have a branch that was deleted, then re-added
1713                 # under the same name but copied from another path, in
1714                 # which case we'll have multiple parents (we don't
1715                 # want to break the original ref, nor lose copypath info):
1716                 if (my $log_entry = $self->find_parent_branch($paths, $rev)) {
1717                         push @{$log_entry->{parents}}, $lc;
1718                         return $log_entry;
1719                 }
1720                 $ed = SVN::Git::Fetcher->new($self);
1721                 $last_rev = $self->{last_rev};
1722                 $ed->{c} = $lc;
1723                 @parents = ($lc);
1724         } else {
1725                 $last_rev = $rev;
1726                 if (my $log_entry = $self->find_parent_branch($paths, $rev)) {
1727                         return $log_entry;
1728                 }
1729                 $ed = SVN::Git::Fetcher->new($self);
1730         }
1731         unless ($self->ra->gs_do_update($last_rev, $rev, $self, $ed)) {
1732                 die "SVN connection failed somewhere...\n";
1733         }
1734         $self->make_log_entry($rev, \@parents, $ed);
1737 sub get_untracked {
1738         my ($self, $ed) = @_;
1739         my @out;
1740         my $h = $ed->{empty};
1741         foreach (sort keys %$h) {
1742                 my $act = $h->{$_} ? '+empty_dir' : '-empty_dir';
1743                 push @out, "  $act: " . uri_encode($_);
1744                 warn "W: $act: $_\n";
1745         }
1746         foreach my $t (qw/dir_prop file_prop/) {
1747                 $h = $ed->{$t} or next;
1748                 foreach my $path (sort keys %$h) {
1749                         my $ppath = $path eq '' ? '.' : $path;
1750                         foreach my $prop (sort keys %{$h->{$path}}) {
1751                                 next if $SKIP_PROP{$prop};
1752                                 my $v = $h->{$path}->{$prop};
1753                                 my $t_ppath_prop = "$t: " .
1754                                                     uri_encode($ppath) . ' ' .
1755                                                     uri_encode($prop);
1756                                 if (defined $v) {
1757                                         push @out, "  +$t_ppath_prop " .
1758                                                    uri_encode($v);
1759                                 } else {
1760                                         push @out, "  -$t_ppath_prop";
1761                                 }
1762                         }
1763                 }
1764         }
1765         foreach my $t (qw/absent_file absent_directory/) {
1766                 $h = $ed->{$t} or next;
1767                 foreach my $parent (sort keys %$h) {
1768                         foreach my $path (sort @{$h->{$parent}}) {
1769                                 push @out, "  $t: " .
1770                                            uri_encode("$parent/$path");
1771                                 warn "W: $t: $parent/$path ",
1772                                      "Insufficient permissions?\n";
1773                         }
1774                 }
1775         }
1776         \@out;
1779 sub parse_svn_date {
1780         my $date = shift || return '+0000 1970-01-01 00:00:00';
1781         my ($Y,$m,$d,$H,$M,$S) = ($date =~ /^(\d{4})\-(\d\d)\-(\d\d)T
1782                                             (\d\d)\:(\d\d)\:(\d\d).\d+Z$/x) or
1783                                          croak "Unable to parse date: $date\n";
1784         "+0000 $Y-$m-$d $H:$M:$S";
1787 sub check_author {
1788         my ($author) = @_;
1789         if (!defined $author || length $author == 0) {
1790                 $author = '(no author)';
1791         }
1792         if (defined $::_authors && ! defined $::users{$author}) {
1793                 die "Author: $author not defined in $::_authors file\n";
1794         }
1795         $author;
1798 sub make_log_entry {
1799         my ($self, $rev, $parents, $ed) = @_;
1800         my $untracked = $self->get_untracked($ed);
1802         open my $un, '>>', "$self->{dir}/unhandled.log" or croak $!;
1803         print $un "r$rev\n" or croak $!;
1804         print $un $_, "\n" foreach @$untracked;
1805         my %log_entry = ( parents => $parents || [], revision => $rev,
1806                           log => '');
1808         my $headrev;
1809         my $logged = delete $self->{logged_rev_props};
1810         if (!$logged || $self->{-want_revprops}) {
1811                 my $rp = $self->ra->rev_proplist($rev);
1812                 foreach (sort keys %$rp) {
1813                         my $v = $rp->{$_};
1814                         if (/^svn:(author|date|log)$/) {
1815                                 $log_entry{$1} = $v;
1816                         } elsif ($_ eq 'svm:headrev') {
1817                                 $headrev = $v;
1818                         } else {
1819                                 print $un "  rev_prop: ", uri_encode($_), ' ',
1820                                           uri_encode($v), "\n";
1821                         }
1822                 }
1823         } else {
1824                 map { $log_entry{$_} = $logged->{$_} } keys %$logged;
1825         }
1826         close $un or croak $!;
1828         $log_entry{date} = parse_svn_date($log_entry{date});
1829         $log_entry{log} .= "\n";
1830         my $author = $log_entry{author} = check_author($log_entry{author});
1831         my ($name, $email) = defined $::users{$author} ? @{$::users{$author}}
1832                                                        : ($author, undef);
1833         if (defined $headrev && $self->use_svm_props) {
1834                 if ($self->rewrite_root) {
1835                         die "Can't have both 'useSvmProps' and 'rewriteRoot' ",
1836                             "options set!\n";
1837                 }
1838                 my ($uuid, $r) = $headrev =~ m{^([a-f\d\-]{30,}):(\d+)$};
1839                 # we don't want "SVM: initializing mirror for junk" ...
1840                 return undef if $r == 0;
1841                 my $svm = $self->svm;
1842                 if ($uuid ne $svm->{uuid}) {
1843                         die "UUID mismatch on SVM path:\n",
1844                             "expected: $svm->{uuid}\n",
1845                             "     got: $uuid\n";
1846                 }
1847                 my $full_url = $self->full_url;
1848                 $full_url =~ s#^\Q$svm->{replace}\E(/|$)#$svm->{source}$1# or
1849                              die "Failed to replace '$svm->{replace}' with ",
1850                                  "'$svm->{source}' in $full_url\n";
1851                 # throw away username for storing in records
1852                 remove_username($full_url);
1853                 $log_entry{metadata} = "$full_url\@$r $uuid";
1854                 $log_entry{svm_revision} = $r;
1855                 $email ||= "$author\@$uuid"
1856         } elsif ($self->use_svnsync_props) {
1857                 my $full_url = $self->svnsync->{url};
1858                 $full_url .= "/$self->{path}" if length $self->{path};
1859                 my $uuid = $self->svnsync->{uuid};
1860                 $log_entry{metadata} = "$full_url\@$rev $uuid";
1861                 $email ||= "$author\@$uuid"
1862         } else {
1863                 $log_entry{metadata} = $self->metadata_url. "\@$rev " .
1864                                        $self->ra->get_uuid;
1865                 $email ||= "$author\@" . $self->ra->get_uuid;
1866         }
1867         $log_entry{name} = $name;
1868         $log_entry{email} = $email;
1869         \%log_entry;
1872 sub fetch {
1873         my ($self, $min_rev, $max_rev, @parents) = @_;
1874         my ($last_rev, $last_commit) = $self->last_rev_commit;
1875         my ($base, $head) = $self->get_fetch_range($min_rev, $max_rev);
1876         $self->ra->gs_fetch_loop_common($base, $head, [$self]);
1879 sub set_tree_cb {
1880         my ($self, $log_entry, $tree, $rev, $date, $author) = @_;
1881         $self->{inject_parents} = { $rev => $tree };
1882         $self->fetch(undef, undef);
1885 sub set_tree {
1886         my ($self, $tree) = (shift, shift);
1887         my $log_entry = ::get_commit_entry($tree);
1888         unless ($self->{last_rev}) {
1889                 fatal("Must have an existing revision to commit\n");
1890         }
1891         my %ed_opts = ( r => $self->{last_rev},
1892                         log => $log_entry->{log},
1893                         ra => $self->ra,
1894                         tree_a => $self->{last_commit},
1895                         tree_b => $tree,
1896                         editor_cb => sub {
1897                                $self->set_tree_cb($log_entry, $tree, @_) },
1898                         svn_path => $self->{path} );
1899         if (!SVN::Git::Editor->new(\%ed_opts)->apply_diff) {
1900                 print "No changes\nr$self->{last_rev} = $tree\n";
1901         }
1904 sub rebuild {
1905         my ($self) = @_;
1906         my $db_path = $self->db_path;
1907         return if (-e $db_path && ! -z $db_path);
1908         return unless ::verify_ref($self->refname.'^0');
1909         if (-f $self->{db_root}) {
1910                 rename $self->{db_root}, $db_path or die
1911                      "rename $self->{db_root} => $db_path failed: $!\n";
1912                 my ($dir, $base) = ($db_path =~ m#^(.*?)/?([^/]+)$#);
1913                 symlink $base, $self->{db_root} or die
1914                      "symlink $base => $self->{db_root} failed: $!\n";
1915                 return;
1916         }
1917         print "Rebuilding $db_path ...\n";
1918         my ($rev_list, $ctx) = command_output_pipe("rev-list", $self->refname);
1919         my $latest;
1920         my $full_url = $self->full_url;
1921         remove_username($full_url);
1922         my $svn_uuid;
1923         while (<$rev_list>) {
1924                 chomp;
1925                 my $c = $_;
1926                 die "Non-SHA1: $c\n" unless $c =~ /^$::sha1$/o;
1927                 my ($url, $rev, $uuid) = ::cmt_metadata($c);
1928                 remove_username($url);
1930                 # ignore merges (from set-tree)
1931                 next if (!defined $rev || !$uuid);
1933                 # if we merged or otherwise started elsewhere, this is
1934                 # how we break out of it
1935                 if ((defined $svn_uuid && ($uuid ne $svn_uuid)) ||
1936                     ($full_url && $url && ($url ne $full_url))) {
1937                         next;
1938                 }
1939                 $latest ||= $rev;
1940                 $svn_uuid ||= $uuid;
1942                 $self->rev_db_set($rev, $c);
1943                 print "r$rev = $c\n";
1944         }
1945         command_close_pipe($rev_list, $ctx);
1946         print "Done rebuilding $db_path\n";
1949 # rev_db:
1950 # Tie::File seems to be prone to offset errors if revisions get sparse,
1951 # it's not that fast, either.  Tie::File is also not in Perl 5.6.  So
1952 # one of my favorite modules is out :<  Next up would be one of the DBM
1953 # modules, but I'm not sure which is most portable...  So I'll just
1954 # go with something that's plain-text, but still capable of
1955 # being randomly accessed.  So here's my ultra-simple fixed-width
1956 # database.  All records are 40 characters + "\n", so it's easy to seek
1957 # to a revision: (41 * rev) is the byte offset.
1958 # A record of 40 0s denotes an empty revision.
1959 # And yes, it's still pretty fast (faster than Tie::File).
1960 # These files are disposable unless noMetadata or useSvmProps is set
1962 sub _rev_db_set {
1963         my ($fh, $rev, $commit) = @_;
1964         my $offset = $rev * 41;
1965         # assume that append is the common case:
1966         seek $fh, 0, 2 or croak $!;
1967         my $pos = tell $fh;
1968         if ($pos < $offset) {
1969                 for (1 .. (($offset - $pos) / 41)) {
1970                         print $fh (('0' x 40),"\n") or croak $!;
1971                 }
1972         }
1973         seek $fh, $offset, 0 or croak $!;
1974         print $fh $commit,"\n" or croak $!;
1977 sub mkfile {
1978         my ($path) = @_;
1979         unless (-e $path) {
1980                 my ($dir, $base) = ($path =~ m#^(.*?)/?([^/]+)$#);
1981                 mkpath([$dir]) unless -d $dir;
1982                 open my $fh, '>>', $path or die "Couldn't create $path: $!\n";
1983                 close $fh or die "Couldn't close (create) $path: $!\n";
1984         }
1987 sub rev_db_set {
1988         my ($self, $rev, $commit, $update_ref, $uuid) = @_;
1989         length $commit == 40 or die "arg3 must be a full SHA1 hexsum\n";
1990         my $db = $self->db_path($uuid);
1991         my $db_lock = "$db.lock";
1992         my $sig;
1993         if ($update_ref) {
1994                 $SIG{INT} = $SIG{HUP} = $SIG{TERM} = $SIG{ALRM} = $SIG{PIPE} =
1995                             $SIG{USR1} = $SIG{USR2} = sub { $sig = $_[0] };
1996         }
1997         mkfile($db);
1999         $LOCKFILES{$db_lock} = 1;
2000         my $sync;
2001         # both of these options make our .rev_db file very, very important
2002         # and we can't afford to lose it because rebuild() won't work
2003         if ($self->use_svm_props || $self->no_metadata) {
2004                 $sync = 1;
2005                 copy($db, $db_lock) or die "rev_db_set(@_): ",
2006                                            "Failed to copy: ",
2007                                            "$db => $db_lock ($!)\n";
2008         } else {
2009                 rename $db, $db_lock or die "rev_db_set(@_): ",
2010                                             "Failed to rename: ",
2011                                             "$db => $db_lock ($!)\n";
2012         }
2013         open my $fh, '+<', $db_lock or die "Couldn't open $db_lock: $!\n";
2014         _rev_db_set($fh, $rev, $commit);
2015         if ($sync) {
2016                 $fh->flush or die "Couldn't flush $db_lock: $!\n";
2017                 $fh->sync or die "Couldn't sync $db_lock: $!\n";
2018         }
2019         close $fh or croak $!;
2020         if ($update_ref) {
2021                 $_head = $self;
2022                 command_noisy('update-ref', '-m', "r$rev",
2023                               $self->refname, $commit);
2024         }
2025         rename $db_lock, $db or die "rev_db_set(@_): ", "Failed to rename: ",
2026                                     "$db_lock => $db ($!)\n";
2027         delete $LOCKFILES{$db_lock};
2028         if ($update_ref) {
2029                 $SIG{INT} = $SIG{HUP} = $SIG{TERM} = $SIG{ALRM} = $SIG{PIPE} =
2030                             $SIG{USR1} = $SIG{USR2} = 'DEFAULT';
2031                 kill $sig, $$ if defined $sig;
2032         }
2035 sub rev_db_max {
2036         my ($self) = @_;
2037         $self->rebuild;
2038         my $db_path = $self->db_path;
2039         my @stat = stat $db_path or return 0;
2040         ($stat[7] % 41) == 0 or die "$db_path inconsistent size: $stat[7]\n";
2041         my $max = $stat[7] / 41;
2042         (($max > 0) ? $max - 1 : 0);
2045 sub rev_db_get {
2046         my ($self, $rev, $uuid) = @_;
2047         my $ret;
2048         my $offset = $rev * 41;
2049         my $db_path = $self->db_path($uuid);
2050         return undef unless -e $db_path;
2051         open my $fh, '<', $db_path or croak $!;
2052         if (sysseek($fh, $offset, 0) == $offset) {
2053                 my $read = sysread($fh, $ret, 40);
2054                 $ret = undef if ($read != 40 || $ret eq ('0'x40));
2055         }
2056         close $fh or croak $!;
2057         $ret;
2060 sub find_rev_before {
2061         my ($self, $rev, $eq_ok) = @_;
2062         --$rev unless $eq_ok;
2063         while ($rev > 0) {
2064                 if (my $c = $self->rev_db_get($rev)) {
2065                         return ($rev, $c);
2066                 }
2067                 --$rev;
2068         }
2069         return (undef, undef);
2072 sub _new {
2073         my ($class, $repo_id, $ref_id, $path) = @_;
2074         unless (defined $repo_id && length $repo_id) {
2075                 $repo_id = $Git::SVN::default_repo_id;
2076         }
2077         unless (defined $ref_id && length $ref_id) {
2078                 $_[2] = $ref_id = $Git::SVN::default_ref_id;
2079         }
2080         $_[1] = $repo_id = sanitize_remote_name($repo_id);
2081         my $dir = "$ENV{GIT_DIR}/svn/$ref_id";
2082         $_[3] = $path = '' unless (defined $path);
2083         mkpath(["$ENV{GIT_DIR}/svn"]);
2084         bless {
2085                 ref_id => $ref_id, dir => $dir, index => "$dir/index",
2086                 path => $path, config => "$ENV{GIT_DIR}/svn/config",
2087                 db_root => "$dir/.rev_db", repo_id => $repo_id }, $class;
2090 sub db_path {
2091         my ($self, $uuid) = @_;
2092         $uuid ||= $self->ra_uuid;
2093         "$self->{db_root}.$uuid";
2096 sub uri_encode {
2097         my ($f) = @_;
2098         $f =~ s#([^a-zA-Z0-9\*!\:_\./\-])#uc sprintf("%%%02x",ord($1))#eg;
2099         $f
2102 sub remove_username {
2103         $_[0] =~ s{^([^:]*://)[^@]+@}{$1};
2106 package Git::SVN::Prompt;
2107 use strict;
2108 use warnings;
2109 require SVN::Core;
2110 use vars qw/$_no_auth_cache $_username/;
2112 sub simple {
2113         my ($cred, $realm, $default_username, $may_save, $pool) = @_;
2114         $may_save = undef if $_no_auth_cache;
2115         $default_username = $_username if defined $_username;
2116         if (defined $default_username && length $default_username) {
2117                 if (defined $realm && length $realm) {
2118                         print STDERR "Authentication realm: $realm\n";
2119                         STDERR->flush;
2120                 }
2121                 $cred->username($default_username);
2122         } else {
2123                 username($cred, $realm, $may_save, $pool);
2124         }
2125         $cred->password(_read_password("Password for '" .
2126                                        $cred->username . "': ", $realm));
2127         $cred->may_save($may_save);
2128         $SVN::_Core::SVN_NO_ERROR;
2131 sub ssl_server_trust {
2132         my ($cred, $realm, $failures, $cert_info, $may_save, $pool) = @_;
2133         $may_save = undef if $_no_auth_cache;
2134         print STDERR "Error validating server certificate for '$realm':\n";
2135         if ($failures & $SVN::Auth::SSL::UNKNOWNCA) {
2136                 print STDERR " - The certificate is not issued by a trusted ",
2137                       "authority. Use the\n",
2138                       "   fingerprint to validate the certificate manually!\n";
2139         }
2140         if ($failures & $SVN::Auth::SSL::CNMISMATCH) {
2141                 print STDERR " - The certificate hostname does not match.\n";
2142         }
2143         if ($failures & $SVN::Auth::SSL::NOTYETVALID) {
2144                 print STDERR " - The certificate is not yet valid.\n";
2145         }
2146         if ($failures & $SVN::Auth::SSL::EXPIRED) {
2147                 print STDERR " - The certificate has expired.\n";
2148         }
2149         if ($failures & $SVN::Auth::SSL::OTHER) {
2150                 print STDERR " - The certificate has an unknown error.\n";
2151         }
2152         printf STDERR
2153                 "Certificate information:\n".
2154                 " - Hostname: %s\n".
2155                 " - Valid: from %s until %s\n".
2156                 " - Issuer: %s\n".
2157                 " - Fingerprint: %s\n",
2158                 map $cert_info->$_, qw(hostname valid_from valid_until
2159                                        issuer_dname fingerprint);
2160         my $choice;
2161 prompt:
2162         print STDERR $may_save ?
2163               "(R)eject, accept (t)emporarily or accept (p)ermanently? " :
2164               "(R)eject or accept (t)emporarily? ";
2165         STDERR->flush;
2166         $choice = lc(substr(<STDIN> || 'R', 0, 1));
2167         if ($choice =~ /^t$/i) {
2168                 $cred->may_save(undef);
2169         } elsif ($choice =~ /^r$/i) {
2170                 return -1;
2171         } elsif ($may_save && $choice =~ /^p$/i) {
2172                 $cred->may_save($may_save);
2173         } else {
2174                 goto prompt;
2175         }
2176         $cred->accepted_failures($failures);
2177         $SVN::_Core::SVN_NO_ERROR;
2180 sub ssl_client_cert {
2181         my ($cred, $realm, $may_save, $pool) = @_;
2182         $may_save = undef if $_no_auth_cache;
2183         print STDERR "Client certificate filename: ";
2184         STDERR->flush;
2185         chomp(my $filename = <STDIN>);
2186         $cred->cert_file($filename);
2187         $cred->may_save($may_save);
2188         $SVN::_Core::SVN_NO_ERROR;
2191 sub ssl_client_cert_pw {
2192         my ($cred, $realm, $may_save, $pool) = @_;
2193         $may_save = undef if $_no_auth_cache;
2194         $cred->password(_read_password("Password: ", $realm));
2195         $cred->may_save($may_save);
2196         $SVN::_Core::SVN_NO_ERROR;
2199 sub username {
2200         my ($cred, $realm, $may_save, $pool) = @_;
2201         $may_save = undef if $_no_auth_cache;
2202         if (defined $realm && length $realm) {
2203                 print STDERR "Authentication realm: $realm\n";
2204         }
2205         my $username;
2206         if (defined $_username) {
2207                 $username = $_username;
2208         } else {
2209                 print STDERR "Username: ";
2210                 STDERR->flush;
2211                 chomp($username = <STDIN>);
2212         }
2213         $cred->username($username);
2214         $cred->may_save($may_save);
2215         $SVN::_Core::SVN_NO_ERROR;
2218 sub _read_password {
2219         my ($prompt, $realm) = @_;
2220         print STDERR $prompt;
2221         STDERR->flush;
2222         require Term::ReadKey;
2223         Term::ReadKey::ReadMode('noecho');
2224         my $password = '';
2225         while (defined(my $key = Term::ReadKey::ReadKey(0))) {
2226                 last if $key =~ /[\012\015]/; # \n\r
2227                 $password .= $key;
2228         }
2229         Term::ReadKey::ReadMode('restore');
2230         print STDERR "\n";
2231         STDERR->flush;
2232         $password;
2235 package main;
2238         my $kill_stupid_warnings = $SVN::Node::none.$SVN::Node::file.
2239                                 $SVN::Node::dir.$SVN::Node::unknown.
2240                                 $SVN::Node::none.$SVN::Node::file.
2241                                 $SVN::Node::dir.$SVN::Node::unknown.
2242                                 $SVN::Auth::SSL::CNMISMATCH.
2243                                 $SVN::Auth::SSL::NOTYETVALID.
2244                                 $SVN::Auth::SSL::EXPIRED.
2245                                 $SVN::Auth::SSL::UNKNOWNCA.
2246                                 $SVN::Auth::SSL::OTHER;
2249 package SVN::Git::Fetcher;
2250 use vars qw/@ISA/;
2251 use strict;
2252 use warnings;
2253 use Carp qw/croak/;
2254 use IO::File qw//;
2255 use Digest::MD5;
2257 # file baton members: path, mode_a, mode_b, pool, fh, blob, base
2258 sub new {
2259         my ($class, $git_svn) = @_;
2260         my $self = SVN::Delta::Editor->new;
2261         bless $self, $class;
2262         $self->{c} = $git_svn->{last_commit} if exists $git_svn->{last_commit};
2263         $self->{empty} = {};
2264         $self->{dir_prop} = {};
2265         $self->{file_prop} = {};
2266         $self->{absent_dir} = {};
2267         $self->{absent_file} = {};
2268         $self->{gii} = $git_svn->tmp_index_do(sub { Git::IndexInfo->new });
2269         $self;
2272 sub set_path_strip {
2273         my ($self, $path) = @_;
2274         $self->{path_strip} = qr/^\Q$path\E(\/|$)/ if length $path;
2277 sub open_root {
2278         { path => '' };
2281 sub open_directory {
2282         my ($self, $path, $pb, $rev) = @_;
2283         { path => $path };
2286 sub git_path {
2287         my ($self, $path) = @_;
2288         if ($self->{path_strip}) {
2289                 $path =~ s!$self->{path_strip}!! or
2290                   die "Failed to strip path '$path' ($self->{path_strip})\n";
2291         }
2292         $path;
2295 sub delete_entry {
2296         my ($self, $path, $rev, $pb) = @_;
2298         my $gpath = $self->git_path($path);
2299         return undef if ($gpath eq '');
2301         # remove entire directories.
2302         if (command('ls-tree', $self->{c}, '--', $gpath) =~ /^040000 tree/) {
2303                 my ($ls, $ctx) = command_output_pipe(qw/ls-tree
2304                                                      -r --name-only -z/,
2305                                                      $self->{c}, '--', $gpath);
2306                 local $/ = "\0";
2307                 while (<$ls>) {
2308                         chomp;
2309                         $self->{gii}->remove($_);
2310                         print "\tD\t$_\n" unless $::_q;
2311                 }
2312                 print "\tD\t$gpath/\n" unless $::_q;
2313                 command_close_pipe($ls, $ctx);
2314                 $self->{empty}->{$path} = 0
2315         } else {
2316                 $self->{gii}->remove($gpath);
2317                 print "\tD\t$gpath\n" unless $::_q;
2318         }
2319         undef;
2322 sub open_file {
2323         my ($self, $path, $pb, $rev) = @_;
2324         my $gpath = $self->git_path($path);
2325         my ($mode, $blob) = (command('ls-tree', $self->{c}, '--', $gpath)
2326                              =~ /^(\d{6}) blob ([a-f\d]{40})\t/);
2327         unless (defined $mode && defined $blob) {
2328                 die "$path was not found in commit $self->{c} (r$rev)\n";
2329         }
2330         { path => $path, mode_a => $mode, mode_b => $mode, blob => $blob,
2331           pool => SVN::Pool->new, action => 'M' };
2334 sub add_file {
2335         my ($self, $path, $pb, $cp_path, $cp_rev) = @_;
2336         my ($dir, $file) = ($path =~ m#^(.*?)/?([^/]+)$#);
2337         delete $self->{empty}->{$dir};
2338         { path => $path, mode_a => 100644, mode_b => 100644,
2339           pool => SVN::Pool->new, action => 'A' };
2342 sub add_directory {
2343         my ($self, $path, $cp_path, $cp_rev) = @_;
2344         my ($dir, $file) = ($path =~ m#^(.*?)/?([^/]+)$#);
2345         delete $self->{empty}->{$dir};
2346         $self->{empty}->{$path} = 1;
2347         { path => $path };
2350 sub change_dir_prop {
2351         my ($self, $db, $prop, $value) = @_;
2352         $self->{dir_prop}->{$db->{path}} ||= {};
2353         $self->{dir_prop}->{$db->{path}}->{$prop} = $value;
2354         undef;
2357 sub absent_directory {
2358         my ($self, $path, $pb) = @_;
2359         $self->{absent_dir}->{$pb->{path}} ||= [];
2360         push @{$self->{absent_dir}->{$pb->{path}}}, $path;
2361         undef;
2364 sub absent_file {
2365         my ($self, $path, $pb) = @_;
2366         $self->{absent_file}->{$pb->{path}} ||= [];
2367         push @{$self->{absent_file}->{$pb->{path}}}, $path;
2368         undef;
2371 sub change_file_prop {
2372         my ($self, $fb, $prop, $value) = @_;
2373         if ($prop eq 'svn:executable') {
2374                 if ($fb->{mode_b} != 120000) {
2375                         $fb->{mode_b} = defined $value ? 100755 : 100644;
2376                 }
2377         } elsif ($prop eq 'svn:special') {
2378                 $fb->{mode_b} = defined $value ? 120000 : 100644;
2379         } else {
2380                 $self->{file_prop}->{$fb->{path}} ||= {};
2381                 $self->{file_prop}->{$fb->{path}}->{$prop} = $value;
2382         }
2383         undef;
2386 sub apply_textdelta {
2387         my ($self, $fb, $exp) = @_;
2388         my $fh = IO::File->new_tmpfile;
2389         $fh->autoflush(1);
2390         # $fh gets auto-closed() by SVN::TxDelta::apply(),
2391         # (but $base does not,) so dup() it for reading in close_file
2392         open my $dup, '<&', $fh or croak $!;
2393         my $base = IO::File->new_tmpfile;
2394         $base->autoflush(1);
2395         if ($fb->{blob}) {
2396                 defined (my $pid = fork) or croak $!;
2397                 if (!$pid) {
2398                         open STDOUT, '>&', $base or croak $!;
2399                         print STDOUT 'link ' if ($fb->{mode_a} == 120000);
2400                         exec qw/git-cat-file blob/, $fb->{blob} or croak $!;
2401                 }
2402                 waitpid $pid, 0;
2403                 croak $? if $?;
2405                 if (defined $exp) {
2406                         seek $base, 0, 0 or croak $!;
2407                         my $md5 = Digest::MD5->new;
2408                         $md5->addfile($base);
2409                         my $got = $md5->hexdigest;
2410                         die "Checksum mismatch: $fb->{path} $fb->{blob}\n",
2411                             "expected: $exp\n",
2412                             "     got: $got\n" if ($got ne $exp);
2413                 }
2414         }
2415         seek $base, 0, 0 or croak $!;
2416         $fb->{fh} = $dup;
2417         $fb->{base} = $base;
2418         [ SVN::TxDelta::apply($base, $fh, undef, $fb->{path}, $fb->{pool}) ];
2421 sub close_file {
2422         my ($self, $fb, $exp) = @_;
2423         my $hash;
2424         my $path = $self->git_path($fb->{path});
2425         if (my $fh = $fb->{fh}) {
2426                 seek($fh, 0, 0) or croak $!;
2427                 my $md5 = Digest::MD5->new;
2428                 $md5->addfile($fh);
2429                 my $got = $md5->hexdigest;
2430                 die "Checksum mismatch: $path\n",
2431                     "expected: $exp\n    got: $got\n" if ($got ne $exp);
2432                 seek($fh, 0, 0) or croak $!;
2433                 if ($fb->{mode_b} == 120000) {
2434                         read($fh, my $buf, 5) == 5 or croak $!;
2435                         $buf eq 'link ' or die "$path has mode 120000",
2436                                                "but is not a link\n";
2437                 }
2438                 defined(my $pid = open my $out,'-|') or die "Can't fork: $!\n";
2439                 if (!$pid) {
2440                         open STDIN, '<&', $fh or croak $!;
2441                         exec qw/git-hash-object -w --stdin/ or croak $!;
2442                 }
2443                 chomp($hash = do { local $/; <$out> });
2444                 close $out or croak $!;
2445                 close $fh or croak $!;
2446                 $hash =~ /^[a-f\d]{40}$/ or die "not a sha1: $hash\n";
2447                 close $fb->{base} or croak $!;
2448         } else {
2449                 $hash = $fb->{blob} or die "no blob information\n";
2450         }
2451         $fb->{pool}->clear;
2452         $self->{gii}->update($fb->{mode_b}, $hash, $path) or croak $!;
2453         print "\t$fb->{action}\t$path\n" if $fb->{action} && ! $::_q;
2454         undef;
2457 sub abort_edit {
2458         my $self = shift;
2459         $self->{nr} = $self->{gii}->{nr};
2460         delete $self->{gii};
2461         $self->SUPER::abort_edit(@_);
2464 sub close_edit {
2465         my $self = shift;
2466         $self->{git_commit_ok} = 1;
2467         $self->{nr} = $self->{gii}->{nr};
2468         delete $self->{gii};
2469         $self->SUPER::close_edit(@_);
2472 package SVN::Git::Editor;
2473 use vars qw/@ISA $_rmdir $_cp_similarity $_find_copies_harder $_rename_limit/;
2474 use strict;
2475 use warnings;
2476 use Carp qw/croak/;
2477 use IO::File;
2478 use Digest::MD5;
2480 sub new {
2481         my ($class, $opts) = @_;
2482         foreach (qw/svn_path r ra tree_a tree_b log editor_cb/) {
2483                 die "$_ required!\n" unless (defined $opts->{$_});
2484         }
2486         my $pool = SVN::Pool->new;
2487         my $mods = generate_diff($opts->{tree_a}, $opts->{tree_b});
2488         my $types = check_diff_paths($opts->{ra}, $opts->{svn_path},
2489                                      $opts->{r}, $mods);
2491         # $opts->{ra} functions should not be used after this:
2492         my @ce  = $opts->{ra}->get_commit_editor($opts->{log},
2493                                                 $opts->{editor_cb}, $pool);
2494         my $self = SVN::Delta::Editor->new(@ce, $pool);
2495         bless $self, $class;
2496         foreach (qw/svn_path r tree_a tree_b/) {
2497                 $self->{$_} = $opts->{$_};
2498         }
2499         $self->{url} = $opts->{ra}->{url};
2500         $self->{mods} = $mods;
2501         $self->{types} = $types;
2502         $self->{pool} = $pool;
2503         $self->{bat} = { '' => $self->open_root($self->{r}, $self->{pool}) };
2504         $self->{rm} = { };
2505         $self->{path_prefix} = length $self->{svn_path} ?
2506                                "$self->{svn_path}/" : '';
2507         return $self;
2510 sub generate_diff {
2511         my ($tree_a, $tree_b) = @_;
2512         my @diff_tree = qw(diff-tree -z -r);
2513         if ($_cp_similarity) {
2514                 push @diff_tree, "-C$_cp_similarity";
2515         } else {
2516                 push @diff_tree, '-C';
2517         }
2518         push @diff_tree, '--find-copies-harder' if $_find_copies_harder;
2519         push @diff_tree, "-l$_rename_limit" if defined $_rename_limit;
2520         push @diff_tree, $tree_a, $tree_b;
2521         my ($diff_fh, $ctx) = command_output_pipe(@diff_tree);
2522         local $/ = "\0";
2523         my $state = 'meta';
2524         my @mods;
2525         while (<$diff_fh>) {
2526                 chomp $_; # this gets rid of the trailing "\0"
2527                 if ($state eq 'meta' && /^:(\d{6})\s(\d{6})\s
2528                                         $::sha1\s($::sha1)\s
2529                                         ([MTCRAD])\d*$/xo) {
2530                         push @mods, {   mode_a => $1, mode_b => $2,
2531                                         sha1_b => $3, chg => $4 };
2532                         if ($4 =~ /^(?:C|R)$/) {
2533                                 $state = 'file_a';
2534                         } else {
2535                                 $state = 'file_b';
2536                         }
2537                 } elsif ($state eq 'file_a') {
2538                         my $x = $mods[$#mods] or croak "Empty array\n";
2539                         if ($x->{chg} !~ /^(?:C|R)$/) {
2540                                 croak "Error parsing $_, $x->{chg}\n";
2541                         }
2542                         $x->{file_a} = $_;
2543                         $state = 'file_b';
2544                 } elsif ($state eq 'file_b') {
2545                         my $x = $mods[$#mods] or croak "Empty array\n";
2546                         if (exists $x->{file_a} && $x->{chg} !~ /^(?:C|R)$/) {
2547                                 croak "Error parsing $_, $x->{chg}\n";
2548                         }
2549                         if (!exists $x->{file_a} && $x->{chg} =~ /^(?:C|R)$/) {
2550                                 croak "Error parsing $_, $x->{chg}\n";
2551                         }
2552                         $x->{file_b} = $_;
2553                         $state = 'meta';
2554                 } else {
2555                         croak "Error parsing $_\n";
2556                 }
2557         }
2558         command_close_pipe($diff_fh, $ctx);
2559         \@mods;
2562 sub check_diff_paths {
2563         my ($ra, $pfx, $rev, $mods) = @_;
2564         my %types;
2565         $pfx .= '/' if length $pfx;
2567         sub type_diff_paths {
2568                 my ($ra, $types, $path, $rev) = @_;
2569                 my @p = split m#/+#, $path;
2570                 my $c = shift @p;
2571                 unless (defined $types->{$c}) {
2572                         $types->{$c} = $ra->check_path($c, $rev);
2573                 }
2574                 while (@p) {
2575                         $c .= '/' . shift @p;
2576                         next if defined $types->{$c};
2577                         $types->{$c} = $ra->check_path($c, $rev);
2578                 }
2579         }
2581         foreach my $m (@$mods) {
2582                 foreach my $f (qw/file_a file_b/) {
2583                         next unless defined $m->{$f};
2584                         my ($dir) = ($m->{$f} =~ m#^(.*?)/?(?:[^/]+)$#);
2585                         if (length $pfx.$dir && ! defined $types{$dir}) {
2586                                 type_diff_paths($ra, \%types, $pfx.$dir, $rev);
2587                         }
2588                 }
2589         }
2590         \%types;
2593 sub split_path {
2594         return ($_[0] =~ m#^(.*?)/?([^/]+)$#);
2597 sub repo_path {
2598         my ($self, $path) = @_;
2599         $self->{path_prefix}.(defined $path ? $path : '');
2602 sub url_path {
2603         my ($self, $path) = @_;
2604         $self->{url} . '/' . $self->repo_path($path);
2607 sub rmdirs {
2608         my ($self) = @_;
2609         my $rm = $self->{rm};
2610         delete $rm->{''}; # we never delete the url we're tracking
2611         return unless %$rm;
2613         foreach (keys %$rm) {
2614                 my @d = split m#/#, $_;
2615                 my $c = shift @d;
2616                 $rm->{$c} = 1;
2617                 while (@d) {
2618                         $c .= '/' . shift @d;
2619                         $rm->{$c} = 1;
2620                 }
2621         }
2622         delete $rm->{$self->{svn_path}};
2623         delete $rm->{''}; # we never delete the url we're tracking
2624         return unless %$rm;
2626         my ($fh, $ctx) = command_output_pipe(qw/ls-tree --name-only -r -z/,
2627                                              $self->{tree_b});
2628         local $/ = "\0";
2629         while (<$fh>) {
2630                 chomp;
2631                 my @dn = split m#/#, $_;
2632                 while (pop @dn) {
2633                         delete $rm->{join '/', @dn};
2634                 }
2635                 unless (%$rm) {
2636                         close $fh;
2637                         return;
2638                 }
2639         }
2640         command_close_pipe($fh, $ctx);
2642         my ($r, $p, $bat) = ($self->{r}, $self->{pool}, $self->{bat});
2643         foreach my $d (sort { $b =~ tr#/#/# <=> $a =~ tr#/#/# } keys %$rm) {
2644                 $self->close_directory($bat->{$d}, $p);
2645                 my ($dn) = ($d =~ m#^(.*?)/?(?:[^/]+)$#);
2646                 print "\tD+\t$d/\n" unless $::_q;
2647                 $self->SUPER::delete_entry($d, $r, $bat->{$dn}, $p);
2648                 delete $bat->{$d};
2649         }
2652 sub open_or_add_dir {
2653         my ($self, $full_path, $baton) = @_;
2654         my $t = $self->{types}->{$full_path};
2655         if (!defined $t) {
2656                 die "$full_path not known in r$self->{r} or we have a bug!\n";
2657         }
2658         if ($t == $SVN::Node::none) {
2659                 return $self->add_directory($full_path, $baton,
2660                                                 undef, -1, $self->{pool});
2661         } elsif ($t == $SVN::Node::dir) {
2662                 return $self->open_directory($full_path, $baton,
2663                                                 $self->{r}, $self->{pool});
2664         }
2665         print STDERR "$full_path already exists in repository at ",
2666                 "r$self->{r} and it is not a directory (",
2667                 ($t == $SVN::Node::file ? 'file' : 'unknown'),"/$t)\n";
2668         exit 1;
2671 sub ensure_path {
2672         my ($self, $path) = @_;
2673         my $bat = $self->{bat};
2674         my $repo_path = $self->repo_path($path);
2675         return $bat->{''} unless (length $repo_path);
2676         my @p = split m#/+#, $repo_path;
2677         my $c = shift @p;
2678         $bat->{$c} ||= $self->open_or_add_dir($c, $bat->{''});
2679         while (@p) {
2680                 my $c0 = $c;
2681                 $c .= '/' . shift @p;
2682                 $bat->{$c} ||= $self->open_or_add_dir($c, $bat->{$c0});
2683         }
2684         return $bat->{$c};
2687 sub A {
2688         my ($self, $m) = @_;
2689         my ($dir, $file) = split_path($m->{file_b});
2690         my $pbat = $self->ensure_path($dir);
2691         my $fbat = $self->add_file($self->repo_path($m->{file_b}), $pbat,
2692                                         undef, -1);
2693         print "\tA\t$m->{file_b}\n" unless $::_q;
2694         $self->chg_file($fbat, $m);
2695         $self->close_file($fbat,undef,$self->{pool});
2698 sub C {
2699         my ($self, $m) = @_;
2700         my ($dir, $file) = split_path($m->{file_b});
2701         my $pbat = $self->ensure_path($dir);
2702         my $fbat = $self->add_file($self->repo_path($m->{file_b}), $pbat,
2703                                 $self->url_path($m->{file_a}), $self->{r});
2704         print "\tC\t$m->{file_a} => $m->{file_b}\n" unless $::_q;
2705         $self->chg_file($fbat, $m);
2706         $self->close_file($fbat,undef,$self->{pool});
2709 sub delete_entry {
2710         my ($self, $path, $pbat) = @_;
2711         my $rpath = $self->repo_path($path);
2712         my ($dir, $file) = split_path($rpath);
2713         $self->{rm}->{$dir} = 1;
2714         $self->SUPER::delete_entry($rpath, $self->{r}, $pbat, $self->{pool});
2717 sub R {
2718         my ($self, $m) = @_;
2719         my ($dir, $file) = split_path($m->{file_b});
2720         my $pbat = $self->ensure_path($dir);
2721         my $fbat = $self->add_file($self->repo_path($m->{file_b}), $pbat,
2722                                 $self->url_path($m->{file_a}), $self->{r});
2723         print "\tR\t$m->{file_a} => $m->{file_b}\n" unless $::_q;
2724         $self->chg_file($fbat, $m);
2725         $self->close_file($fbat,undef,$self->{pool});
2727         ($dir, $file) = split_path($m->{file_a});
2728         $pbat = $self->ensure_path($dir);
2729         $self->delete_entry($m->{file_a}, $pbat);
2732 sub M {
2733         my ($self, $m) = @_;
2734         my ($dir, $file) = split_path($m->{file_b});
2735         my $pbat = $self->ensure_path($dir);
2736         my $fbat = $self->open_file($self->repo_path($m->{file_b}),
2737                                 $pbat,$self->{r},$self->{pool});
2738         print "\t$m->{chg}\t$m->{file_b}\n" unless $::_q;
2739         $self->chg_file($fbat, $m);
2740         $self->close_file($fbat,undef,$self->{pool});
2743 sub T { shift->M(@_) }
2745 sub change_file_prop {
2746         my ($self, $fbat, $pname, $pval) = @_;
2747         $self->SUPER::change_file_prop($fbat, $pname, $pval, $self->{pool});
2750 sub chg_file {
2751         my ($self, $fbat, $m) = @_;
2752         if ($m->{mode_b} =~ /755$/ && $m->{mode_a} !~ /755$/) {
2753                 $self->change_file_prop($fbat,'svn:executable','*');
2754         } elsif ($m->{mode_b} !~ /755$/ && $m->{mode_a} =~ /755$/) {
2755                 $self->change_file_prop($fbat,'svn:executable',undef);
2756         }
2757         my $fh = IO::File->new_tmpfile or croak $!;
2758         if ($m->{mode_b} =~ /^120/) {
2759                 print $fh 'link ' or croak $!;
2760                 $self->change_file_prop($fbat,'svn:special','*');
2761         } elsif ($m->{mode_a} =~ /^120/ && $m->{mode_b} !~ /^120/) {
2762                 $self->change_file_prop($fbat,'svn:special',undef);
2763         }
2764         defined(my $pid = fork) or croak $!;
2765         if (!$pid) {
2766                 open STDOUT, '>&', $fh or croak $!;
2767                 exec qw/git-cat-file blob/, $m->{sha1_b} or croak $!;
2768         }
2769         waitpid $pid, 0;
2770         croak $? if $?;
2771         $fh->flush == 0 or croak $!;
2772         seek $fh, 0, 0 or croak $!;
2774         my $md5 = Digest::MD5->new;
2775         $md5->addfile($fh) or croak $!;
2776         seek $fh, 0, 0 or croak $!;
2778         my $exp = $md5->hexdigest;
2779         my $pool = SVN::Pool->new;
2780         my $atd = $self->apply_textdelta($fbat, undef, $pool);
2781         my $got = SVN::TxDelta::send_stream($fh, @$atd, $pool);
2782         die "Checksum mismatch\nexpected: $exp\ngot: $got\n" if ($got ne $exp);
2783         $pool->clear;
2785         close $fh or croak $!;
2788 sub D {
2789         my ($self, $m) = @_;
2790         my ($dir, $file) = split_path($m->{file_b});
2791         my $pbat = $self->ensure_path($dir);
2792         print "\tD\t$m->{file_b}\n" unless $::_q;
2793         $self->delete_entry($m->{file_b}, $pbat);
2796 sub close_edit {
2797         my ($self) = @_;
2798         my ($p,$bat) = ($self->{pool}, $self->{bat});
2799         foreach (sort { $b =~ tr#/#/# <=> $a =~ tr#/#/# } keys %$bat) {
2800                 $self->close_directory($bat->{$_}, $p);
2801         }
2802         $self->SUPER::close_edit($p);
2803         $p->clear;
2806 sub abort_edit {
2807         my ($self) = @_;
2808         $self->SUPER::abort_edit($self->{pool});
2811 sub DESTROY {
2812         my $self = shift;
2813         $self->SUPER::DESTROY(@_);
2814         $self->{pool}->clear;
2817 # this drives the editor
2818 sub apply_diff {
2819         my ($self) = @_;
2820         my $mods = $self->{mods};
2821         my %o = ( D => 1, R => 0, C => -1, A => 3, M => 3, T => 3 );
2822         foreach my $m (sort { $o{$a->{chg}} <=> $o{$b->{chg}} } @$mods) {
2823                 my $f = $m->{chg};
2824                 if (defined $o{$f}) {
2825                         $self->$f($m);
2826                 } else {
2827                         fatal("Invalid change type: $f\n");
2828                 }
2829         }
2830         $self->rmdirs if $_rmdir;
2831         if (@$mods == 0) {
2832                 $self->abort_edit;
2833         } else {
2834                 $self->close_edit;
2835         }
2836         return scalar @$mods;
2839 package Git::SVN::Ra;
2840 use vars qw/@ISA $config_dir $_log_window_size/;
2841 use strict;
2842 use warnings;
2843 my ($can_do_switch);
2844 my $RA;
2846 BEGIN {
2847         # enforce temporary pool usage for some simple functions
2848         my $e;
2849         foreach (qw/get_latest_revnum get_uuid get_repos_root/) {
2850                 $e .= "sub $_ {
2851                         my \$self = shift;
2852                         my \$pool = SVN::Pool->new;
2853                         my \@ret = \$self->SUPER::$_(\@_,\$pool);
2854                         \$pool->clear;
2855                         wantarray ? \@ret : \$ret[0]; }\n";
2856         }
2858         # get_dir needs $pool held in cache for dirents to work,
2859         # check_path is cacheable and rev_proplist is close enough
2860         # for our purposes.
2861         foreach (qw/check_path get_dir rev_proplist/) {
2862                 $e .= "my \%${_}_cache; my \$${_}_rev = 0; sub $_ {
2863                         my \$self = shift;
2864                         my \$r = pop;
2865                         my \$k = join(\"\\0\", \@_);
2866                         if (my \$x = \$${_}_cache{\$r}->{\$k}) {
2867                                 return wantarray ? \@\$x : \$x->[0];
2868                         }
2869                         my \$pool = SVN::Pool->new;
2870                         my \@ret = \$self->SUPER::$_(\@_, \$r, \$pool);
2871                         if (\$r != \$${_}_rev) {
2872                                 \%${_}_cache = ( pool => [] );
2873                                 \$${_}_rev = \$r;
2874                         }
2875                         \$${_}_cache{\$r}->{\$k} = \\\@ret;
2876                         push \@{\$${_}_cache{pool}}, \$pool;
2877                         wantarray ? \@ret : \$ret[0]; }\n";
2878         }
2879         $e .= "\n1;";
2880         eval $e or die $@;
2883 sub new {
2884         my ($class, $url) = @_;
2885         $url =~ s!/+$!!;
2886         return $RA if ($RA && $RA->{url} eq $url);
2887         $RA->{pool}->clear if $RA;
2889         SVN::_Core::svn_config_ensure($config_dir, undef);
2890         my ($baton, $callbacks) = SVN::Core::auth_open_helper([
2891             SVN::Client::get_simple_provider(),
2892             SVN::Client::get_ssl_server_trust_file_provider(),
2893             SVN::Client::get_simple_prompt_provider(
2894               \&Git::SVN::Prompt::simple, 2),
2895             SVN::Client::get_ssl_client_cert_prompt_provider(
2896               \&Git::SVN::Prompt::ssl_client_cert, 2),
2897             SVN::Client::get_ssl_client_cert_pw_prompt_provider(
2898               \&Git::SVN::Prompt::ssl_client_cert_pw, 2),
2899             SVN::Client::get_username_provider(),
2900             SVN::Client::get_ssl_server_trust_prompt_provider(
2901               \&Git::SVN::Prompt::ssl_server_trust),
2902             SVN::Client::get_username_prompt_provider(
2903               \&Git::SVN::Prompt::username, 2),
2904           ]);
2905         my $config = SVN::Core::config_get_config($config_dir);
2906         my $self = SVN::Ra->new(url => $url, auth => $baton,
2907                               config => $config,
2908                               pool => SVN::Pool->new,
2909                               auth_provider_callbacks => $callbacks);
2910         $self->{svn_path} = $url;
2911         $self->{repos_root} = $self->get_repos_root;
2912         $self->{svn_path} =~ s#^\Q$self->{repos_root}\E(/|$)##;
2913         $RA = bless $self, $class;
2916 sub DESTROY {
2917         # do not call the real DESTROY since we store ourselves in $RA
2920 sub get_log {
2921         my ($self, @args) = @_;
2922         my $pool = SVN::Pool->new;
2923         splice(@args, 3, 1) if ($SVN::Core::VERSION le '1.2.0');
2924         my $ret = $self->SUPER::get_log(@args, $pool);
2925         $pool->clear;
2926         $ret;
2929 sub get_commit_editor {
2930         my ($self, $log, $cb, $pool) = @_;
2931         my @lock = $SVN::Core::VERSION ge '1.2.0' ? (undef, 0) : ();
2932         $self->SUPER::get_commit_editor($log, $cb, @lock, $pool);
2935 sub gs_do_update {
2936         my ($self, $rev_a, $rev_b, $gs, $editor) = @_;
2937         my $new = ($rev_a == $rev_b);
2938         my $path = $gs->{path};
2940         if ($new && -e $gs->{index}) {
2941                 unlink $gs->{index} or die
2942                   "Couldn't unlink index: $gs->{index}: $!\n";
2943         }
2944         my $pool = SVN::Pool->new;
2945         $editor->set_path_strip($path);
2946         my (@pc) = split m#/#, $path;
2947         my $reporter = $self->do_update($rev_b, (@pc ? shift @pc : ''),
2948                                         1, $editor, $pool);
2949         my @lock = $SVN::Core::VERSION ge '1.2.0' ? (undef) : ();
2951         # Since we can't rely on svn_ra_reparent being available, we'll
2952         # just have to do some magic with set_path to make it so
2953         # we only want a partial path.
2954         my $sp = '';
2955         my $final = join('/', @pc);
2956         while (@pc) {
2957                 $reporter->set_path($sp, $rev_b, 0, @lock, $pool);
2958                 $sp .= '/' if length $sp;
2959                 $sp .= shift @pc;
2960         }
2961         die "BUG: '$sp' != '$final'\n" if ($sp ne $final);
2963         $reporter->set_path($sp, $rev_a, $new, @lock, $pool);
2965         $reporter->finish_report($pool);
2966         $pool->clear;
2967         $editor->{git_commit_ok};
2970 # this requires SVN 1.4.3 or later (do_switch didn't work before 1.4.3, and
2971 # svn_ra_reparent didn't work before 1.4)
2972 sub gs_do_switch {
2973         my ($self, $rev_a, $rev_b, $gs, $url_b, $editor) = @_;
2974         my $path = $gs->{path};
2975         my $pool = SVN::Pool->new;
2977         my $full_url = $self->{url};
2978         my $old_url = $full_url;
2979         $full_url .= "/$path" if length $path;
2980         my ($ra, $reparented);
2981         if ($old_url ne $full_url) {
2982                 if ($old_url !~ m#^svn(\+ssh)?://#) {
2983                         SVN::_Ra::svn_ra_reparent($self->{session}, $full_url,
2984                                                   $pool);
2985                         $self->{url} = $full_url;
2986                         $reparented = 1;
2987                 } else {
2988                         $ra = Git::SVN::Ra->new($full_url);
2989                 }
2990         }
2991         $ra ||= $self;
2992         my $reporter = $ra->do_switch($rev_b, '', 1, $url_b, $editor, $pool);
2993         my @lock = $SVN::Core::VERSION ge '1.2.0' ? (undef) : ();
2994         $reporter->set_path('', $rev_a, 0, @lock, $pool);
2995         $reporter->finish_report($pool);
2997         if ($reparented) {
2998                 SVN::_Ra::svn_ra_reparent($self->{session}, $old_url, $pool);
2999                 $self->{url} = $old_url;
3000         }
3002         $pool->clear;
3003         $editor->{git_commit_ok};
3006 sub gs_fetch_loop_common {
3007         my ($self, $base, $head, $gsv, $globs) = @_;
3008         return if ($base > $head);
3009         my $inc = $_log_window_size;
3010         my ($min, $max) = ($base, $head < $base + $inc ? $head : $base + $inc);
3011         my %common;
3012         my $common_max = scalar @$gsv;
3014         foreach my $gs (@$gsv) {
3015                 my @tmp = split m#/#, $gs->{path};
3016                 my $p = '';
3017                 foreach (@tmp) {
3018                         $p .= length($p) ? "/$_" : $_;
3019                         $common{$p} ||= 0;
3020                         $common{$p}++;
3021                 }
3022         }
3023         $globs ||= [];
3024         $common_max += scalar @$globs;
3025         foreach my $glob (@$globs) {
3026                 my @tmp = split m#/#, $glob->{path}->{left};
3027                 my $p = '';
3028                 foreach (@tmp) {
3029                         $p .= length($p) ? "/$_" : $_;
3030                         $common{$p} ||= 0;
3031                         $common{$p}++;
3032                 }
3033         }
3035         my $longest_path = '';
3036         foreach (sort {length $b <=> length $a} keys %common) {
3037                 if ($common{$_} == $common_max) {
3038                         $longest_path = $_;
3039                         last;
3040                 }
3041         }
3042         while (1) {
3043                 my %revs;
3044                 my $err;
3045                 my $err_handler = $SVN::Error::handler;
3046                 $SVN::Error::handler = sub {
3047                         ($err) = @_;
3048                         skip_unknown_revs($err);
3049                 };
3050                 sub _cb {
3051                         my ($paths, $r, $author, $date, $log) = @_;
3052                         [ dup_changed_paths($paths),
3053                           { author => $author, date => $date, log => $log } ];
3054                 }
3055                 $self->get_log([$longest_path], $min, $max, 0, 1, 1,
3056                                sub { $revs{$_[1]} = _cb(@_) });
3057                 if ($err && $max >= $head) {
3058                         print STDERR "Path '$longest_path' ",
3059                                      "was probably deleted:\n",
3060                                      $err->expanded_message,
3061                                      "\nWill attempt to follow ",
3062                                      "revisions r$min .. r$max ",
3063                                      "committed before the deletion\n";
3064                         my $hi = $max;
3065                         while (--$hi >= $min) {
3066                                 my $ok;
3067                                 $self->get_log([$longest_path], $min, $hi,
3068                                                0, 1, 1, sub {
3069                                                $ok ||= $_[1];
3070                                                $revs{$_[1]} = _cb(@_) });
3071                                 if ($ok) {
3072                                         print STDERR "r$min .. r$ok OK\n";
3073                                         last;
3074                                 }
3075                         }
3076                 }
3077                 $SVN::Error::handler = $err_handler;
3079                 my %exists = map { $_->{path} => $_ } @$gsv;
3080                 foreach my $r (sort {$a <=> $b} keys %revs) {
3081                         my ($paths, $logged) = @{$revs{$r}};
3083                         foreach my $gs ($self->match_globs(\%exists, $paths,
3084                                                            $globs, $r)) {
3085                                 if ($gs->rev_db_max >= $r) {
3086                                         next;
3087                                 }
3088                                 next unless $gs->match_paths($paths, $r);
3089                                 $gs->{logged_rev_props} = $logged;
3090                                 if (my $last_commit = $gs->last_commit) {
3091                                         $gs->assert_index_clean($last_commit);
3092                                 }
3093                                 my $log_entry = $gs->do_fetch($paths, $r);
3094                                 if ($log_entry) {
3095                                         $gs->do_git_commit($log_entry);
3096                                 }
3097                         }
3098                         foreach my $g (@$globs) {
3099                                 my $k = "svn-remote.$g->{remote}." .
3100                                         "$g->{t}-maxRev";
3101                                 Git::SVN::tmp_config($k, $r);
3102                         }
3103                 }
3104                 # pre-fill the .rev_db since it'll eventually get filled in
3105                 # with '0' x40 if something new gets committed
3106                 foreach my $gs (@$gsv) {
3107                         next if defined $gs->rev_db_get($max);
3108                         $gs->rev_db_set($max, 0 x40);
3109                 }
3110                 foreach my $g (@$globs) {
3111                         my $k = "svn-remote.$g->{remote}.$g->{t}-maxRev";
3112                         Git::SVN::tmp_config($k, $max);
3113                 }
3114                 last if $max >= $head;
3115                 $min = $max + 1;
3116                 $max += $inc;
3117                 $max = $head if ($max > $head);
3118         }
3121 sub match_globs {
3122         my ($self, $exists, $paths, $globs, $r) = @_;
3124         sub get_dir_check {
3125                 my ($self, $exists, $g, $r) = @_;
3126                 my @x = eval { $self->get_dir($g->{path}->{left}, $r) };
3127                 return unless scalar @x == 3;
3128                 my $dirents = $x[0];
3129                 foreach my $de (keys %$dirents) {
3130                         next if $dirents->{$de}->kind != $SVN::Node::dir;
3131                         my $p = $g->{path}->full_path($de);
3132                         next if $exists->{$p};
3133                         next if (length $g->{path}->{right} &&
3134                                  ($self->check_path($p, $r) !=
3135                                   $SVN::Node::dir));
3136                         $exists->{$p} = Git::SVN->init($self->{url}, $p, undef,
3137                                          $g->{ref}->full_path($de), 1);
3138                 }
3139         }
3140         foreach my $g (@$globs) {
3141                 if (my $path = $paths->{"/$g->{path}->{left}"}) {
3142                         if ($path->{action} =~ /^[AR]$/) {
3143                                 get_dir_check($self, $exists, $g, $r);
3144                         }
3145                 }
3146                 foreach (keys %$paths) {
3147                         if (/$g->{path}->{left_regex}/ &&
3148                             !/$g->{path}->{regex}/) {
3149                                 next if $paths->{$_}->{action} !~ /^[AR]$/;
3150                                 get_dir_check($self, $exists, $g, $r);
3151                         }
3152                         next unless /$g->{path}->{regex}/;
3153                         my $p = $1;
3154                         my $pathname = $g->{path}->full_path($p);
3155                         next if $exists->{$pathname};
3156                         $exists->{$pathname} = Git::SVN->init(
3157                                               $self->{url}, $pathname, undef,
3158                                               $g->{ref}->full_path($p), 1);
3159                 }
3160                 my $c = '';
3161                 foreach (split m#/#, $g->{path}->{left}) {
3162                         $c .= "/$_";
3163                         next unless ($paths->{$c} &&
3164                                      ($paths->{$c}->{action} =~ /^[AR]$/));
3165                         get_dir_check($self, $exists, $g, $r);
3166                 }
3167         }
3168         values %$exists;
3171 sub minimize_url {
3172         my ($self) = @_;
3173         return $self->{url} if ($self->{url} eq $self->{repos_root});
3174         my $url = $self->{repos_root};
3175         my @components = split(m!/!, $self->{svn_path});
3176         my $c = '';
3177         do {
3178                 $url .= "/$c" if length $c;
3179                 eval { (ref $self)->new($url)->get_latest_revnum };
3180         } while ($@ && ($c = shift @components));
3181         $url;
3184 sub can_do_switch {
3185         my $self = shift;
3186         unless (defined $can_do_switch) {
3187                 my $pool = SVN::Pool->new;
3188                 my $rep = eval {
3189                         $self->do_switch(1, '', 0, $self->{url},
3190                                          SVN::Delta::Editor->new, $pool);
3191                 };
3192                 if ($@) {
3193                         $can_do_switch = 0;
3194                 } else {
3195                         $rep->abort_report($pool);
3196                         $can_do_switch = 1;
3197                 }
3198                 $pool->clear;
3199         }
3200         $can_do_switch;
3203 sub skip_unknown_revs {
3204         my ($err) = @_;
3205         my $errno = $err->apr_err();
3206         # Maybe the branch we're tracking didn't
3207         # exist when the repo started, so it's
3208         # not an error if it doesn't, just continue
3209         #
3210         # Wonderfully consistent library, eh?
3211         # 160013 - svn:// and file://
3212         # 175002 - http(s)://
3213         # 175007 - http(s):// (this repo required authorization, too...)
3214         #   More codes may be discovered later...
3215         if ($errno == 175007 || $errno == 175002 || $errno == 160013) {
3216                 warn "W: Ignoring error from SVN, path probably ",
3217                      "does not exist: ($errno): ",
3218                      $err->expanded_message,"\n";
3219                 return;
3220         }
3221         die "Error from SVN, ($errno): ", $err->expanded_message,"\n";
3224 # svn_log_changed_path_t objects passed to get_log are likely to be
3225 # overwritten even if only the refs are copied to an external variable,
3226 # so we should dup the structures in their entirety.  Using an externally
3227 # passed pool (instead of our temporary and quickly cleared pool in
3228 # Git::SVN::Ra) does not help matters at all...
3229 sub dup_changed_paths {
3230         my ($paths) = @_;
3231         return undef unless $paths;
3232         my %ret;
3233         foreach my $p (keys %$paths) {
3234                 my $i = $paths->{$p};
3235                 my %s = map { $_ => $i->$_ }
3236                               qw/copyfrom_path copyfrom_rev action/;
3237                 $ret{$p} = \%s;
3238         }
3239         \%ret;
3242 package Git::SVN::Log;
3243 use strict;
3244 use warnings;
3245 use POSIX qw/strftime/;
3246 use vars qw/$TZ $limit $color $pager $non_recursive $verbose $oneline
3247             %rusers $show_commit $incremental/;
3248 my $l_fmt;
3250 sub cmt_showable {
3251         my ($c) = @_;
3252         return 1 if defined $c->{r};
3253         if ($c->{l} && $c->{l}->[-1] eq "...\n" &&
3254                                 $c->{a_raw} =~ /\@([a-f\d\-]+)>$/) {
3255                 my @log = command(qw/cat-file commit/, $c->{c});
3256                 shift @log while ($log[0] ne "\n");
3257                 shift @log;
3258                 @{$c->{l}} = grep !/^git-svn-id: /, @log;
3260                 (undef, $c->{r}, undef) = ::extract_metadata(
3261                                 (grep(/^git-svn-id: /, @log))[-1]);
3262         }
3263         return defined $c->{r};
3266 sub log_use_color {
3267         return 1 if $color;
3268         my ($dc, $dcvar);
3269         $dcvar = 'color.diff';
3270         $dc = `git-config --get $dcvar`;
3271         if ($dc eq '') {
3272                 # nothing at all; fallback to "diff.color"
3273                 $dcvar = 'diff.color';
3274                 $dc = `git-config --get $dcvar`;
3275         }
3276         chomp($dc);
3277         if ($dc eq 'auto') {
3278                 my $pc;
3279                 $pc = `git-config --get color.pager`;
3280                 if ($pc eq '') {
3281                         # does not have it -- fallback to pager.color
3282                         $pc = `git-config --bool --get pager.color`;
3283                 }
3284                 else {
3285                         $pc = `git-config --bool --get color.pager`;
3286                         if ($?) {
3287                                 $pc = 'false';
3288                         }
3289                 }
3290                 chomp($pc);
3291                 if (-t *STDOUT || (defined $pager && $pc eq 'true')) {
3292                         return ($ENV{TERM} && $ENV{TERM} ne 'dumb');
3293                 }
3294                 return 0;
3295         }
3296         return 0 if $dc eq 'never';
3297         return 1 if $dc eq 'always';
3298         chomp($dc = `git-config --bool --get $dcvar`);
3299         return ($dc eq 'true');
3302 sub git_svn_log_cmd {
3303         my ($r_min, $r_max, @args) = @_;
3304         my $head = 'HEAD';
3305         foreach my $x (@args) {
3306                 last if $x eq '--';
3307                 next unless ::verify_ref("$x^0");
3308                 $head = $x;
3309                 last;
3310         }
3312         my $url = (::working_head_info($head))[0];
3313         my $gs = Git::SVN->find_by_url($url) || Git::SVN->_new;
3314         my @cmd = (qw/log --abbrev-commit --pretty=raw --default/,
3315                    $gs->refname);
3316         push @cmd, '-r' unless $non_recursive;
3317         push @cmd, qw/--raw --name-status/ if $verbose;
3318         push @cmd, '--color' if log_use_color();
3319         return @cmd unless defined $r_max;
3320         if ($r_max == $r_min) {
3321                 push @cmd, '--max-count=1';
3322                 if (my $c = $gs->rev_db_get($r_max)) {
3323                         push @cmd, $c;
3324                 }
3325         } else {
3326                 my ($c_min, $c_max);
3327                 $c_max = $gs->rev_db_get($r_max);
3328                 $c_min = $gs->rev_db_get($r_min);
3329                 if (defined $c_min && defined $c_max) {
3330                         if ($r_max > $r_max) {
3331                                 push @cmd, "$c_min..$c_max";
3332                         } else {
3333                                 push @cmd, "$c_max..$c_min";
3334                         }
3335                 } elsif ($r_max > $r_min) {
3336                         push @cmd, $c_max;
3337                 } else {
3338                         push @cmd, $c_min;
3339                 }
3340         }
3341         return @cmd;
3344 # adapted from pager.c
3345 sub config_pager {
3346         $pager ||= $ENV{GIT_PAGER} || $ENV{PAGER};
3347         if (!defined $pager) {
3348                 $pager = 'less';
3349         } elsif (length $pager == 0 || $pager eq 'cat') {
3350                 $pager = undef;
3351         }
3354 sub run_pager {
3355         return unless -t *STDOUT;
3356         pipe my $rfd, my $wfd or return;
3357         defined(my $pid = fork) or ::fatal "Can't fork: $!\n";
3358         if (!$pid) {
3359                 open STDOUT, '>&', $wfd or
3360                                      ::fatal "Can't redirect to stdout: $!\n";
3361                 return;
3362         }
3363         open STDIN, '<&', $rfd or ::fatal "Can't redirect stdin: $!\n";
3364         $ENV{LESS} ||= 'FRSX';
3365         exec $pager or ::fatal "Can't run pager: $! ($pager)\n";
3368 sub tz_to_s_offset {
3369         my ($tz) = @_;
3370         $tz =~ s/(\d\d)$//;
3371         return ($1 * 60) + ($tz * 3600);
3374 sub get_author_info {
3375         my ($dest, $author, $t, $tz) = @_;
3376         $author =~ s/(?:^\s*|\s*$)//g;
3377         $dest->{a_raw} = $author;
3378         my $au;
3379         if ($::_authors) {
3380                 $au = $rusers{$author} || undef;
3381         }
3382         if (!$au) {
3383                 ($au) = ($author =~ /<([^>]+)\@[^>]+>$/);
3384         }
3385         $dest->{t} = $t;
3386         $dest->{tz} = $tz;
3387         $dest->{a} = $au;
3388         # Date::Parse isn't in the standard Perl distro :(
3389         if ($tz =~ s/^\+//) {
3390                 $t += tz_to_s_offset($tz);
3391         } elsif ($tz =~ s/^\-//) {
3392                 $t -= tz_to_s_offset($tz);
3393         }
3394         $dest->{t_utc} = $t;
3397 sub process_commit {
3398         my ($c, $r_min, $r_max, $defer) = @_;
3399         if (defined $r_min && defined $r_max) {
3400                 if ($r_min == $c->{r} && $r_min == $r_max) {
3401                         show_commit($c);
3402                         return 0;
3403                 }
3404                 return 1 if $r_min == $r_max;
3405                 if ($r_min < $r_max) {
3406                         # we need to reverse the print order
3407                         return 0 if (defined $limit && --$limit < 0);
3408                         push @$defer, $c;
3409                         return 1;
3410                 }
3411                 if ($r_min != $r_max) {
3412                         return 1 if ($r_min < $c->{r});
3413                         return 1 if ($r_max > $c->{r});
3414                 }
3415         }
3416         return 0 if (defined $limit && --$limit < 0);
3417         show_commit($c);
3418         return 1;
3421 sub show_commit {
3422         my $c = shift;
3423         if ($oneline) {
3424                 my $x = "\n";
3425                 if (my $l = $c->{l}) {
3426                         while ($l->[0] =~ /^\s*$/) { shift @$l }
3427                         $x = $l->[0];
3428                 }
3429                 $l_fmt ||= 'A' . length($c->{r});
3430                 print 'r',pack($l_fmt, $c->{r}),' | ';
3431                 print "$c->{c} | " if $show_commit;
3432                 print $x;
3433         } else {
3434                 show_commit_normal($c);
3435         }
3438 sub show_commit_changed_paths {
3439         my ($c) = @_;
3440         return unless $c->{changed};
3441         print "Changed paths:\n", @{$c->{changed}};
3444 sub show_commit_normal {
3445         my ($c) = @_;
3446         print '-' x72, "\nr$c->{r} | ";
3447         print "$c->{c} | " if $show_commit;
3448         print "$c->{a} | ", strftime("%Y-%m-%d %H:%M:%S %z (%a, %d %b %Y)",
3449                                  localtime($c->{t_utc})), ' | ';
3450         my $nr_line = 0;
3452         if (my $l = $c->{l}) {
3453                 while ($l->[$#$l] eq "\n" && $#$l > 0
3454                                           && $l->[($#$l - 1)] eq "\n") {
3455                         pop @$l;
3456                 }
3457                 $nr_line = scalar @$l;
3458                 if (!$nr_line) {
3459                         print "1 line\n\n\n";
3460                 } else {
3461                         if ($nr_line == 1) {
3462                                 $nr_line = '1 line';
3463                         } else {
3464                                 $nr_line .= ' lines';
3465                         }
3466                         print $nr_line, "\n";
3467                         show_commit_changed_paths($c);
3468                         print "\n";
3469                         print $_ foreach @$l;
3470                 }
3471         } else {
3472                 print "1 line\n";
3473                 show_commit_changed_paths($c);
3474                 print "\n";
3476         }
3477         foreach my $x (qw/raw stat diff/) {
3478                 if ($c->{$x}) {
3479                         print "\n";
3480                         print $_ foreach @{$c->{$x}}
3481                 }
3482         }
3485 sub cmd_show_log {
3486         my (@args) = @_;
3487         my ($r_min, $r_max);
3488         my $r_last = -1; # prevent dupes
3489         if (defined $TZ) {
3490                 $ENV{TZ} = $TZ;
3491         } else {
3492                 delete $ENV{TZ};
3493         }
3494         if (defined $::_revision) {
3495                 if ($::_revision =~ /^(\d+):(\d+)$/) {
3496                         ($r_min, $r_max) = ($1, $2);
3497                 } elsif ($::_revision =~ /^\d+$/) {
3498                         $r_min = $r_max = $::_revision;
3499                 } else {
3500                         ::fatal "-r$::_revision is not supported, use ",
3501                                 "standard \'git log\' arguments instead\n";
3502                 }
3503         }
3505         config_pager();
3506         @args = (git_svn_log_cmd($r_min, $r_max, @args), @args);
3507         my $log = command_output_pipe(@args);
3508         run_pager();
3509         my (@k, $c, $d, $stat);
3510         my $esc_color = qr/(?:\033\[(?:(?:\d+;)*\d*)?m)*/;
3511         while (<$log>) {
3512                 if (/^${esc_color}commit ($::sha1_short)/o) {
3513                         my $cmt = $1;
3514                         if ($c && cmt_showable($c) && $c->{r} != $r_last) {
3515                                 $r_last = $c->{r};
3516                                 process_commit($c, $r_min, $r_max, \@k) or
3517                                                                 goto out;
3518                         }
3519                         $d = undef;
3520                         $c = { c => $cmt };
3521                 } elsif (/^${esc_color}author (.+) (\d+) ([\-\+]?\d+)$/o) {
3522                         get_author_info($c, $1, $2, $3);
3523                 } elsif (/^${esc_color}(?:tree|parent|committer) /o) {
3524                         # ignore
3525                 } elsif (/^${esc_color}:\d{6} \d{6} $::sha1_short/o) {
3526                         push @{$c->{raw}}, $_;
3527                 } elsif (/^${esc_color}[ACRMDT]\t/) {
3528                         # we could add $SVN->{svn_path} here, but that requires
3529                         # remote access at the moment (repo_path_split)...
3530                         s#^(${esc_color})([ACRMDT])\t#$1   $2 #o;
3531                         push @{$c->{changed}}, $_;
3532                 } elsif (/^${esc_color}diff /o) {
3533                         $d = 1;
3534                         push @{$c->{diff}}, $_;
3535                 } elsif ($d) {
3536                         push @{$c->{diff}}, $_;
3537                 } elsif (/^\ .+\ \|\s*\d+\ $esc_color[\+\-]*
3538                           $esc_color*[\+\-]*$esc_color$/x) {
3539                         $stat = 1;
3540                         push @{$c->{stat}}, $_;
3541                 } elsif ($stat && /^ \d+ files changed, \d+ insertions/) {
3542                         push @{$c->{stat}}, $_;
3543                         $stat = undef;
3544                 } elsif (/^${esc_color}    (git-svn-id:.+)$/o) {
3545                         ($c->{url}, $c->{r}, undef) = ::extract_metadata($1);
3546                 } elsif (s/^${esc_color}    //o) {
3547                         push @{$c->{l}}, $_;
3548                 }
3549         }
3550         if ($c && defined $c->{r} && $c->{r} != $r_last) {
3551                 $r_last = $c->{r};
3552                 process_commit($c, $r_min, $r_max, \@k);
3553         }
3554         if (@k) {
3555                 my $swap = $r_max;
3556                 $r_max = $r_min;
3557                 $r_min = $swap;
3558                 process_commit($_, $r_min, $r_max) foreach reverse @k;
3559         }
3560 out:
3561         close $log;
3562         print '-' x72,"\n" unless $incremental || $oneline;
3565 package Git::SVN::Migration;
3566 # these version numbers do NOT correspond to actual version numbers
3567 # of git nor git-svn.  They are just relative.
3569 # v0 layout: .git/$id/info/url, refs/heads/$id-HEAD
3571 # v1 layout: .git/$id/info/url, refs/remotes/$id
3573 # v2 layout: .git/svn/$id/info/url, refs/remotes/$id
3575 # v3 layout: .git/svn/$id, refs/remotes/$id
3576 #            - info/url may remain for backwards compatibility
3577 #            - this is what we migrate up to this layout automatically,
3578 #            - this will be used by git svn init on single branches
3579 # v3.1 layout (auto migrated):
3580 #            - .rev_db => .rev_db.$UUID, .rev_db will remain as a symlink
3581 #              for backwards compatibility
3583 # v4 layout: .git/svn/$repo_id/$id, refs/remotes/$repo_id/$id
3584 #            - this is only created for newly multi-init-ed
3585 #              repositories.  Similar in spirit to the
3586 #              --use-separate-remotes option in git-clone (now default)
3587 #            - we do not automatically migrate to this (following
3588 #              the example set by core git)
3589 use strict;
3590 use warnings;
3591 use Carp qw/croak/;
3592 use File::Path qw/mkpath/;
3593 use File::Basename qw/dirname basename/;
3594 use vars qw/$_minimize/;
3596 sub migrate_from_v0 {
3597         my $git_dir = $ENV{GIT_DIR};
3598         return undef unless -d $git_dir;
3599         my ($fh, $ctx) = command_output_pipe(qw/rev-parse --symbolic --all/);
3600         my $migrated = 0;
3601         while (<$fh>) {
3602                 chomp;
3603                 my ($id, $orig_ref) = ($_, $_);
3604                 next unless $id =~ s#^refs/heads/(.+)-HEAD$#$1#;
3605                 next unless -f "$git_dir/$id/info/url";
3606                 my $new_ref = "refs/remotes/$id";
3607                 if (::verify_ref("$new_ref^0")) {
3608                         print STDERR "W: $orig_ref is probably an old ",
3609                                      "branch used by an ancient version of ",
3610                                      "git-svn.\n",
3611                                      "However, $new_ref also exists.\n",
3612                                      "We will not be able ",
3613                                      "to use this branch until this ",
3614                                      "ambiguity is resolved.\n";
3615                         next;
3616                 }
3617                 print STDERR "Migrating from v0 layout...\n" if !$migrated;
3618                 print STDERR "Renaming ref: $orig_ref => $new_ref\n";
3619                 command_noisy('update-ref', $new_ref, $orig_ref);
3620                 command_noisy('update-ref', '-d', $orig_ref, $orig_ref);
3621                 $migrated++;
3622         }
3623         command_close_pipe($fh, $ctx);
3624         print STDERR "Done migrating from v0 layout...\n" if $migrated;
3625         $migrated;
3628 sub migrate_from_v1 {
3629         my $git_dir = $ENV{GIT_DIR};
3630         my $migrated = 0;
3631         return $migrated unless -d $git_dir;
3632         my $svn_dir = "$git_dir/svn";
3634         # just in case somebody used 'svn' as their $id at some point...
3635         return $migrated if -d $svn_dir && ! -f "$svn_dir/info/url";
3637         print STDERR "Migrating from a git-svn v1 layout...\n";
3638         mkpath([$svn_dir]);
3639         print STDERR "Data from a previous version of git-svn exists, but\n\t",
3640                      "$svn_dir\n\t(required for this version ",
3641                      "($::VERSION) of git-svn) does not. exist\n";
3642         my ($fh, $ctx) = command_output_pipe(qw/rev-parse --symbolic --all/);
3643         while (<$fh>) {
3644                 my $x = $_;
3645                 next unless $x =~ s#^refs/remotes/##;
3646                 chomp $x;
3647                 next unless -f "$git_dir/$x/info/url";
3648                 my $u = eval { ::file_to_s("$git_dir/$x/info/url") };
3649                 next unless $u;
3650                 my $dn = dirname("$git_dir/svn/$x");
3651                 mkpath([$dn]) unless -d $dn;
3652                 if ($x eq 'svn') { # they used 'svn' as GIT_SVN_ID:
3653                         mkpath(["$git_dir/svn/svn"]);
3654                         print STDERR " - $git_dir/$x/info => ",
3655                                         "$git_dir/svn/$x/info\n";
3656                         rename "$git_dir/$x/info", "$git_dir/svn/$x/info" or
3657                                croak "$!: $x";
3658                         # don't worry too much about these, they probably
3659                         # don't exist with repos this old (save for index,
3660                         # and we can easily regenerate that)
3661                         foreach my $f (qw/unhandled.log index .rev_db/) {
3662                                 rename "$git_dir/$x/$f", "$git_dir/svn/$x/$f";
3663                         }
3664                 } else {
3665                         print STDERR " - $git_dir/$x => $git_dir/svn/$x\n";
3666                         rename "$git_dir/$x", "$git_dir/svn/$x" or
3667                                croak "$!: $x";
3668                 }
3669                 $migrated++;
3670         }
3671         command_close_pipe($fh, $ctx);
3672         print STDERR "Done migrating from a git-svn v1 layout\n";
3673         $migrated;
3676 sub read_old_urls {
3677         my ($l_map, $pfx, $path) = @_;
3678         my @dir;
3679         foreach (<$path/*>) {
3680                 if (-r "$_/info/url") {
3681                         $pfx .= '/' if $pfx && $pfx !~ m!/$!;
3682                         my $ref_id = $pfx . basename $_;
3683                         my $url = ::file_to_s("$_/info/url");
3684                         $l_map->{$ref_id} = $url;
3685                 } elsif (-d $_) {
3686                         push @dir, $_;
3687                 }
3688         }
3689         foreach (@dir) {
3690                 my $x = $_;
3691                 $x =~ s!^\Q$ENV{GIT_DIR}\E/svn/!!o;
3692                 read_old_urls($l_map, $x, $_);
3693         }
3696 sub migrate_from_v2 {
3697         my @cfg = command(qw/config -l/);
3698         return if grep /^svn-remote\..+\.url=/, @cfg;
3699         my %l_map;
3700         read_old_urls(\%l_map, '', "$ENV{GIT_DIR}/svn");
3701         my $migrated = 0;
3703         foreach my $ref_id (sort keys %l_map) {
3704                 eval { Git::SVN->init($l_map{$ref_id}, '', undef, $ref_id) };
3705                 if ($@) {
3706                         Git::SVN->init($l_map{$ref_id}, '', $ref_id, $ref_id);
3707                 }
3708                 $migrated++;
3709         }
3710         $migrated;
3713 sub minimize_connections {
3714         my $r = Git::SVN::read_all_remotes();
3715         my $new_urls = {};
3716         my $root_repos = {};
3717         foreach my $repo_id (keys %$r) {
3718                 my $url = $r->{$repo_id}->{url} or next;
3719                 my $fetch = $r->{$repo_id}->{fetch} or next;
3720                 my $ra = Git::SVN::Ra->new($url);
3722                 # skip existing cases where we already connect to the root
3723                 if (($ra->{url} eq $ra->{repos_root}) ||
3724                     (Git::SVN::sanitize_remote_name($ra->{repos_root}) eq
3725                      $repo_id)) {
3726                         $root_repos->{$ra->{url}} = $repo_id;
3727                         next;
3728                 }
3730                 my $root_ra = Git::SVN::Ra->new($ra->{repos_root});
3731                 my $root_path = $ra->{url};
3732                 $root_path =~ s#^\Q$ra->{repos_root}\E(/|$)##;
3733                 foreach my $path (keys %$fetch) {
3734                         my $ref_id = $fetch->{$path};
3735                         my $gs = Git::SVN->new($ref_id, $repo_id, $path);
3737                         # make sure we can read when connecting to
3738                         # a higher level of a repository
3739                         my ($last_rev, undef) = $gs->last_rev_commit;
3740                         if (!defined $last_rev) {
3741                                 $last_rev = eval {
3742                                         $root_ra->get_latest_revnum;
3743                                 };
3744                                 next if $@;
3745                         }
3746                         my $new = $root_path;
3747                         $new .= length $path ? "/$path" : '';
3748                         eval {
3749                                 $root_ra->get_log([$new], $last_rev, $last_rev,
3750                                                   0, 0, 1, sub { });
3751                         };
3752                         next if $@;
3753                         $new_urls->{$ra->{repos_root}}->{$new} =
3754                                 { ref_id => $ref_id,
3755                                   old_repo_id => $repo_id,
3756                                   old_path => $path };
3757                 }
3758         }
3760         my @emptied;
3761         foreach my $url (keys %$new_urls) {
3762                 # see if we can re-use an existing [svn-remote "repo_id"]
3763                 # instead of creating a(n ugly) new section:
3764                 my $repo_id = $root_repos->{$url} ||
3765                               Git::SVN::sanitize_remote_name($url);
3767                 my $fetch = $new_urls->{$url};
3768                 foreach my $path (keys %$fetch) {
3769                         my $x = $fetch->{$path};
3770                         Git::SVN->init($url, $path, $repo_id, $x->{ref_id});
3771                         my $pfx = "svn-remote.$x->{old_repo_id}";
3773                         my $old_fetch = quotemeta("$x->{old_path}:".
3774                                                   "refs/remotes/$x->{ref_id}");
3775                         command_noisy(qw/config --unset/,
3776                                       "$pfx.fetch", '^'. $old_fetch . '$');
3777                         delete $r->{$x->{old_repo_id}}->
3778                                {fetch}->{$x->{old_path}};
3779                         if (!keys %{$r->{$x->{old_repo_id}}->{fetch}}) {
3780                                 command_noisy(qw/config --unset/,
3781                                               "$pfx.url");
3782                                 push @emptied, $x->{old_repo_id}
3783                         }
3784                 }
3785         }
3786         if (@emptied) {
3787                 my $file = $ENV{GIT_CONFIG} || $ENV{GIT_CONFIG_LOCAL} ||
3788                            "$ENV{GIT_DIR}/config";
3789                 print STDERR <<EOF;
3790 The following [svn-remote] sections in your config file ($file) are empty
3791 and can be safely removed:
3792 EOF
3793                 print STDERR "[svn-remote \"$_\"]\n" foreach @emptied;
3794         }
3797 sub migration_check {
3798         migrate_from_v0();
3799         migrate_from_v1();
3800         migrate_from_v2();
3801         minimize_connections() if $_minimize;
3804 package Git::IndexInfo;
3805 use strict;
3806 use warnings;
3807 use Git qw/command_input_pipe command_close_pipe/;
3809 sub new {
3810         my ($class) = @_;
3811         my ($gui, $ctx) = command_input_pipe(qw/update-index -z --index-info/);
3812         bless { gui => $gui, ctx => $ctx, nr => 0}, $class;
3815 sub remove {
3816         my ($self, $path) = @_;
3817         if (print { $self->{gui} } '0 ', 0 x 40, "\t", $path, "\0") {
3818                 return ++$self->{nr};
3819         }
3820         undef;
3823 sub update {
3824         my ($self, $mode, $hash, $path) = @_;
3825         if (print { $self->{gui} } $mode, ' ', $hash, "\t", $path, "\0") {
3826                 return ++$self->{nr};
3827         }
3828         undef;
3831 sub DESTROY {
3832         my ($self) = @_;
3833         command_close_pipe($self->{gui}, $self->{ctx});
3836 package Git::SVN::GlobSpec;
3837 use strict;
3838 use warnings;
3840 sub new {
3841         my ($class, $glob) = @_;
3842         my $re = $glob;
3843         $re =~ s!/+$!!g; # no need for trailing slashes
3844         my $nr = ($re =~ s!^(.*)\*(.*)$!\(\[^/\]+\)!g);
3845         my ($left, $right) = ($1, $2);
3846         if ($nr > 1) {
3847                 die "Only one '*' wildcard expansion ",
3848                     "is supported (got $nr): '$glob'\n";
3849         } elsif ($nr == 0) {
3850                 die "One '*' is needed for glob: '$glob'\n";
3851         }
3852         $re = quotemeta($left) . $re . quotemeta($right);
3853         if (length $left && !($left =~ s!/+$!!g)) {
3854                 die "Missing trailing '/' on left side of: '$glob' ($left)\n";
3855         }
3856         if (length $right && !($right =~ s!^/+!!g)) {
3857                 die "Missing leading '/' on right side of: '$glob' ($right)\n";
3858         }
3859         my $left_re = qr/^\/\Q$left\E(\/|$)/;
3860         bless { left => $left, right => $right, left_regex => $left_re,
3861                 regex => qr/$re/, glob => $glob }, $class;
3864 sub full_path {
3865         my ($self, $path) = @_;
3866         return (length $self->{left} ? "$self->{left}/" : '') .
3867                $path . (length $self->{right} ? "/$self->{right}" : '');
3870 __END__
3872 Data structures:
3875 $remotes = { # returned by read_all_remotes()
3876         'svn' => {
3877                 # svn-remote.svn.url=https://svn.musicpd.org
3878                 url => 'https://svn.musicpd.org',
3879                 # svn-remote.svn.fetch=mpd/trunk:trunk
3880                 fetch => {
3881                         'mpd/trunk' => 'trunk',
3882                 },
3883                 # svn-remote.svn.tags=mpd/tags/*:tags/*
3884                 tags => {
3885                         path => {
3886                                 left => 'mpd/tags',
3887                                 right => '',
3888                                 regex => qr!mpd/tags/([^/]+)$!,
3889                                 glob => 'tags/*',
3890                         },
3891                         ref => {
3892                                 left => 'tags',
3893                                 right => '',
3894                                 regex => qr!tags/([^/]+)$!,
3895                                 glob => 'tags/*',
3896                         },
3897                 }
3898         }
3899 };
3901 $log_entry hashref as returned by libsvn_log_entry()
3903         log => 'whitespace-formatted log entry
3904 ',                                              # trailing newline is preserved
3905         revision => '8',                        # integer
3906         date => '2004-02-24T17:01:44.108345Z',  # commit date
3907         author => 'committer name'
3908 };
3911 # this is generated by generate_diff();
3912 @mods = array of diff-index line hashes, each element represents one line
3913         of diff-index output
3915 diff-index line ($m hash)
3917         mode_a => first column of diff-index output, no leading ':',
3918         mode_b => second column of diff-index output,
3919         sha1_b => sha1sum of the final blob,
3920         chg => change type [MCRADT],
3921         file_a => original file name of a file (iff chg is 'C' or 'R')
3922         file_b => new/current file name of a file (any chg)
3926 # retval of read_url_paths{,_all}();
3927 $l_map = {
3928         # repository root url
3929         'https://svn.musicpd.org' => {
3930                 # repository path               # GIT_SVN_ID
3931                 'mpd/trunk'             =>      'trunk',
3932                 'mpd/tags/0.11.5'       =>      'tags/0.11.5',
3933         },
3936 Notes:
3937         I don't trust the each() function on unless I created %hash myself
3938         because the internal iterator may not have started at base.