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