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