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