Code

git-svn: convert 'set-tree' command to use Git::SVN
[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                 $SVN_URL
8                 $GIT_SVN_INDEX $GIT_SVN
9                 $GIT_DIR $GIT_SVN_DIR $REVDB
10                 $_follow_parent $sha1 $sha1_short $_revision
11                 $_cp_remote $_upgrade $_rmdir $_q $_cp_similarity
12                 $_find_copies_harder $_l $_authors %users/;
13 $AUTHOR = 'Eric Wong <normalperson@yhbt.net>';
14 $VERSION = '@@GIT_VERSION@@';
16 use Cwd qw/abs_path/;
17 $GIT_DIR = abs_path($ENV{GIT_DIR} || '.git');
18 $ENV{GIT_DIR} = $GIT_DIR;
20 my $LC_ALL = $ENV{LC_ALL};
21 $Git::SVN::Log::TZ = $ENV{TZ};
22 # make sure the svn binary gives consistent output between locales and TZs:
23 $ENV{TZ} = 'UTC';
24 $ENV{LC_ALL} = 'C';
25 $| = 1; # unbuffer STDOUT
27 sub fatal (@) { print STDERR @_; exit 1 }
28 require SVN::Core; # use()-ing this causes segfaults for me... *shrug*
29 require SVN::Ra;
30 require SVN::Delta;
31 if ($SVN::Core::VERSION lt '1.1.0') {
32         fatal "Need SVN::Core 1.1.0 or better (got $SVN::Core::VERSION)\n";
33 }
34 push @Git::SVN::Ra::ISA, 'SVN::Ra';
35 push @SVN::Git::Editor::ISA, 'SVN::Delta::Editor';
36 push @SVN::Git::Fetcher::ISA, 'SVN::Delta::Editor';
37 use Carp qw/croak/;
38 use IO::File qw//;
39 use File::Basename qw/dirname basename/;
40 use File::Path qw/mkpath/;
41 use Getopt::Long qw/:config gnu_getopt no_ignore_case auto_abbrev pass_through/;
42 use IPC::Open3;
43 use Git;
45 BEGIN {
46         my $s;
47         foreach (qw/command command_oneline command_noisy command_output_pipe
48                     command_input_pipe command_close_pipe/) {
49                 $s .= "*SVN::Git::Editor::$_ = *SVN::Git::Fetcher::$_ = ".
50                       "*Git::SVN::Log::$_ = *Git::SVN::$_ = *$_ = *Git::$_; ";
51         }
52         eval $s;
53 }
55 my ($SVN);
57 my $_optimize_commits = 1 unless $ENV{GIT_SVN_NO_OPTIMIZE_COMMITS};
58 $sha1 = qr/[a-f\d]{40}/;
59 $sha1_short = qr/[a-f\d]{4,40}/;
60 my ($_stdin, $_help, $_edit,
61         $_repack, $_repack_nr, $_repack_flags,
62         $_message, $_file, $_no_metadata,
63         $_template, $_shared, $_no_default_regex, $_no_graft_copy,
64         $_version, $_upgrade, $_branch_all_refs, @_opt_m,
65         $_merge, $_strategy, $_dry_run,
66         $_prefix);
67 my (@_branch_from, %tree_map);
68 my @repo_path_split_cache;
70 my %fc_opts = ( 'branch|b=s' => \@_branch_from,
71                 'follow-parent|follow' => \$_follow_parent,
72                 'branch-all-refs|B' => \$_branch_all_refs,
73                 'authors-file|A=s' => \$_authors,
74                 'repack:i' => \$_repack,
75                 'no-metadata' => \$_no_metadata,
76                 'quiet|q' => \$_q,
77                 'username=s' => \$Git::SVN::Prompt::_username,
78                 'config-dir=s' => \$Git::SVN::Ra::config_dir,
79                 'no-auth-cache' => \$Git::SVN::Prompt::_no_auth_cache,
80                 'repack-flags|repack-args|repack-opts=s' => \$_repack_flags);
82 my ($_trunk, $_tags, $_branches);
83 my %multi_opts = ( 'trunk|T=s' => \$_trunk,
84                 'tags|t=s' => \$_tags,
85                 'branches|b=s' => \$_branches );
86 my %init_opts = ( 'template=s' => \$_template, 'shared' => \$_shared );
87 my %cmt_opts = ( 'edit|e' => \$_edit,
88                 'rmdir' => \$_rmdir,
89                 'find-copies-harder' => \$_find_copies_harder,
90                 'l=i' => \$_l,
91                 'copy-similarity|C=i'=> \$_cp_similarity
92 );
94 my %cmd = (
95         fetch => [ \&cmd_fetch, "Download new revisions from SVN",
96                         { 'revision|r=s' => \$_revision, %fc_opts } ],
97         init => [ \&cmd_init, "Initialize a repo for tracking" .
98                           " (requires URL argument)",
99                           \%init_opts ],
100         dcommit => [ \&cmd_dcommit,
101                      'Commit several diffs to merge with upstream',
102                         { 'merge|m|M' => \$_merge,
103                           'strategy|s=s' => \$_strategy,
104                           'dry-run|n' => \$_dry_run,
105                         %cmt_opts, %fc_opts } ],
106         'set-tree' => [ \&cmd_set_tree,
107                         "Set an SVN repository to a git tree-ish",
108                         { 'stdin|' => \$_stdin, %cmt_opts, %fc_opts, } ],
109         'show-ignore' => [ \&cmd_show_ignore, "Show svn:ignore listings",
110                         { 'revision|r=i' => \$_revision } ],
111         rebuild => [ \&cmd_rebuild, "Rebuild git-svn metadata (after git clone)",
112                         { 'copy-remote|remote=s' => \$_cp_remote,
113                           'upgrade' => \$_upgrade } ],
114         'graft-branches' => [ \&graft_branches,
115                         'Detect merges/branches from already imported history',
116                         { 'merge-rx|m' => \@_opt_m,
117                           'branch|b=s' => \@_branch_from,
118                           'branch-all-refs|B' => \$_branch_all_refs,
119                           'no-default-regex' => \$_no_default_regex,
120                           'no-graft-copy' => \$_no_graft_copy } ],
121         'multi-init' => [ \&cmd_multi_init,
122                         'Initialize multiple trees (like git-svnimport)',
123                         { %multi_opts, %init_opts,
124                          'revision|r=i' => \$_revision,
125                          'username=s' => \$Git::SVN::Prompt::_username,
126                          'config-dir=s' => \$Git::SVN::Ra::config_dir,
127                          'no-auth-cache' => \$Git::SVN::Prompt::_no_auth_cache,
128                          'prefix=s' => \$_prefix,
129                         } ],
130         'multi-fetch' => [ \&cmd_multi_fetch,
131                         'Fetch multiple trees (like git-svnimport)',
132                         \%fc_opts ],
133         'log' => [ \&Git::SVN::Log::cmd_show_log, 'Show commit logs',
134                         { 'limit=i' => \$Git::SVN::Log::limit,
135                           'revision|r=s' => \$_revision,
136                           'verbose|v' => \$Git::SVN::Log::verbose,
137                           'incremental' => \$Git::SVN::Log::incremental,
138                           'oneline' => \$Git::SVN::Log::oneline,
139                           'show-commit' => \$Git::SVN::Log::show_commit,
140                           'non-recursive' => \$Git::SVN::Log::non_recursive,
141                           'authors-file|A=s' => \$_authors,
142                           'color' => \$Git::SVN::Log::color,
143                           'pager=s' => \$Git::SVN::Log::pager,
144                         } ],
145         'commit-diff' => [ \&cmd_commit_diff,
146                            'Commit a diff between two trees',
147                         { 'message|m=s' => \$_message,
148                           'file|F=s' => \$_file,
149                           'revision|r=s' => \$_revision,
150                         %cmt_opts } ],
151 );
153 my $cmd;
154 for (my $i = 0; $i < @ARGV; $i++) {
155         if (defined $cmd{$ARGV[$i]}) {
156                 $cmd = $ARGV[$i];
157                 splice @ARGV, $i, 1;
158                 last;
159         }
160 };
162 my %opts = %{$cmd{$cmd}->[2]} if (defined $cmd);
164 read_repo_config(\%opts);
165 my $rv = GetOptions(%opts, 'help|H|h' => \$_help,
166                                 'version|V' => \$_version,
167                                 'id|i=s' => \$GIT_SVN);
168 exit 1 if (!$rv && $cmd ne 'log');
170 set_default_vals();
171 usage(0) if $_help;
172 version() if $_version;
173 usage(1) unless defined $cmd;
174 init_vars();
175 load_authors() if $_authors;
176 load_all_refs() if $_branch_all_refs;
177 migration_check() unless $cmd =~ /^(?:init|rebuild|multi-init|commit-diff)$/;
178 $cmd{$cmd}->[0]->(@ARGV);
179 exit 0;
181 ####################### primary functions ######################
182 sub usage {
183         my $exit = shift || 0;
184         my $fd = $exit ? \*STDERR : \*STDOUT;
185         print $fd <<"";
186 git-svn - bidirectional operations between a single Subversion tree and git
187 Usage: $0 <command> [options] [arguments]\n
189         print $fd "Available commands:\n" unless $cmd;
191         foreach (sort keys %cmd) {
192                 next if $cmd && $cmd ne $_;
193                 print $fd '  ',pack('A17',$_),$cmd{$_}->[1],"\n";
194                 foreach (keys %{$cmd{$_}->[2]}) {
195                         # prints out arguments as they should be passed:
196                         my $x = s#[:=]s$## ? '<arg>' : s#[:=]i$## ? '<num>' : '';
197                         print $fd ' ' x 21, join(', ', map { length $_ > 1 ?
198                                                         "--$_" : "-$_" }
199                                                 split /\|/,$_)," $x\n";
200                 }
201         }
202         print $fd <<"";
203 \nGIT_SVN_ID may be set in the environment or via the --id/-i switch to an
204 arbitrary identifier if you're tracking multiple SVN branches/repositories in
205 one git repository and want to keep them separate.  See git-svn(1) for more
206 information.
208         exit $exit;
211 sub version {
212         print "git-svn version $VERSION (svn $SVN::Core::VERSION)\n";
213         exit 0;
216 sub cmd_rebuild {
217         my $url = shift;
218         my $gs = $url ? Git::SVN->init(undef, $url)
219                       : eval { Git::SVN->new };
220         $gs ||= Git::SVN->_new;
221         if (!verify_ref($gs->refname.'^0')) {
222                 $gs->copy_remote_ref;
223         }
224         if ($_upgrade) {
225                 command_noisy('update-ref',$gs->refname, $gs->{id}.'-HEAD');
226         } else {
227                 $gs->check_upgrade_needed;
228         }
230         my ($rev_list, $ctx) = command_output_pipe("rev-list", $gs->refname);
231         my $latest;
232         my $svn_uuid;
233         while (<$rev_list>) {
234                 chomp;
235                 my $c = $_;
236                 fatal "Non-SHA1: $c\n" unless $c =~ /^$sha1$/o;
237                 my ($url, $rev, $uuid) = cmt_metadata($c);
239                 # ignore merges (from set-tree)
240                 next if (!defined $rev || !$uuid);
242                 # if we merged or otherwise started elsewhere, this is
243                 # how we break out of it
244                 if ((defined $svn_uuid && ($uuid ne $svn_uuid)) ||
245                     ($gs->{url} && $url && ($url ne $gs->{url}))) {
246                         next;
247                 }
249                 unless (defined $latest) {
250                         if (!$gs->{url} && !$url) {
251                                 fatal "SVN repository location required\n";
252                         }
253                         $gs = Git::SVN->init(undef, $url);
254                         $latest = $rev;
255                 }
256                 $gs->rev_db_set($rev, $c);
257                 print "r$rev = $c\n";
258         }
259         command_close_pipe($rev_list, $ctx);
262 sub do_git_init_db {
263         unless (-d $ENV{GIT_DIR}) {
264                 my @init_db = ('init');
265                 push @init_db, "--template=$_template" if defined $_template;
266                 push @init_db, "--shared" if defined $_shared;
267                 command_noisy(@init_db);
268         }
271 sub cmd_init {
272         my $url = shift or die "SVN repository location required " .
273                                 "as a command-line argument\n";
274         if (my $repo_path = shift) {
275                 unless (-d $repo_path) {
276                         mkpath([$repo_path]);
277                 }
278                 chdir $repo_path or croak $!;
279                 $ENV{GIT_DIR} = $repo_path . "/.git";
280         }
281         do_git_init_db();
283         Git::SVN->init(undef, $url);
286 sub cmd_fetch {
287         my $gs = Git::SVN->new;
288         $gs->fetch(@_);
289         if ($gs->{last_commit} && !verify_ref('refs/heads/master^0')) {
290                 command_noisy(qw(update-ref refs/heads/master),
291                               $gs->{last_commit});
292         }
295 sub cmd_set_tree {
296         my (@commits) = @_;
297         if ($_stdin || !@commits) {
298                 print "Reading from stdin...\n";
299                 @commits = ();
300                 while (<STDIN>) {
301                         if (/\b($sha1_short)\b/o) {
302                                 unshift @commits, $1;
303                         }
304                 }
305         }
306         my @revs;
307         foreach my $c (@commits) {
308                 my @tmp = command('rev-parse',$c);
309                 if (scalar @tmp == 1) {
310                         push @revs, $tmp[0];
311                 } elsif (scalar @tmp > 1) {
312                         push @revs, reverse(command('rev-list',@tmp));
313                 } else {
314                         fatal "Failed to rev-parse $c\n";
315                 }
316         }
317         my $gs = Git::SVN->new;
318         my ($r_last, $cmt_last) = $gs->last_rev_commit;
319         $gs->fetch;
320         if ($r_last != $gs->{last_rev}) {
321                 fatal "There are new revisions that were fetched ",
322                       "and need to be merged (or acknowledged) ",
323                       "before committing.\nlast rev: $r_last\n",
324                       " current: $gs->{last_rev}\n";
325         }
326         $gs->set_tree($_) foreach @revs;
327         print "Done committing ",scalar @revs," revisions to SVN\n";
330 sub cmd_dcommit {
331         my $head = shift;
332         my $gs = Git::SVN->new;
333         $head ||= 'HEAD';
334         my @refs = command(qw/rev-list --no-merges/, $gs->refname."..$head");
335         my $last_rev;
336         foreach my $d (reverse @refs) {
337                 if (!verify_ref("$d~1")) {
338                         fatal "Commit $d\n",
339                               "has no parent commit, and therefore ",
340                               "nothing to diff against.\n",
341                               "You should be working from a repository ",
342                               "originally created by git-svn\n";
343                 }
344                 unless (defined $last_rev) {
345                         (undef, $last_rev, undef) = cmt_metadata("$d~1");
346                         unless (defined $last_rev) {
347                                 fatal "Unable to extract revision information ",
348                                       "from commit $d~1\n";
349                         }
350                 }
351                 if ($_dry_run) {
352                         print "diff-tree $d~1 $d\n";
353                 } else {
354                         my $ra = $gs->ra;
355                         my $pool = SVN::Pool->new;
356                         my %ed_opts = ( r => $last_rev,
357                                         ra => $ra->dup,
358                                         svn_path => $ra->{svn_path} );
359                         my $ed = SVN::Git::Editor->new(\%ed_opts,
360                                          $ra->get_commit_editor($::_message,
361                                          sub { print "Committed r$_[0]\n";
362                                                $last_rev = $_[0]; }),
363                                          $pool);
364                         my $mods = $ed->apply_diff("$d~1", $d);
365                         if (@$mods == 0) {
366                                 print "No changes\n$d~1 == $d\n";
367                         }
368                 }
369         }
370         return if $_dry_run;
371         $gs->fetch;
372         # we always want to rebase against the current HEAD, not any
373         # head that was passed to us
374         my @diff = command('diff-tree', 'HEAD', $gs->refname, '--');
375         my @finish;
376         if (@diff) {
377                 @finish = qw/rebase/;
378                 push @finish, qw/--merge/ if $_merge;
379                 push @finish, "--strategy=$_strategy" if $_strategy;
380                 print STDERR "W: HEAD and ", $gs->refname, " differ, ",
381                              "using @finish:\n", "@diff";
382         } else {
383                 print "No changes between current HEAD and ",
384                       $gs->refname, "\nResetting to the latest ",
385                       $gs->refname, "\n";
386                 @finish = qw/reset --mixed/;
387         }
388         command_noisy(@finish, $gs->refname);
391 sub cmd_show_ignore {
392         my $gs = Git::SVN->new;
393         my $r = (defined $_revision ? $_revision : $gs->ra->get_latest_revnum);
394         $gs->traverse_ignore(\*STDOUT, '', $r);
397 sub graft_branches {
398         my $gr_file = "$GIT_DIR/info/grafts";
399         my ($grafts, $comments) = read_grafts($gr_file);
400         my $gr_sha1;
402         if (%$grafts) {
403                 # temporarily disable our grafts file to make this idempotent
404                 chomp($gr_sha1 = command(qw/hash-object -w/,$gr_file));
405                 rename $gr_file, "$gr_file~$gr_sha1" or croak $!;
406         }
408         my $l_map = read_url_paths();
409         my @re = map { qr/$_/is } @_opt_m if @_opt_m;
410         unless ($_no_default_regex) {
411                 push @re, (qr/\b(?:merge|merging|merged)\s+with\s+([\w\.\-]+)/i,
412                         qr/\b(?:merge|merging|merged)\s+([\w\.\-]+)/i,
413                         qr/\b(?:from|of)\s+([\w\.\-]+)/i );
414         }
415         foreach my $u (keys %$l_map) {
416                 if (@re) {
417                         foreach my $p (keys %{$l_map->{$u}}) {
418                                 graft_merge_msg($grafts,$l_map,$u,$p,@re);
419                         }
420                 }
421                 unless ($_no_graft_copy) {
422                         graft_file_copy_lib($grafts,$l_map,$u);
423                 }
424         }
425         graft_tree_joins($grafts);
427         write_grafts($grafts, $comments, $gr_file);
428         unlink "$gr_file~$gr_sha1" if $gr_sha1;
431 sub cmd_multi_init {
432         my $url = shift;
433         unless (defined $_trunk || defined $_branches || defined $_tags) {
434                 usage(1);
435         }
436         do_git_init_db();
437         $_prefix = '' unless defined $_prefix;
438         if (defined $_trunk) {
439                 my $gs_trunk = eval { Git::SVN->new($_prefix . 'trunk') };
440                 unless ($gs_trunk) {
441                         my $trunk_url = complete_svn_url($url, $_trunk);
442                         $gs_trunk = Git::SVN->init($_prefix . 'trunk',
443                                                    $trunk_url);
444                         command_noisy('config', 'svn.trunk', $trunk_url);
445                 }
446         }
447         my $ra = $url ? Git::SVN::Ra->new($url) : undef;
448         complete_url_ls_init($ra, $_branches, '--branches/-b', $_prefix);
449         complete_url_ls_init($ra, $_tags, '--tags/-t', $_prefix . 'tags/');
452 sub cmd_multi_fetch {
453         # try to do trunk first, since branches/tags
454         # may be descended from it.
455         if (-e "$ENV{GIT_DIR}/svn/trunk/info/url") {
456                 my $gs = Git::SVN->new('trunk');
457                 $gs->fetch(@_);
458         }
459         rec_fetch('', "$ENV{GIT_DIR}/svn", @_);
462 # this command is special because it requires no metadata
463 sub cmd_commit_diff {
464         my ($ta, $tb, $url) = @_;
465         my $usage = "Usage: $0 commit-diff -r<revision> ".
466                     "<tree-ish> <tree-ish> [<URL>]\n";
467         fatal($usage) if (!defined $ta || !defined $tb);
468         if (!defined $url) {
469                 my $gs = eval { Git::SVN->new };
470                 if (!$gs) {
471                         fatal("Needed URL or usable git-svn --id in ",
472                               "the command-line\n", $usage);
473                 }
474                 $url = $gs->{url};
475         }
476         unless (defined $_revision) {
477                 fatal("-r|--revision is a required argument\n", $usage);
478         }
479         if (defined $_message && defined $_file) {
480                 fatal("Both --message/-m and --file/-F specified ",
481                       "for the commit message.\n",
482                       "I have no idea what you mean\n");
483         }
484         if (defined $_file) {
485                 $_message = file_to_s($_file);
486         } else {
487                 $_message ||= get_commit_entry($tb)->{log};
488         }
489         my $ra ||= Git::SVN::Ra->new($url);
490         my $r = $_revision;
491         if ($r eq 'HEAD') {
492                 $r = $ra->get_latest_revnum;
493         } elsif ($r !~ /^\d+$/) {
494                 die "revision argument: $r not understood by git-svn\n";
495         }
496         my $pool = SVN::Pool->new;
497         my %ed_opts = ( r => $r,
498                         ra => $ra->dup,
499                         svn_path => $ra->{svn_path} );
500         my $ed = SVN::Git::Editor->new(\%ed_opts,
501                                        $ra->get_commit_editor($_message,
502                                          sub { print "Committed r$_[0]\n" }),
503                                        $pool);
504         my $mods = $ed->apply_diff($ta, $tb);
505         if (@$mods == 0) {
506                 print "No changes\n$ta == $tb\n";
507         }
508         $pool->clear;
511 ########################### utility functions #########################
513 sub rec_fetch {
514         my ($pfx, $p, @args) = @_;
515         my @dir;
516         foreach (sort <$p/*>) {
517                 if (-r "$_/info/url") {
518                         $pfx .= '/' if $pfx && $pfx !~ m!/$!;
519                         my $id = $pfx . basename $_;
520                         next if $id eq 'trunk';
521                         my $gs = Git::SVN->new($id);
522                         $gs->fetch(@args);
523                 } elsif (-d $_) {
524                         push @dir, $_;
525                 }
526         }
527         foreach (@dir) {
528                 my $x = $_;
529                 $x =~ s!^\Q$ENV{GIT_DIR}\E/svn/!!o;
530                 rec_fetch($x, $_, @args);
531         }
534 sub complete_svn_url {
535         my ($url, $path) = @_;
536         $path =~ s#/+$##;
537         $url =~ s#/+$## if $url;
538         if ($path !~ m#^[a-z\+]+://#) {
539                 $path = '/' . $path if ($path !~ m#^/#);
540                 if (!defined $url || $url !~ m#^[a-z\+]+://#) {
541                         fatal("E: '$path' is not a complete URL ",
542                               "and a separate URL is not specified\n");
543                 }
544                 $path = $url . $path;
545         }
546         return $path;
549 sub complete_url_ls_init {
550         my ($ra, $path, $switch, $pfx) = @_;
551         unless ($path) {
552                 print STDERR "W: $switch not specified\n";
553                 return;
554         }
555         $path =~ s#/+$##;
556         if ($path =~ m#^[a-z\+]+://#) {
557                 $ra = Git::SVN::Ra->new($path);
558                 $path = '';
559         } else {
560                 $path =~ s#^/+##;
561                 unless ($ra) {
562                         fatal("E: '$path' is not a complete URL ",
563                               "and a separate URL is not specified\n");
564                 }
565         }
566         my $r = defined $_revision ? $_revision : $ra->get_latest_revnum;
567         my ($dirent, undef, undef) = $ra->get_dir($path, $r);
568         my $url = $ra->{url} . (length $path ? "/$path" : '');
569         foreach my $d (sort keys %$dirent) {
570                 next if ($dirent->{$d}->kind != $SVN::Node::dir);
571                 my $u =  "$url/$d";
572                 my $id = "$pfx$d";
573                 my $gs = eval { Git::SVN->new($id) };
574                 # don't try to init already existing refs
575                 unless ($gs) {
576                         print "init $u => $id\n";
577                         Git::SVN->init($id, $u);
578                 }
579         }
580         my ($n) = ($switch =~ /^--(\w+)/);
581         command_noisy('config', "svn.$n", $url);
584 sub common_prefix {
585         my $paths = shift;
586         my %common;
587         foreach (@$paths) {
588                 my @tmp = split m#/#, $_;
589                 my $p = '';
590                 while (my $x = shift @tmp) {
591                         $p .= "/$x";
592                         $common{$p} ||= 0;
593                         $common{$p}++;
594                 }
595         }
596         foreach (sort {length $b <=> length $a} keys %common) {
597                 if ($common{$_} == @$paths) {
598                         return $_;
599                 }
600         }
601         return '';
604 # grafts set here are 'stronger' in that they're based on actual tree
605 # matches, and won't be deleted from merge-base checking in write_grafts()
606 sub graft_tree_joins {
607         my $grafts = shift;
608         map_tree_joins() if (@_branch_from && !%tree_map);
609         return unless %tree_map;
611         git_svn_each(sub {
612                 my $i = shift;
613                 my @args = (qw/rev-list --pretty=raw/, "refs/remotes/$i");
614                 my ($fh, $ctx) = command_output_pipe(@args);
615                 while (<$fh>) {
616                         next unless /^commit ($sha1)$/o;
617                         my $c = $1;
618                         my ($t) = (<$fh> =~ /^tree ($sha1)$/o);
619                         next unless $tree_map{$t};
621                         my $l;
622                         do {
623                                 $l = readline $fh;
624                         } until ($l =~ /^committer (?:.+) (\d+) ([\-\+]?\d+)$/);
626                         my ($s, $tz) = ($1, $2);
627                         if ($tz =~ s/^\+//) {
628                                 $s += tz_to_s_offset($tz);
629                         } elsif ($tz =~ s/^\-//) {
630                                 $s -= tz_to_s_offset($tz);
631                         }
633                         my ($url_a, $r_a, $uuid_a) = cmt_metadata($c);
635                         foreach my $p (@{$tree_map{$t}}) {
636                                 next if $p eq $c;
637                                 my $mb = eval { command('merge-base', $c, $p) };
638                                 next unless ($@ || $?);
639                                 if (defined $r_a) {
640                                         # see if SVN says it's a relative
641                                         my ($url_b, $r_b, $uuid_b) =
642                                                         cmt_metadata($p);
643                                         next if (defined $url_b &&
644                                                         defined $url_a &&
645                                                         ($url_a eq $url_b) &&
646                                                         ($uuid_a eq $uuid_b));
647                                         if ($uuid_a eq $uuid_b) {
648                                                 if ($r_b < $r_a) {
649                                                         $grafts->{$c}->{$p} = 2;
650                                                         next;
651                                                 } elsif ($r_b > $r_a) {
652                                                         $grafts->{$p}->{$c} = 2;
653                                                         next;
654                                                 }
655                                         }
656                                 }
657                                 my $ct = get_commit_time($p);
658                                 if ($ct < $s) {
659                                         $grafts->{$c}->{$p} = 2;
660                                 } elsif ($ct > $s) {
661                                         $grafts->{$p}->{$c} = 2;
662                                 }
663                                 # what should we do when $ct == $s ?
664                         }
665                 }
666                 command_close_pipe($fh, $ctx);
667         });
670 sub graft_file_copy_lib {
671         my ($grafts, $l_map, $u) = @_;
672         my $tree_paths = $l_map->{$u};
673         my $pfx = common_prefix([keys %$tree_paths]);
674         my ($repo, $path) = repo_path_split($u.$pfx);
675         $SVN = Git::SVN::Ra->new($repo);
677         my ($base, $head) = libsvn_parse_revision();
678         my $inc = 1000;
679         my ($min, $max) = ($base, $head < $base+$inc ? $head : $base+$inc);
680         my $eh = $SVN::Error::handler;
681         $SVN::Error::handler = \&libsvn_skip_unknown_revs;
682         while (1) {
683                 $SVN->dup->get_log([$path], $min, $max, 0, 2, 1,
684                         sub {
685                                 libsvn_graft_file_copies($grafts, $tree_paths,
686                                                         $path, @_);
687                         });
688                 last if ($max >= $head);
689                 $min = $max + 1;
690                 $max += $inc;
691                 $max = $head if ($max > $head);
692         }
693         $SVN::Error::handler = $eh;
696 sub process_merge_msg_matches {
697         my ($grafts, $l_map, $u, $p, $c, @matches) = @_;
698         my (@strong, @weak);
699         foreach (@matches) {
700                 # merging with ourselves is not interesting
701                 next if $_ eq $p;
702                 if ($l_map->{$u}->{$_}) {
703                         push @strong, $_;
704                 } else {
705                         push @weak, $_;
706                 }
707         }
708         foreach my $w (@weak) {
709                 last if @strong;
710                 # no exact match, use branch name as regexp.
711                 my $re = qr/\Q$w\E/i;
712                 foreach (keys %{$l_map->{$u}}) {
713                         if (/$re/) {
714                                 push @strong, $l_map->{$u}->{$_};
715                                 last;
716                         }
717                 }
718                 last if @strong;
719                 $w = basename($w);
720                 $re = qr/\Q$w\E/i;
721                 foreach (keys %{$l_map->{$u}}) {
722                         if (/$re/) {
723                                 push @strong, $l_map->{$u}->{$_};
724                                 last;
725                         }
726                 }
727         }
728         my ($rev) = ($c->{m} =~ /^git-svn-id:\s(?:\S+?)\@(\d+)
729                                         \s(?:[a-f\d\-]+)$/xsm);
730         unless (defined $rev) {
731                 ($rev) = ($c->{m} =~/^git-svn-id:\s(\d+)
732                                         \@(?:[a-f\d\-]+)/xsm);
733                 return unless defined $rev;
734         }
735         foreach my $m (@strong) {
736                 my ($r0, $s0) = find_rev_before($rev, $m, 1);
737                 $grafts->{$c->{c}}->{$s0} = 1 if defined $s0;
738         }
741 sub graft_merge_msg {
742         my ($grafts, $l_map, $u, $p, @re) = @_;
744         my $x = $l_map->{$u}->{$p};
745         my $rl = rev_list_raw("refs/remotes/$x");
746         while (my $c = next_rev_list_entry($rl)) {
747                 foreach my $re (@re) {
748                         my (@br) = ($c->{m} =~ /$re/g);
749                         next unless @br;
750                         process_merge_msg_matches($grafts,$l_map,$u,$p,$c,@br);
751                 }
752         }
755 sub verify_ref {
756         my ($ref) = @_;
757         eval { command_oneline([ 'rev-parse', '--verify', $ref ],
758                                { STDERR => 0 }); };
761 sub repo_path_split {
762         my $full_url = shift;
763         $full_url =~ s#/+$##;
765         foreach (@repo_path_split_cache) {
766                 if ($full_url =~ s#$_##) {
767                         my $u = $1;
768                         $full_url =~ s#^/+##;
769                         return ($u, $full_url);
770                 }
771         }
772         my $tmp = Git::SVN::Ra->new($full_url);
773         return ($tmp->{repos_root}, $tmp->{svn_path});
776 sub setup_git_svn {
777         defined $SVN_URL or croak "SVN repository location required\n";
778         unless (-d $GIT_DIR) {
779                 croak "GIT_DIR=$GIT_DIR does not exist!\n";
780         }
781         mkpath([$GIT_SVN_DIR]);
782         mkpath(["$GIT_SVN_DIR/info"]);
783         open my $fh, '>>',$REVDB or croak $!;
784         close $fh;
785         s_to_file($SVN_URL,"$GIT_SVN_DIR/info/url");
789 sub get_tree_from_treeish {
790         my ($treeish) = @_;
791         # $treeish can be a symbolic ref, too:
792         my $type = command_oneline(qw/cat-file -t/, $treeish);
793         my $expected;
794         while ($type eq 'tag') {
795                 ($treeish, $type) = command(qw/cat-file tag/, $treeish);
796         }
797         if ($type eq 'commit') {
798                 $expected = (grep /^tree /, command(qw/cat-file commit/,
799                                                     $treeish))[0];
800                 ($expected) = ($expected =~ /^tree ($sha1)$/o);
801                 die "Unable to get tree from $treeish\n" unless $expected;
802         } elsif ($type eq 'tree') {
803                 $expected = $treeish;
804         } else {
805                 die "$treeish is a $type, expected tree, tag or commit\n";
806         }
807         return $expected;
810 sub get_diff {
811         my ($from, $treeish) = @_;
812         print "diff-tree $from $treeish\n";
813         my @diff_tree = qw(diff-tree -z -r);
814         if ($_cp_similarity) {
815                 push @diff_tree, "-C$_cp_similarity";
816         } else {
817                 push @diff_tree, '-C';
818         }
819         push @diff_tree, '--find-copies-harder' if $_find_copies_harder;
820         push @diff_tree, "-l$_l" if defined $_l;
821         push @diff_tree, $from, $treeish;
822         my ($diff_fh, $ctx) = command_output_pipe(@diff_tree);
823         local $/ = "\0";
824         my $state = 'meta';
825         my @mods;
826         while (<$diff_fh>) {
827                 chomp $_; # this gets rid of the trailing "\0"
828                 if ($state eq 'meta' && /^:(\d{6})\s(\d{6})\s
829                                         $sha1\s($sha1)\s([MTCRAD])\d*$/xo) {
830                         push @mods, {   mode_a => $1, mode_b => $2,
831                                         sha1_b => $3, chg => $4 };
832                         if ($4 =~ /^(?:C|R)$/) {
833                                 $state = 'file_a';
834                         } else {
835                                 $state = 'file_b';
836                         }
837                 } elsif ($state eq 'file_a') {
838                         my $x = $mods[$#mods] or croak "Empty array\n";
839                         if ($x->{chg} !~ /^(?:C|R)$/) {
840                                 croak "Error parsing $_, $x->{chg}\n";
841                         }
842                         $x->{file_a} = $_;
843                         $state = 'file_b';
844                 } elsif ($state eq 'file_b') {
845                         my $x = $mods[$#mods] or croak "Empty array\n";
846                         if (exists $x->{file_a} && $x->{chg} !~ /^(?:C|R)$/) {
847                                 croak "Error parsing $_, $x->{chg}\n";
848                         }
849                         if (!exists $x->{file_a} && $x->{chg} =~ /^(?:C|R)$/) {
850                                 croak "Error parsing $_, $x->{chg}\n";
851                         }
852                         $x->{file_b} = $_;
853                         $state = 'meta';
854                 } else {
855                         croak "Error parsing $_\n";
856                 }
857         }
858         command_close_pipe($diff_fh, $ctx);
859         return \@mods;
862 sub get_commit_entry {
863         my ($treeish) = shift;
864         my %log_entry = ( log => '', tree => get_tree_from_treeish($treeish) );
865         my $commit_editmsg = "$ENV{GIT_DIR}/COMMIT_EDITMSG";
866         my $commit_msg = "$ENV{GIT_DIR}/COMMIT_MSG";
867         open my $log_fh, '>', $commit_editmsg or croak $!;
869         my $type = command_oneline(qw/cat-file -t/, $treeish);
870         if ($type eq 'commit' || $type eq 'tag') {
871                 my ($msg_fh, $ctx) = command_output_pipe('cat-file',
872                                                          $type, $treeish);
873                 my $in_msg = 0;
874                 while (<$msg_fh>) {
875                         if (!$in_msg) {
876                                 $in_msg = 1 if (/^\s*$/);
877                         } elsif (/^git-svn-id: /) {
878                                 # skip this for now, we regenerate the
879                                 # correct one on re-fetch anyways
880                                 # TODO: set *:merge properties or like...
881                         } else {
882                                 print $log_fh $_ or croak $!;
883                         }
884                 }
885                 command_close_pipe($msg_fh, $ctx);
886         }
887         close $log_fh or croak $!;
889         if ($_edit || ($type eq 'tree')) {
890                 my $editor = $ENV{VISUAL} || $ENV{EDITOR} || 'vi';
891                 # TODO: strip out spaces, comments, like git-commit.sh
892                 system($editor, $commit_editmsg);
893         }
894         rename $commit_editmsg, $commit_msg or croak $!;
895         open $log_fh, '<', $commit_msg or croak $!;
896         { local $/; chomp($log_entry{log} = <$log_fh>); }
897         close $log_fh or croak $!;
898         unlink $commit_msg;
899         \%log_entry;
902 sub rev_list_raw {
903         my ($fh, $c) = command_output_pipe(qw/rev-list --pretty=raw/, @_);
904         return { fh => $fh, ctx => $c, t => { } };
907 sub next_rev_list_entry {
908         my $rl = shift;
909         my $fh = $rl->{fh};
910         my $x = $rl->{t};
911         while (<$fh>) {
912                 if (/^commit ($sha1)$/o) {
913                         if ($x->{c}) {
914                                 $rl->{t} = { c => $1 };
915                                 return $x;
916                         } else {
917                                 $x->{c} = $1;
918                         }
919                 } elsif (/^parent ($sha1)$/o) {
920                         $x->{p}->{$1} = 1;
921                 } elsif (s/^    //) {
922                         $x->{m} ||= '';
923                         $x->{m} .= $_;
924                 }
925         }
926         command_close_pipe($fh, $rl->{ctx});
927         return ($x != $rl->{t}) ? $x : undef;
930 sub s_to_file {
931         my ($str, $file, $mode) = @_;
932         open my $fd,'>',$file or croak $!;
933         print $fd $str,"\n" or croak $!;
934         close $fd or croak $!;
935         chmod ($mode &~ umask, $file) if (defined $mode);
938 sub file_to_s {
939         my $file = shift;
940         open my $fd,'<',$file or croak "$!: file: $file\n";
941         local $/;
942         my $ret = <$fd>;
943         close $fd or croak $!;
944         $ret =~ s/\s*$//s;
945         return $ret;
948 sub check_upgrade_needed {
949         if (!-r $REVDB) {
950                 -d $GIT_SVN_DIR or mkpath([$GIT_SVN_DIR]);
951                 open my $fh, '>>',$REVDB or croak $!;
952                 close $fh;
953         }
954         return unless eval {
955                 command([qw/rev-parse --verify/,"$GIT_SVN-HEAD^0"],
956                         {STDERR => 0});
957         };
958         my $head = eval { command('rev-parse',"refs/remotes/$GIT_SVN") };
959         if ($@ || !$head) {
960                 print STDERR "Please run: $0 rebuild --upgrade\n";
961                 exit 1;
962         }
965 # fills %tree_map with a reverse mapping of trees to commits.  Useful
966 # for finding parents to commit on.
967 sub map_tree_joins {
968         my %seen;
969         foreach my $br (@_branch_from) {
970                 my $pipe = command_output_pipe(qw/rev-list
971                                             --topo-order --pretty=raw/, $br);
972                 while (<$pipe>) {
973                         if (/^commit ($sha1)$/o) {
974                                 my $commit = $1;
976                                 # if we've seen a commit,
977                                 # we've seen its parents
978                                 last if $seen{$commit};
979                                 my ($tree) = (<$pipe> =~ /^tree ($sha1)$/o);
980                                 unless (defined $tree) {
981                                         die "Failed to parse commit $commit\n";
982                                 }
983                                 push @{$tree_map{$tree}}, $commit;
984                                 $seen{$commit} = 1;
985                         }
986                 }
987                 close $pipe;
988         }
991 sub load_all_refs {
992         if (@_branch_from) {
993                 print STDERR '--branch|-b parameters are ignored when ',
994                         "--branch-all-refs|-B is passed\n";
995         }
997         # don't worry about rev-list on non-commit objects/tags,
998         # it shouldn't blow up if a ref is a blob or tree...
999         @_branch_from = command(qw/rev-parse --symbolic --all/);
1002 # '<svn username> = real-name <email address>' mapping based on git-svnimport:
1003 sub load_authors {
1004         open my $authors, '<', $_authors or die "Can't open $_authors $!\n";
1005         my $log = $cmd eq 'log';
1006         while (<$authors>) {
1007                 chomp;
1008                 next unless /^(\S+?|\(no author\))\s*=\s*(.+?)\s*<(.+)>\s*$/;
1009                 my ($user, $name, $email) = ($1, $2, $3);
1010                 if ($log) {
1011                         $Git::SVN::Log::rusers{"$name <$email>"} = $user;
1012                 } else {
1013                         $users{$user} = [$name, $email];
1014                 }
1015         }
1016         close $authors or croak $!;
1019 sub git_svn_each {
1020         my $sub = shift;
1021         foreach (command(qw/rev-parse --symbolic --all/)) {
1022                 next unless s#^refs/remotes/##;
1023                 chomp $_;
1024                 next unless -f "$GIT_DIR/svn/$_/info/url";
1025                 &$sub($_);
1026         }
1029 sub migrate_revdb {
1030         git_svn_each(sub {
1031                 my $id = shift;
1032                 defined(my $pid = fork) or croak $!;
1033                 if (!$pid) {
1034                         $GIT_SVN = $ENV{GIT_SVN_ID} = $id;
1035                         init_vars();
1036                         exit 0 if -r $REVDB;
1037                         print "Upgrading svn => git mapping...\n";
1038                         -d $GIT_SVN_DIR or mkpath([$GIT_SVN_DIR]);
1039                         open my $fh, '>>',$REVDB or croak $!;
1040                         close $fh;
1041                         rebuild();
1042                         print "Done upgrading. You may now delete the ",
1043                                 "deprecated $GIT_SVN_DIR/revs directory\n";
1044                         exit 0;
1045                 }
1046                 waitpid $pid, 0;
1047                 croak $? if $?;
1048         });
1051 sub migration_check {
1052         migrate_revdb() unless (-e $REVDB);
1053         return if (-d "$GIT_DIR/svn" || !-d $GIT_DIR);
1054         print "Upgrading repository...\n";
1055         unless (-d "$GIT_DIR/svn") {
1056                 mkdir "$GIT_DIR/svn" or croak $!;
1057         }
1058         print "Data from a previous version of git-svn exists, but\n\t",
1059                                 "$GIT_SVN_DIR\n\t(required for this version ",
1060                                 "($VERSION) of git-svn) does not.\n";
1062         foreach my $x (command(qw/rev-parse --symbolic --all/)) {
1063                 next unless $x =~ s#^refs/remotes/##;
1064                 chomp $x;
1065                 next unless -f "$GIT_DIR/$x/info/url";
1066                 my $u = eval { file_to_s("$GIT_DIR/$x/info/url") };
1067                 next unless $u;
1068                 my $dn = dirname("$GIT_DIR/svn/$x");
1069                 mkpath([$dn]) unless -d $dn;
1070                 rename "$GIT_DIR/$x", "$GIT_DIR/svn/$x" or croak "$!: $x";
1071         }
1072         migrate_revdb() if (-d $GIT_SVN_DIR && !-w $REVDB);
1073         print "Done upgrading.\n";
1076 sub find_rev_before {
1077         my ($r, $id, $eq_ok) = @_;
1078         my $f = "$GIT_DIR/svn/$id/.rev_db";
1079         return (undef,undef) unless -r $f;
1080         --$r unless $eq_ok;
1081         while ($r > 0) {
1082                 if (my $c = revdb_get($f, $r)) {
1083                         return ($r, $c);
1084                 }
1085                 --$r;
1086         }
1087         return (undef, undef);
1090 sub init_vars {
1091         $GIT_SVN ||= $ENV{GIT_SVN_ID} || 'git-svn';
1092         $Git::SVN::default = $GIT_SVN;
1093         $GIT_SVN_DIR = "$GIT_DIR/svn/$GIT_SVN";
1094         $REVDB = "$GIT_SVN_DIR/.rev_db";
1095         $GIT_SVN_INDEX = "$GIT_SVN_DIR/index";
1096         $SVN_URL = undef;
1097         %tree_map = ();
1100 # convert GetOpt::Long specs for use by git-config
1101 sub read_repo_config {
1102         return unless -d $GIT_DIR;
1103         my $opts = shift;
1104         foreach my $o (keys %$opts) {
1105                 my $v = $opts->{$o};
1106                 my ($key) = ($o =~ /^([a-z\-]+)/);
1107                 $key =~ s/-//g;
1108                 my $arg = 'git-config';
1109                 $arg .= ' --int' if ($o =~ /[:=]i$/);
1110                 $arg .= ' --bool' if ($o !~ /[:=][sfi]$/);
1111                 if (ref $v eq 'ARRAY') {
1112                         chomp(my @tmp = `$arg --get-all svn.$key`);
1113                         @$v = @tmp if @tmp;
1114                 } else {
1115                         chomp(my $tmp = `$arg --get svn.$key`);
1116                         if ($tmp && !($arg =~ / --bool/ && $tmp eq 'false')) {
1117                                 $$v = $tmp;
1118                         }
1119                 }
1120         }
1123 sub set_default_vals {
1124         if (defined $_repack) {
1125                 $_repack = 1000 if ($_repack <= 0);
1126                 $_repack_nr = $_repack;
1127                 $_repack_flags ||= '-d';
1128         }
1131 sub read_grafts {
1132         my $gr_file = shift;
1133         my ($grafts, $comments) = ({}, {});
1134         if (open my $fh, '<', $gr_file) {
1135                 my @tmp;
1136                 while (<$fh>) {
1137                         if (/^($sha1)\s+/) {
1138                                 my $c = $1;
1139                                 if (@tmp) {
1140                                         @{$comments->{$c}} = @tmp;
1141                                         @tmp = ();
1142                                 }
1143                                 foreach my $p (split /\s+/, $_) {
1144                                         $grafts->{$c}->{$p} = 1;
1145                                 }
1146                         } else {
1147                                 push @tmp, $_;
1148                         }
1149                 }
1150                 close $fh or croak $!;
1151                 @{$comments->{'END'}} = @tmp if @tmp;
1152         }
1153         return ($grafts, $comments);
1156 sub write_grafts {
1157         my ($grafts, $comments, $gr_file) = @_;
1159         open my $fh, '>', $gr_file or croak $!;
1160         foreach my $c (sort keys %$grafts) {
1161                 if ($comments->{$c}) {
1162                         print $fh $_ foreach @{$comments->{$c}};
1163                 }
1164                 my $p = $grafts->{$c};
1165                 my %x; # real parents
1166                 delete $p->{$c}; # commits are not self-reproducing...
1167                 my $ch = command_output_pipe(qw/cat-file commit/, $c);
1168                 while (<$ch>) {
1169                         if (/^parent ($sha1)/) {
1170                                 $x{$1} = $p->{$1} = 1;
1171                         } else {
1172                                 last unless /^\S/;
1173                         }
1174                 }
1175                 close $ch; # breaking the pipe
1177                 # if real parents are the only ones in the grafts, drop it
1178                 next if join(' ',sort keys %$p) eq join(' ',sort keys %x);
1180                 my (@ip, @jp, $mb);
1181                 my %del = %x;
1182                 @ip = @jp = keys %$p;
1183                 foreach my $i (@ip) {
1184                         next if $del{$i} || $p->{$i} == 2;
1185                         foreach my $j (@jp) {
1186                                 next if $i eq $j || $del{$j} || $p->{$j} == 2;
1187                                 $mb = eval { command('merge-base', $i, $j) };
1188                                 next unless $mb;
1189                                 chomp $mb;
1190                                 next if $x{$mb};
1191                                 if ($mb eq $j) {
1192                                         delete $p->{$i};
1193                                         $del{$i} = 1;
1194                                 } elsif ($mb eq $i) {
1195                                         delete $p->{$j};
1196                                         $del{$j} = 1;
1197                                 }
1198                         }
1199                 }
1201                 # if real parents are the only ones in the grafts, drop it
1202                 next if join(' ',sort keys %$p) eq join(' ',sort keys %x);
1204                 print $fh $c, ' ', join(' ', sort keys %$p),"\n";
1205         }
1206         if ($comments->{'END'}) {
1207                 print $fh $_ foreach @{$comments->{'END'}};
1208         }
1209         close $fh or croak $!;
1212 sub read_url_paths_all {
1213         my ($l_map, $pfx, $p) = @_;
1214         my @dir;
1215         foreach (<$p/*>) {
1216                 if (-r "$_/info/url") {
1217                         $pfx .= '/' if $pfx && $pfx !~ m!/$!;
1218                         my $id = $pfx . basename $_;
1219                         my $url = file_to_s("$_/info/url");
1220                         my ($u, $p) = repo_path_split($url);
1221                         $l_map->{$u}->{$p} = $id;
1222                 } elsif (-d $_) {
1223                         push @dir, $_;
1224                 }
1225         }
1226         foreach (@dir) {
1227                 my $x = $_;
1228                 $x =~ s!^\Q$GIT_DIR\E/svn/!!o;
1229                 read_url_paths_all($l_map, $x, $_);
1230         }
1233 # this one only gets ids that have been imported, not new ones
1234 sub read_url_paths {
1235         my $l_map = {};
1236         git_svn_each(sub { my $x = shift;
1237                         my $url = file_to_s("$GIT_DIR/svn/$x/info/url");
1238                         my ($u, $p) = repo_path_split($url);
1239                         $l_map->{$u}->{$p} = $x;
1240                         });
1241         return $l_map;
1244 sub extract_metadata {
1245         my $id = shift or return (undef, undef, undef);
1246         my ($url, $rev, $uuid) = ($id =~ /^git-svn-id:\s(\S+?)\@(\d+)
1247                                                         \s([a-f\d\-]+)$/x);
1248         if (!defined $rev || !$uuid || !$url) {
1249                 # some of the original repositories I made had
1250                 # identifiers like this:
1251                 ($rev, $uuid) = ($id =~/^git-svn-id:\s(\d+)\@([a-f\d\-]+)/);
1252         }
1253         return ($url, $rev, $uuid);
1256 sub cmt_metadata {
1257         return extract_metadata((grep(/^git-svn-id: /,
1258                 command(qw/cat-file commit/, shift)))[-1]);
1261 sub get_commit_time {
1262         my $cmt = shift;
1263         my $fh = command_output_pipe(qw/rev-list --pretty=raw -n1/, $cmt);
1264         while (<$fh>) {
1265                 /^committer\s(?:.+) (\d+) ([\-\+]?\d+)$/ or next;
1266                 my ($s, $tz) = ($1, $2);
1267                 if ($tz =~ s/^\+//) {
1268                         $s += tz_to_s_offset($tz);
1269                 } elsif ($tz =~ s/^\-//) {
1270                         $s -= tz_to_s_offset($tz);
1271                 }
1272                 close $fh;
1273                 return $s;
1274         }
1275         die "Can't get commit time for commit: $cmt\n";
1278 sub tz_to_s_offset {
1279         my ($tz) = @_;
1280         $tz =~ s/(\d\d)$//;
1281         return ($1 * 60) + ($tz * 3600);
1284 package Git::SVN;
1285 use strict;
1286 use warnings;
1287 use vars qw/$default/;
1288 use Carp qw/croak/;
1289 use File::Path qw/mkpath/;
1290 use IPC::Open3;
1292 # properties that we do not log:
1293 my %SKIP_PROP;
1294 BEGIN {
1295         %SKIP_PROP = map { $_ => 1 } qw/svn:wc:ra_dav:version-url
1296                                         svn:special svn:executable
1297                                         svn:entry:committed-rev
1298                                         svn:entry:last-author
1299                                         svn:entry:uuid
1300                                         svn:entry:committed-date/;
1303 sub init {
1304         my ($class, $id, $url) = @_;
1305         my $self = _new($class, $id);
1306         mkpath(["$self->{dir}/info"]);
1307         if (defined $url) {
1308                 $url =~ s!/+$!!; # strip trailing slash
1309                 ::s_to_file($url, "$self->{dir}/info/url");
1310         }
1311         $self->{url} = $url;
1312         open my $fh, '>>', $self->{db_path} or croak $!;
1313         close $fh or croak $!;
1314         $self;
1317 sub new {
1318         my ($class, $id) = @_;
1319         my $self = _new($class, $id);
1320         $self->{url} = ::file_to_s("$self->{dir}/info/url");
1321         $self;
1324 sub refname { "refs/remotes/$_[0]->{id}" }
1326 sub ra {
1327         my ($self) = shift;
1328         $self->{ra} ||= Git::SVN::Ra->new($self->{url});
1331 sub copy_remote_ref {
1332         my ($self) = @_;
1333         my $origin = $::_cp_remote ? $::_cp_remote : 'origin';
1334         my $ref = $self->refname;
1335         if (command('ls-remote', $origin, $ref)) {
1336                 command_noisy('fetch', $origin, "$ref:$ref");
1337         } elsif ($::_cp_remote && !$::_upgrade) {
1338                 die "Unable to find remote reference: $ref on $origin\n";
1339         }
1342 sub traverse_ignore {
1343         my ($self, $fh, $path, $r) = @_;
1344         $path =~ s#^/+##g;
1345         my ($dirent, undef, $props) = $self->ra->get_dir($path, $r);
1346         my $p = $path;
1347         $p =~ s#^\Q$self->{ra}->{svn_path}\E/##;
1348         print $fh length $p ? "\n# $p\n" : "\n# /\n";
1349         if (my $s = $props->{'svn:ignore'}) {
1350                 $s =~ s/[\r\n]+/\n/g;
1351                 chomp $s;
1352                 if (length $p == 0) {
1353                         $s =~ s#\n#\n/$p#g;
1354                         print $fh "/$s\n";
1355                 } else {
1356                         $s =~ s#\n#\n/$p/#g;
1357                         print $fh "/$p/$s\n";
1358                 }
1359         }
1360         foreach (sort keys %$dirent) {
1361                 next if $dirent->{$_}->kind != $SVN::Node::dir;
1362                 $self->traverse_ignore($fh, "$path/$_", $r);
1363         }
1366 # returns the newest SVN revision number and newest commit SHA1
1367 sub last_rev_commit {
1368         my ($self) = @_;
1369         if (defined $self->{last_rev} && defined $self->{last_commit}) {
1370                 return ($self->{last_rev}, $self->{last_commit});
1371         }
1372         my $c = ::verify_ref($self->refname.'^0');
1373         if (defined $c && length $c) {
1374                 my $rev = (::cmt_metadata($c))[1];
1375                 if (defined $rev) {
1376                         ($self->{last_rev}, $self->{last_commit}) = ($rev, $c);
1377                         return ($rev, $c);
1378                 }
1379         }
1380         my $offset = -41; # from tail
1381         my $rl;
1382         open my $fh, '<', $self->{db_path} or
1383                                  croak "$self->{db_path} not readable: $!\n";
1384         seek $fh, $offset, 2;
1385         $rl = readline $fh;
1386         defined $rl or return (undef, undef);
1387         chomp $rl;
1388         while ($c ne $rl && tell $fh != 0) {
1389                 $offset -= 41;
1390                 seek $fh, $offset, 2;
1391                 $rl = readline $fh;
1392                 defined $rl or return (undef, undef);
1393                 chomp $rl;
1394         }
1395         my $rev = tell $fh;
1396         croak $! if ($rev < 0);
1397         $rev =  ($rev - 41) / 41;
1398         close $fh or croak $!;
1399         ($self->{last_rev}, $self->{last_commit}) = ($rev, $c);
1400         return ($rev, $c);
1403 sub parse_revision {
1404         my ($self, $base) = @_;
1405         my $head = $self->ra->get_latest_revnum;
1406         if (!defined $::_revision || $::_revision eq 'BASE:HEAD') {
1407                 return ($base + 1, $head) if (defined $base);
1408                 return (0, $head);
1409         }
1410         return ($1, $2) if ($::_revision =~ /^(\d+):(\d+)$/);
1411         return ($::_revision, $::_revision) if ($::_revision =~ /^\d+$/);
1412         if ($::_revision =~ /^BASE:(\d+)$/) {
1413                 return ($base + 1, $1) if (defined $base);
1414                 return (0, $head);
1415         }
1416         return ($1, $head) if ($::_revision =~ /^(\d+):HEAD$/);
1417         die "revision argument: $::_revision not understood by git-svn\n",
1418                 "Try using the command-line svn client instead\n";
1421 sub tmp_index_do {
1422         my ($self, $sub) = @_;
1423         my $old_index = $ENV{GIT_INDEX_FILE};
1424         $ENV{GIT_INDEX_FILE} = $self->{index};
1425         my @ret = &$sub;
1426         if ($old_index) {
1427                 $ENV{GIT_INDEX_FILE} = $old_index;
1428         } else {
1429                 delete $ENV{GIT_INDEX_FILE};
1430         }
1431         wantarray ? @ret : $ret[0];
1434 sub assert_index_clean {
1435         my ($self, $treeish) = @_;
1437         $self->tmp_index_do(sub {
1438                 command_noisy('read-tree', $treeish) unless -e $self->{index};
1439                 my $x = command_oneline('write-tree');
1440                 my ($y) = (command(qw/cat-file commit/, $treeish) =~
1441                            /^tree ($::sha1)/mo);
1442                 if ($y ne $x) {
1443                         unlink $self->{index} or croak $!;
1444                         command_noisy('read-tree', $treeish);
1445                 }
1446                 $x = command_oneline('write-tree');
1447                 if ($y ne $x) {
1448                         ::fatal "trees ($treeish) $y != $x\n",
1449                                 "Something is seriously wrong...\n";
1450                 }
1451         });
1454 sub get_commit_parents {
1455         my ($self, $log_entry, @parents) = @_;
1456         my (%seen, @ret, @tmp);
1457         # commit parents can be conditionally bound to a particular
1458         # svn revision via: "svn_revno=commit_sha1", filter them out here:
1459         foreach my $p (@parents) {
1460                 next unless defined $p;
1461                 if ($p =~ /^(\d+)=($::sha1_short)$/o) {
1462                         push @tmp, $2 if $1 == $log_entry->{revision};
1463                 } else {
1464                         push @tmp, $p if $p =~ /^$::sha1_short$/o;
1465                 }
1466         }
1467         if (my $cur = ::verify_ref($self->refname.'^0')) {
1468                 push @tmp, $cur;
1469         }
1470         push @tmp, $_ foreach (@{$log_entry->{parents}}, @tmp);
1471         while (my $p = shift @tmp) {
1472                 next if $seen{$p};
1473                 $seen{$p} = 1;
1474                 push @ret, $p;
1475                 # MAXPARENT is defined to 16 in commit-tree.c:
1476                 last if @ret >= 16;
1477         }
1478         if (@tmp) {
1479                 die "r$log_entry->{revision}: No room for parents:\n\t",
1480                     join("\n\t", @tmp), "\n";
1481         }
1482         @ret;
1485 sub check_upgrade_needed {
1486         my ($self) = @_;
1487         if (!-r $self->{db_path}) {
1488                 -d $self->{dir} or mkpath([$self->{dir}]);
1489                 open my $fh, '>>', $self->{db_path} or croak $!;
1490                 close $fh;
1491         }
1492         return unless ::verify_ref($self->{id}.'-HEAD^0');
1493         my $head = ::verify_ref($self->refname.'^0');
1494         if ($@ || !$head) {
1495                 ::fatal("Please run: $0 rebuild --upgrade\n");
1496         }
1499 sub do_git_commit {
1500         my ($self, $log_entry, @parents) = @_;
1501         if (my $c = $self->rev_db_get($log_entry->{revision})) {
1502                 croak "$log_entry->{revision} = $c already exists! ",
1503                       "Why are we refetching it?\n";
1504         }
1505         my $author = $log_entry->{author};
1506         my ($name, $email) = (defined $::users{$author} ? @{$::users{$author}}
1507                            : ($author, "$author\@".$self->ra->uuid));
1508         $ENV{GIT_AUTHOR_NAME} = $ENV{GIT_COMMITTER_NAME} = $name;
1509         $ENV{GIT_AUTHOR_EMAIL} = $ENV{GIT_COMMITTER_EMAIL} = $email;
1510         $ENV{GIT_AUTHOR_DATE} = $ENV{GIT_COMMITTER_DATE} = $log_entry->{date};
1512         my $tree = $log_entry->{tree};
1513         if (!defined $tree) {
1514                 $tree = $self->tmp_index_do(sub {
1515                                             command_oneline('write-tree') });
1516         }
1517         die "Tree is not a valid sha1: $tree\n" if $tree !~ /^$::sha1$/o;
1519         my @exec = ('git-commit-tree', $tree);
1520         foreach ($self->get_commit_parents($log_entry, @parents)) {
1521                 push @exec, '-p', $_;
1522         }
1523         defined(my $pid = open3(my $msg_fh, my $out_fh, '>&STDERR', @exec))
1524                                                                    or croak $!;
1525         print $msg_fh $log_entry->{log} or croak $!;
1526         print $msg_fh "\ngit-svn-id: ", $self->ra->{url}, '@',
1527                       $log_entry->{revision}, ' ',
1528                       $self->ra->uuid, "\n" or croak $!;
1529         $msg_fh->flush == 0 or croak $!;
1530         close $msg_fh or croak $!;
1531         chomp(my $commit = do { local $/; <$out_fh> });
1532         close $out_fh or croak $!;
1533         waitpid $pid, 0;
1534         croak $? if $?;
1535         if ($commit !~ /^$::sha1$/o) {
1536                 die "Failed to commit, invalid sha1: $commit\n";
1537         }
1539         command_noisy('update-ref',$self->refname, $commit);
1540         $self->rev_db_set($log_entry->{revision}, $commit);
1542         $self->{last_rev} = $log_entry->{revision};
1543         $self->{last_commit} = $commit;
1544         print "r$log_entry->{revision} = $commit\n";
1545         return $commit;
1548 sub do_fetch {
1549         my ($self, $paths, $rev) = @_; #, $author, $date, $log) = @_;
1550         my $ed = SVN::Git::Fetcher->new($self);
1551         my ($last_rev, @parents);
1552         if ($self->{last_commit}) {
1553                 $last_rev = $self->{last_rev};
1554                 $ed->{c} = $self->{last_commit};
1555                 @parents = ($self->{last_commit});
1556         } else {
1557                 $last_rev = $rev;
1558         }
1559         unless ($self->ra->gs_do_update($last_rev, $rev, '', 1, $ed)) {
1560                 die "SVN connection failed somewhere...\n";
1561         }
1562         $self->make_log_entry($rev, \@parents, $ed);
1565 sub write_untracked {
1566         my ($self, $rev, $fh, $untracked) = @_;
1567         my $h;
1568         print $fh "r$rev\n" or croak $!;
1569         $h = $untracked->{empty};
1570         foreach (sort keys %$h) {
1571                 my $act = $h->{$_} ? '+empty_dir' : '-empty_dir';
1572                 print $fh "  $act: ", uri_encode($_), "\n" or croak $!;
1573                 warn "W: $act: $_\n";
1574         }
1575         foreach my $t (qw/dir_prop file_prop/) {
1576                 $h = $untracked->{$t} or next;
1577                 foreach my $path (sort keys %$h) {
1578                         my $ppath = $path eq '' ? '.' : $path;
1579                         foreach my $prop (sort keys %{$h->{$path}}) {
1580                                 next if $SKIP_PROP{$prop};
1581                                 my $v = $h->{$path}->{$prop};
1582                                 if (defined $v) {
1583                                         print $fh "  +$t: ",
1584                                                   uri_encode($ppath), ' ',
1585                                                   uri_encode($prop), ' ',
1586                                                   uri_encode($v), "\n"
1587                                                   or croak $!;
1588                                 } else {
1589                                         print $fh "  -$t: ",
1590                                                   uri_encode($ppath), ' ',
1591                                                   uri_encode($prop), "\n"
1592                                                   or croak $!;
1593                                 }
1594                         }
1595                 }
1596         }
1597         foreach my $t (qw/absent_file absent_directory/) {
1598                 $h = $untracked->{$t} or next;
1599                 foreach my $parent (sort keys %$h) {
1600                         foreach my $path (sort @{$h->{$parent}}) {
1601                                 print $fh "  $t: ",
1602                                       uri_encode("$parent/$path"), "\n"
1603                                       or croak $!;
1604                                 warn "W: $t: $parent/$path ",
1605                                      "Insufficient permissions?\n";
1606                         }
1607                 }
1608         }
1611 sub parse_svn_date {
1612         my $date = shift || return '+0000 1970-01-01 00:00:00';
1613         my ($Y,$m,$d,$H,$M,$S) = ($date =~ /^(\d{4})\-(\d\d)\-(\d\d)T
1614                                             (\d\d)\:(\d\d)\:(\d\d).\d+Z$/x) or
1615                                          croak "Unable to parse date: $date\n";
1616         "+0000 $Y-$m-$d $H:$M:$S";
1619 sub check_author {
1620         my ($author) = @_;
1621         if (!defined $author || length $author == 0) {
1622                 $author = '(no author)';
1623         }
1624         if (defined $::_authors && ! defined $::users{$author}) {
1625                 die "Author: $author not defined in $::_authors file\n";
1626         }
1627         $author;
1630 sub make_log_entry {
1631         my ($self, $rev, $parents, $untracked) = @_;
1632         my $rp = $self->ra->rev_proplist($rev);
1633         my %log_entry = ( parents => $parents || [], revision => $rev,
1634                           revprops => $rp, log => '');
1635         open my $un, '>>', "$self->{dir}/unhandled.log" or croak $!;
1636         $self->write_untracked($rev, $un, $untracked);
1637         foreach (sort keys %$rp) {
1638                 my $v = $rp->{$_};
1639                 if (/^svn:(author|date|log)$/) {
1640                         $log_entry{$1} = $v;
1641                 } else {
1642                         print $un "  rev_prop: ", uri_encode($_), ' ',
1643                                   uri_encode($v), "\n";
1644                 }
1645         }
1646         close $un or croak $!;
1647         $log_entry{date} = parse_svn_date($log_entry{date});
1648         $log_entry{author} = check_author($log_entry{author});
1649         $log_entry{log} .= "\n";
1650         \%log_entry;
1653 sub fetch {
1654         my ($self, @parents) = @_;
1655         my ($last_rev, $last_commit) = $self->last_rev_commit;
1656         my ($base, $head) = $self->parse_revision($last_rev);
1657         return if ($base > $head);
1658         if (defined $last_commit) {
1659                 $self->assert_index_clean($last_commit);
1660         }
1661         my $inc = 1000;
1662         my ($min, $max) = ($base, $head < $base + $inc ? $head : $base + $inc);
1663         my $err_handler = $SVN::Error::handler;
1664         $SVN::Error::handler = \&skip_unknown_revs;
1665         while (1) {
1666                 my @revs;
1667                 $self->ra->get_log([''], $min, $max, 0, 1, 1, sub {
1668                         my ($paths, $rev, $author, $date, $log) = @_;
1669                         push @revs, $rev });
1670                 foreach (@revs) {
1671                         my $log_entry = $self->do_fetch(undef, $_);
1672                         $self->do_git_commit($log_entry, @parents);
1673                 }
1674                 last if $max >= $head;
1675                 $min = $max + 1;
1676                 $max += $inc;
1677                 $max = $head if ($max > $head);
1678         }
1679         $SVN::Error::handler = $err_handler;
1682 sub set_tree_cb {
1683         my ($self, $log_entry, $tree, $rev, $date, $author) = @_;
1684         # TODO: enable and test optimized commits:
1685         if (0 && $rev == ($self->{last_rev} + 1)) {
1686                 $log_entry->{revision} = $rev;
1687                 $log_entry->{author} = $author;
1688                 $self->do_git_commit($log_entry, "$rev=$tree");
1689         } else {
1690                 $self->fetch("$rev=$tree");
1691         }
1694 sub set_tree {
1695         my ($self, $tree) = (shift, shift);
1696         my $log_entry = ::get_commit_entry($tree);
1697         unless ($self->{last_rev}) {
1698                 fatal("Must have an existing revision to commit\n");
1699         }
1700         my $pool = SVN::Pool->new;
1701         my $ed = SVN::Git::Editor->new({ r => $self->{last_rev},
1702                                          ra => $self->ra->dup,
1703                                          svn_path => $self->ra->{svn_path}
1704                                        },
1705                                        $self->ra->get_commit_editor(
1706                                          $log_entry->{log}, sub {
1707                                            $self->set_tree_cb($log_entry,
1708                                                               $tree, @_);
1709                                        }),
1710                                        $pool);
1711         my $mods = $ed->apply_diff($self->{last_commit}, $tree);
1712         if (@$mods == 0) {
1713                 print "No changes\nr$self->{last_rev} = $tree\n";
1714         }
1715         $pool->clear;
1718 sub skip_unknown_revs {
1719         my ($err) = @_;
1720         my $errno = $err->apr_err();
1721         # Maybe the branch we're tracking didn't
1722         # exist when the repo started, so it's
1723         # not an error if it doesn't, just continue
1724         #
1725         # Wonderfully consistent library, eh?
1726         # 160013 - svn:// and file://
1727         # 175002 - http(s)://
1728         # 175007 - http(s):// (this repo required authorization, too...)
1729         #   More codes may be discovered later...
1730         if ($errno == 175007 || $errno == 175002 || $errno == 160013) {
1731                 return;
1732         }
1733         croak "Error from SVN, ($errno): ", $err->expanded_message,"\n";
1736 # rev_db:
1737 # Tie::File seems to be prone to offset errors if revisions get sparse,
1738 # it's not that fast, either.  Tie::File is also not in Perl 5.6.  So
1739 # one of my favorite modules is out :<  Next up would be one of the DBM
1740 # modules, but I'm not sure which is most portable...  So I'll just
1741 # go with something that's plain-text, but still capable of
1742 # being randomly accessed.  So here's my ultra-simple fixed-width
1743 # database.  All records are 40 characters + "\n", so it's easy to seek
1744 # to a revision: (41 * rev) is the byte offset.
1745 # A record of 40 0s denotes an empty revision.
1746 # And yes, it's still pretty fast (faster than Tie::File).
1748 sub rev_db_set {
1749         my ($self, $rev, $commit) = @_;
1750         length $commit == 40 or croak "arg3 must be a full SHA1 hexsum\n";
1751         open my $fh, '+<', $self->{db_path} or croak $!;
1752         my $offset = $rev * 41;
1753         # assume that append is the common case:
1754         seek $fh, 0, 2 or croak $!;
1755         my $pos = tell $fh;
1756         if ($pos < $offset) {
1757                 print $fh (('0' x 40),"\n") x (($offset - $pos) / 41)
1758                   or croak $!;
1759         }
1760         seek $fh, $offset, 0 or croak $!;
1761         print $fh $commit,"\n" or croak $!;
1762         close $fh or croak $!;
1765 sub rev_db_get {
1766         my ($self, $rev) = @_;
1767         my $ret;
1768         my $offset = $rev * 41;
1769         open my $fh, '<', $self->{db_path} or croak $!;
1770         if (seek $fh, $offset, 0) {
1771                 $ret = readline $fh;
1772                 if (defined $ret) {
1773                         chomp $ret;
1774                         $ret = undef if ($ret =~ /^0{40}$/);
1775                 }
1776         }
1777         close $fh or croak $!;
1778         $ret;
1781 sub _new {
1782         my ($class, $id) = @_;
1783         $id ||= $Git::SVN::default;
1784         my $dir = "$ENV{GIT_DIR}/svn/$id";
1785         bless { id => $id, dir => $dir, index => "$dir/index",
1786                 db_path => "$dir/.rev_db" }, $class;
1789 sub uri_encode {
1790         my ($f) = @_;
1791         $f =~ s#([^a-zA-Z0-9\*!\:_\./\-])#uc sprintf("%%%02x",ord($1))#eg;
1792         $f
1795 package Git::SVN::Prompt;
1796 use strict;
1797 use warnings;
1798 require SVN::Core;
1799 use vars qw/$_no_auth_cache $_username/;
1801 sub simple {
1802         my ($cred, $realm, $default_username, $may_save, $pool) = @_;
1803         $may_save = undef if $_no_auth_cache;
1804         $default_username = $_username if defined $_username;
1805         if (defined $default_username && length $default_username) {
1806                 if (defined $realm && length $realm) {
1807                         print STDERR "Authentication realm: $realm\n";
1808                         STDERR->flush;
1809                 }
1810                 $cred->username($default_username);
1811         } else {
1812                 username($cred, $realm, $may_save, $pool);
1813         }
1814         $cred->password(_read_password("Password for '" .
1815                                        $cred->username . "': ", $realm));
1816         $cred->may_save($may_save);
1817         $SVN::_Core::SVN_NO_ERROR;
1820 sub ssl_server_trust {
1821         my ($cred, $realm, $failures, $cert_info, $may_save, $pool) = @_;
1822         $may_save = undef if $_no_auth_cache;
1823         print STDERR "Error validating server certificate for '$realm':\n";
1824         if ($failures & $SVN::Auth::SSL::UNKNOWNCA) {
1825                 print STDERR " - The certificate is not issued by a trusted ",
1826                       "authority. Use the\n",
1827                       "   fingerprint to validate the certificate manually!\n";
1828         }
1829         if ($failures & $SVN::Auth::SSL::CNMISMATCH) {
1830                 print STDERR " - The certificate hostname does not match.\n";
1831         }
1832         if ($failures & $SVN::Auth::SSL::NOTYETVALID) {
1833                 print STDERR " - The certificate is not yet valid.\n";
1834         }
1835         if ($failures & $SVN::Auth::SSL::EXPIRED) {
1836                 print STDERR " - The certificate has expired.\n";
1837         }
1838         if ($failures & $SVN::Auth::SSL::OTHER) {
1839                 print STDERR " - The certificate has an unknown error.\n";
1840         }
1841         printf STDERR
1842                 "Certificate information:\n".
1843                 " - Hostname: %s\n".
1844                 " - Valid: from %s until %s\n".
1845                 " - Issuer: %s\n".
1846                 " - Fingerprint: %s\n",
1847                 map $cert_info->$_, qw(hostname valid_from valid_until
1848                                        issuer_dname fingerprint);
1849         my $choice;
1850 prompt:
1851         print STDERR $may_save ?
1852               "(R)eject, accept (t)emporarily or accept (p)ermanently? " :
1853               "(R)eject or accept (t)emporarily? ";
1854         STDERR->flush;
1855         $choice = lc(substr(<STDIN> || 'R', 0, 1));
1856         if ($choice =~ /^t$/i) {
1857                 $cred->may_save(undef);
1858         } elsif ($choice =~ /^r$/i) {
1859                 return -1;
1860         } elsif ($may_save && $choice =~ /^p$/i) {
1861                 $cred->may_save($may_save);
1862         } else {
1863                 goto prompt;
1864         }
1865         $cred->accepted_failures($failures);
1866         $SVN::_Core::SVN_NO_ERROR;
1869 sub ssl_client_cert {
1870         my ($cred, $realm, $may_save, $pool) = @_;
1871         $may_save = undef if $_no_auth_cache;
1872         print STDERR "Client certificate filename: ";
1873         STDERR->flush;
1874         chomp(my $filename = <STDIN>);
1875         $cred->cert_file($filename);
1876         $cred->may_save($may_save);
1877         $SVN::_Core::SVN_NO_ERROR;
1880 sub ssl_client_cert_pw {
1881         my ($cred, $realm, $may_save, $pool) = @_;
1882         $may_save = undef if $_no_auth_cache;
1883         $cred->password(_read_password("Password: ", $realm));
1884         $cred->may_save($may_save);
1885         $SVN::_Core::SVN_NO_ERROR;
1888 sub username {
1889         my ($cred, $realm, $may_save, $pool) = @_;
1890         $may_save = undef if $_no_auth_cache;
1891         if (defined $realm && length $realm) {
1892                 print STDERR "Authentication realm: $realm\n";
1893         }
1894         my $username;
1895         if (defined $_username) {
1896                 $username = $_username;
1897         } else {
1898                 print STDERR "Username: ";
1899                 STDERR->flush;
1900                 chomp($username = <STDIN>);
1901         }
1902         $cred->username($username);
1903         $cred->may_save($may_save);
1904         $SVN::_Core::SVN_NO_ERROR;
1907 sub _read_password {
1908         my ($prompt, $realm) = @_;
1909         print STDERR $prompt;
1910         STDERR->flush;
1911         require Term::ReadKey;
1912         Term::ReadKey::ReadMode('noecho');
1913         my $password = '';
1914         while (defined(my $key = Term::ReadKey::ReadKey(0))) {
1915                 last if $key =~ /[\012\015]/; # \n\r
1916                 $password .= $key;
1917         }
1918         Term::ReadKey::ReadMode('restore');
1919         print STDERR "\n";
1920         STDERR->flush;
1921         $password;
1924 package main;
1926 sub uri_encode {
1927         my ($f) = @_;
1928         $f =~ s#([^a-zA-Z0-9\*!\:_\./\-])#uc sprintf("%%%02x",ord($1))#eg;
1929         $f
1932 sub uri_decode {
1933         my ($f) = @_;
1934         $f =~ tr/+/ /;
1935         $f =~ s/%([A-F0-9]{2})/chr hex($1)/ge;
1936         $f
1939 sub libsvn_parse_revision {
1940         my $base = shift;
1941         my $head = $SVN->get_latest_revnum();
1942         if (!defined $_revision || $_revision eq 'BASE:HEAD') {
1943                 return ($base + 1, $head) if (defined $base);
1944                 return (0, $head);
1945         }
1946         return ($1, $2) if ($_revision =~ /^(\d+):(\d+)$/);
1947         return ($_revision, $_revision) if ($_revision =~ /^\d+$/);
1948         if ($_revision =~ /^BASE:(\d+)$/) {
1949                 return ($base + 1, $1) if (defined $base);
1950                 return (0, $head);
1951         }
1952         return ($1, $head) if ($_revision =~ /^(\d+):HEAD$/);
1953         die "revision argument: $_revision not understood by git-svn\n",
1954                 "Try using the command-line svn client instead\n";
1957 sub libsvn_traverse_ignore {
1958         my ($fh, $path, $r) = @_;
1959         $path =~ s#^/+##g;
1960         my ($dirent, undef, $props) = $SVN->get_dir($path, $r);
1961         my $p = $path;
1962         $p =~ s#^\Q$SVN->{svn_path}\E/##;
1963         print $fh length $p ? "\n# $p\n" : "\n# /\n";
1964         if (my $s = $props->{'svn:ignore'}) {
1965                 $s =~ s/[\r\n]+/\n/g;
1966                 chomp $s;
1967                 if (length $p == 0) {
1968                         $s =~ s#\n#\n/$p#g;
1969                         print $fh "/$s\n";
1970                 } else {
1971                         $s =~ s#\n#\n/$p/#g;
1972                         print $fh "/$p/$s\n";
1973                 }
1974         }
1975         foreach (sort keys %$dirent) {
1976                 next if $dirent->{$_}->kind != $SVN::Node::dir;
1977                 libsvn_traverse_ignore($fh, "$path/$_", $r);
1978         }
1981 sub revisions_eq {
1982         my ($path, $r0, $r1) = @_;
1983         return 1 if $r0 == $r1;
1984         my $nr = 0;
1985         # should be OK to use Pool here (r1 - r0) should be small
1986         $SVN->get_log([$path], $r0, $r1, 0, 0, 1, sub {$nr++});
1987         return 0 if ($nr > 1);
1988         return 1;
1991 sub libsvn_find_parent_branch {
1992         my ($paths, $rev, $author, $date, $log) = @_;
1993         my $svn_path = '/'.$SVN->{svn_path};
1995         # look for a parent from another branch:
1996         my $i = $paths->{$svn_path} or return;
1997         my $branch_from = $i->copyfrom_path or return;
1998         my $r = $i->copyfrom_rev;
1999         print STDERR  "Found possible branch point: ",
2000                                 "$branch_from => $svn_path, $r\n";
2001         $branch_from =~ s#^/##;
2002         my $l_map = {};
2003         read_url_paths_all($l_map, '', "$GIT_DIR/svn");
2004         my $url = $SVN->{repos_root};
2005         defined $l_map->{$url} or return;
2006         my $id = $l_map->{$url}->{$branch_from};
2007         if (!defined $id && $_follow_parent) {
2008                 print STDERR "Following parent: $branch_from\@$r\n";
2009                 # auto create a new branch and follow it
2010                 $id = basename($branch_from);
2011                 $id .= '@'.$r if -r "$GIT_DIR/svn/$id";
2012                 while (-r "$GIT_DIR/svn/$id") {
2013                         # just grow a tail if we're not unique enough :x
2014                         $id .= '-';
2015                 }
2016         }
2017         return unless defined $id;
2019         my ($r0, $parent) = find_rev_before($r,$id,1);
2020         if ($_follow_parent && (!defined $r0 || !defined $parent)) {
2021                 defined(my $pid = fork) or croak $!;
2022                 if (!$pid) {
2023                         $GIT_SVN = $ENV{GIT_SVN_ID} = $id;
2024                         init_vars();
2025                         $SVN_URL = "$url/$branch_from";
2026                         $SVN = undef;
2027                         setup_git_svn();
2028                         # we can't assume SVN_URL exists at r+1:
2029                         $_revision = "0:$r";
2030                         fetch_lib();
2031                         exit 0;
2032                 }
2033                 waitpid $pid, 0;
2034                 croak $? if $?;
2035                 ($r0, $parent) = find_rev_before($r,$id,1);
2036         }
2037         return unless (defined $r0 && defined $parent);
2038         if (revisions_eq($branch_from, $r0, $r)) {
2039                 unlink $GIT_SVN_INDEX;
2040                 print STDERR "Found branch parent: ($GIT_SVN) $parent\n";
2041                 command_noisy('read-tree', $parent);
2042                 unless ($SVN->can_do_switch) {
2043                         return _libsvn_new_tree($paths, $rev, $author, $date,
2044                                                 $log, [$parent]);
2045                 }
2046                 # do_switch works with svn/trunk >= r22312, but that is not
2047                 # included with SVN 1.4.2 (the latest version at the moment),
2048                 # so we can't rely on it.
2049                 my $ra = Git::SVN::Ra->new("$url/$branch_from");
2050                 my $ed = SVN::Git::Fetcher->new({c => $parent, q => $_q });
2051                 $ra->gs_do_switch($r0, $rev, '', 1, $SVN->{url}, $ed) or
2052                                    die "SVN connection failed somewhere...\n";
2053                 return libsvn_log_entry($rev, $author, $date, $log, [$parent]);
2054         }
2055         print STDERR "Nope, branch point not imported or unknown\n";
2056         return undef;
2059 sub _libsvn_new_tree {
2060         my ($paths, $rev, $author, $date, $log, $parents) = @_;
2061         my $ed = SVN::Git::Fetcher->new({q => $_q});
2062         unless ($SVN->gs_do_update($rev, $rev, '', 1, $ed)) {
2063                 die "SVN connection failed somewhere...\n";
2064         }
2065         libsvn_log_entry($rev, $author, $date, $log, $parents, $ed);
2068 sub find_graft_path_commit {
2069         my ($tree_paths, $p1, $r1) = @_;
2070         foreach my $x (keys %$tree_paths) {
2071                 next unless ($p1 =~ /^\Q$x\E/);
2072                 my $i = $tree_paths->{$x};
2073                 my ($r0, $parent) = find_rev_before($r1,$i,1);
2074                 return $parent if (defined $r0 && $r0 == $r1);
2075                 print STDERR "r$r1 of $i not imported\n";
2076                 next;
2077         }
2078         return undef;
2081 sub find_graft_path_parents {
2082         my ($grafts, $tree_paths, $c, $p0, $r0) = @_;
2083         foreach my $x (keys %$tree_paths) {
2084                 next unless ($p0 =~ /^\Q$x\E/);
2085                 my $i = $tree_paths->{$x};
2086                 my ($r, $parent) = find_rev_before($r0, $i, 1);
2087                 if (defined $r && defined $parent && revisions_eq($x,$r,$r0)) {
2088                         my ($url_b, undef, $uuid_b) = cmt_metadata($c);
2089                         my ($url_a, undef, $uuid_a) = cmt_metadata($parent);
2090                         next if ($url_a && $url_b && $url_a eq $url_b &&
2091                                                         $uuid_b eq $uuid_a);
2092                         $grafts->{$c}->{$parent} = 1;
2093                 }
2094         }
2097 sub libsvn_graft_file_copies {
2098         my ($grafts, $tree_paths, $path, $paths, $rev) = @_;
2099         foreach (keys %$paths) {
2100                 my $i = $paths->{$_};
2101                 my ($m, $p0, $r0) = ($i->action, $i->copyfrom_path,
2102                                         $i->copyfrom_rev);
2103                 next unless (defined $p0 && defined $r0);
2105                 my $p1 = $_;
2106                 $p1 =~ s#^/##;
2107                 $p0 =~ s#^/##;
2108                 my $c = find_graft_path_commit($tree_paths, $p1, $rev);
2109                 next unless $c;
2110                 find_graft_path_parents($grafts, $tree_paths, $c, $p0, $r0);
2111         }
2114 sub revdb_get {
2115         my ($file, $rev) = @_;
2116         my $ret;
2117         my $offset = $rev * 41;
2118         open my $fh, '<', $file or croak $!;
2119         seek $fh, $offset, 0;
2120         if (tell $fh == $offset) {
2121                 $ret = readline $fh;
2122                 if (defined $ret) {
2123                         chomp $ret;
2124                         $ret = undef if ($ret =~ /^0{40}$/);
2125                 }
2126         }
2127         close $fh or croak $!;
2128         return $ret;
2132         my $kill_stupid_warnings = $SVN::Node::none.$SVN::Node::file.
2133                                 $SVN::Node::dir.$SVN::Node::unknown.
2134                                 $SVN::Node::none.$SVN::Node::file.
2135                                 $SVN::Node::dir.$SVN::Node::unknown.
2136                                 $SVN::Auth::SSL::CNMISMATCH.
2137                                 $SVN::Auth::SSL::NOTYETVALID.
2138                                 $SVN::Auth::SSL::EXPIRED.
2139                                 $SVN::Auth::SSL::UNKNOWNCA.
2140                                 $SVN::Auth::SSL::OTHER;
2143 package SVN::Git::Fetcher;
2144 use vars qw/@ISA/;
2145 use strict;
2146 use warnings;
2147 use Carp qw/croak/;
2148 use IO::File qw//;
2150 # file baton members: path, mode_a, mode_b, pool, fh, blob, base
2151 sub new {
2152         my ($class, $git_svn) = @_;
2153         my $self = SVN::Delta::Editor->new;
2154         bless $self, $class;
2155         $self->{c} = $git_svn->{last_commit} if exists $git_svn->{last_commit};
2156         $self->{empty} = {};
2157         $self->{dir_prop} = {};
2158         $self->{file_prop} = {};
2159         $self->{absent_dir} = {};
2160         $self->{absent_file} = {};
2161         ($self->{gui}, $self->{ctx}) = $git_svn->tmp_index_do(
2162                sub { command_input_pipe(qw/update-index -z --index-info/) } );
2163         require Digest::MD5;
2164         $self;
2167 sub open_root {
2168         { path => '' };
2171 sub open_directory {
2172         my ($self, $path, $pb, $rev) = @_;
2173         { path => $path };
2176 sub delete_entry {
2177         my ($self, $path, $rev, $pb) = @_;
2178         my $gui = $self->{gui};
2180         # remove entire directories.
2181         if (command('ls-tree', $self->{c}, '--', $path) =~ /^040000 tree/) {
2182                 my ($ls, $ctx) = command_output_pipe(qw/ls-tree
2183                                                      -r --name-only -z/,
2184                                                      $self->{c}, '--', $path);
2185                 local $/ = "\0";
2186                 while (<$ls>) {
2187                         print $gui '0 ',0 x 40,"\t",$_ or croak $!;
2188                         print "\tD\t$_\n" unless $self->{q};
2189                 }
2190                 print "\tD\t$path/\n" unless $self->{q};
2191                 command_close_pipe($ls, $ctx);
2192                 $self->{empty}->{$path} = 0
2193         } else {
2194                 print $gui '0 ',0 x 40,"\t",$path,"\0" or croak $!;
2195                 print "\tD\t$path\n" unless $self->{q};
2196         }
2197         undef;
2200 sub open_file {
2201         my ($self, $path, $pb, $rev) = @_;
2202         my ($mode, $blob) = (command('ls-tree', $self->{c}, '--',$path)
2203                              =~ /^(\d{6}) blob ([a-f\d]{40})\t/);
2204         unless (defined $mode && defined $blob) {
2205                 die "$path was not found in commit $self->{c} (r$rev)\n";
2206         }
2207         { path => $path, mode_a => $mode, mode_b => $mode, blob => $blob,
2208           pool => SVN::Pool->new, action => 'M' };
2211 sub add_file {
2212         my ($self, $path, $pb, $cp_path, $cp_rev) = @_;
2213         my ($dir, $file) = ($path =~ m#^(.*?)/?([^/]+)$#);
2214         delete $self->{empty}->{$dir};
2215         { path => $path, mode_a => 100644, mode_b => 100644,
2216           pool => SVN::Pool->new, action => 'A' };
2219 sub add_directory {
2220         my ($self, $path, $cp_path, $cp_rev) = @_;
2221         my ($dir, $file) = ($path =~ m#^(.*?)/?([^/]+)$#);
2222         delete $self->{empty}->{$dir};
2223         $self->{empty}->{$path} = 1;
2224         { path => $path };
2227 sub change_dir_prop {
2228         my ($self, $db, $prop, $value) = @_;
2229         $self->{dir_prop}->{$db->{path}} ||= {};
2230         $self->{dir_prop}->{$db->{path}}->{$prop} = $value;
2231         undef;
2234 sub absent_directory {
2235         my ($self, $path, $pb) = @_;
2236         $self->{absent_dir}->{$pb->{path}} ||= [];
2237         push @{$self->{absent_dir}->{$pb->{path}}}, $path;
2238         undef;
2241 sub absent_file {
2242         my ($self, $path, $pb) = @_;
2243         $self->{absent_file}->{$pb->{path}} ||= [];
2244         push @{$self->{absent_file}->{$pb->{path}}}, $path;
2245         undef;
2248 sub change_file_prop {
2249         my ($self, $fb, $prop, $value) = @_;
2250         if ($prop eq 'svn:executable') {
2251                 if ($fb->{mode_b} != 120000) {
2252                         $fb->{mode_b} = defined $value ? 100755 : 100644;
2253                 }
2254         } elsif ($prop eq 'svn:special') {
2255                 $fb->{mode_b} = defined $value ? 120000 : 100644;
2256         } else {
2257                 $self->{file_prop}->{$fb->{path}} ||= {};
2258                 $self->{file_prop}->{$fb->{path}}->{$prop} = $value;
2259         }
2260         undef;
2263 sub apply_textdelta {
2264         my ($self, $fb, $exp) = @_;
2265         my $fh = IO::File->new_tmpfile;
2266         $fh->autoflush(1);
2267         # $fh gets auto-closed() by SVN::TxDelta::apply(),
2268         # (but $base does not,) so dup() it for reading in close_file
2269         open my $dup, '<&', $fh or croak $!;
2270         my $base = IO::File->new_tmpfile;
2271         $base->autoflush(1);
2272         if ($fb->{blob}) {
2273                 defined (my $pid = fork) or croak $!;
2274                 if (!$pid) {
2275                         open STDOUT, '>&', $base or croak $!;
2276                         print STDOUT 'link ' if ($fb->{mode_a} == 120000);
2277                         exec qw/git-cat-file blob/, $fb->{blob} or croak $!;
2278                 }
2279                 waitpid $pid, 0;
2280                 croak $? if $?;
2282                 if (defined $exp) {
2283                         seek $base, 0, 0 or croak $!;
2284                         my $md5 = Digest::MD5->new;
2285                         $md5->addfile($base);
2286                         my $got = $md5->hexdigest;
2287                         die "Checksum mismatch: $fb->{path} $fb->{blob}\n",
2288                             "expected: $exp\n",
2289                             "     got: $got\n" if ($got ne $exp);
2290                 }
2291         }
2292         seek $base, 0, 0 or croak $!;
2293         $fb->{fh} = $dup;
2294         $fb->{base} = $base;
2295         [ SVN::TxDelta::apply($base, $fh, undef, $fb->{path}, $fb->{pool}) ];
2298 sub close_file {
2299         my ($self, $fb, $exp) = @_;
2300         my $hash;
2301         my $path = $fb->{path};
2302         if (my $fh = $fb->{fh}) {
2303                 seek($fh, 0, 0) or croak $!;
2304                 my $md5 = Digest::MD5->new;
2305                 $md5->addfile($fh);
2306                 my $got = $md5->hexdigest;
2307                 die "Checksum mismatch: $path\n",
2308                     "expected: $exp\n    got: $got\n" if ($got ne $exp);
2309                 seek($fh, 0, 0) or croak $!;
2310                 if ($fb->{mode_b} == 120000) {
2311                         read($fh, my $buf, 5) == 5 or croak $!;
2312                         $buf eq 'link ' or die "$path has mode 120000",
2313                                                "but is not a link\n";
2314                 }
2315                 defined(my $pid = open my $out,'-|') or die "Can't fork: $!\n";
2316                 if (!$pid) {
2317                         open STDIN, '<&', $fh or croak $!;
2318                         exec qw/git-hash-object -w --stdin/ or croak $!;
2319                 }
2320                 chomp($hash = do { local $/; <$out> });
2321                 close $out or croak $!;
2322                 close $fh or croak $!;
2323                 $hash =~ /^[a-f\d]{40}$/ or die "not a sha1: $hash\n";
2324                 close $fb->{base} or croak $!;
2325         } else {
2326                 $hash = $fb->{blob} or die "no blob information\n";
2327         }
2328         $fb->{pool}->clear;
2329         my $gui = $self->{gui};
2330         print $gui "$fb->{mode_b} $hash\t$path\0" or croak $!;
2331         print "\t$fb->{action}\t$path\n" if $fb->{action} && ! $self->{q};
2332         undef;
2335 sub abort_edit {
2336         my $self = shift;
2337         eval { command_close_pipe($self->{gui}, $self->{ctx}) };
2338         $self->SUPER::abort_edit(@_);
2341 sub close_edit {
2342         my $self = shift;
2343         command_close_pipe($self->{gui}, $self->{ctx});
2344         $self->{git_commit_ok} = 1;
2345         $self->SUPER::close_edit(@_);
2348 package SVN::Git::Editor;
2349 use vars qw/@ISA/;
2350 use strict;
2351 use warnings;
2352 use Carp qw/croak/;
2353 use IO::File;
2355 sub new {
2356         my $class = shift;
2357         my $git_svn = shift;
2358         my $self = SVN::Delta::Editor->new(@_);
2359         bless $self, $class;
2360         foreach (qw/svn_path r ra/) {
2361                 die "$_ required!\n" unless (defined $git_svn->{$_});
2362                 $self->{$_} = $git_svn->{$_};
2363         }
2364         $self->{pool} = SVN::Pool->new;
2365         $self->{bat} = { '' => $self->open_root($self->{r}, $self->{pool}) };
2366         $self->{rm} = { };
2367         require Digest::MD5;
2368         return $self;
2371 sub split_path {
2372         return ($_[0] =~ m#^(.*?)/?([^/]+)$#);
2375 sub repo_path {
2376         (defined $_[1] && length $_[1]) ? $_[1] : ''
2379 sub url_path {
2380         my ($self, $path) = @_;
2381         $self->{ra}->{url} . '/' . $self->repo_path($path);
2384 sub rmdirs {
2385         my ($self, $tree_b) = @_;
2386         my $rm = $self->{rm};
2387         delete $rm->{''}; # we never delete the url we're tracking
2388         return unless %$rm;
2390         foreach (keys %$rm) {
2391                 my @d = split m#/#, $_;
2392                 my $c = shift @d;
2393                 $rm->{$c} = 1;
2394                 while (@d) {
2395                         $c .= '/' . shift @d;
2396                         $rm->{$c} = 1;
2397                 }
2398         }
2399         delete $rm->{$self->{svn_path}};
2400         delete $rm->{''}; # we never delete the url we're tracking
2401         return unless %$rm;
2403         my ($fh, $ctx) = command_output_pipe(
2404                                    qw/ls-tree --name-only -r -z/, $tree_b);
2405         local $/ = "\0";
2406         while (<$fh>) {
2407                 chomp;
2408                 my @dn = split m#/#, $_;
2409                 while (pop @dn) {
2410                         delete $rm->{join '/', @dn};
2411                 }
2412                 unless (%$rm) {
2413                         close $fh;
2414                         return;
2415                 }
2416         }
2417         command_close_pipe($fh, $ctx);
2419         my ($r, $p, $bat) = ($self->{r}, $self->{pool}, $self->{bat});
2420         foreach my $d (sort { $b =~ tr#/#/# <=> $a =~ tr#/#/# } keys %$rm) {
2421                 $self->close_directory($bat->{$d}, $p);
2422                 my ($dn) = ($d =~ m#^(.*?)/?(?:[^/]+)$#);
2423                 print "\tD+\t$d/\n" unless $::_q;
2424                 $self->SUPER::delete_entry($d, $r, $bat->{$dn}, $p);
2425                 delete $bat->{$d};
2426         }
2429 sub open_or_add_dir {
2430         my ($self, $full_path, $baton) = @_;
2431         my $t = $self->{ra}->check_path($full_path, $self->{r});
2432         if ($t == $SVN::Node::none) {
2433                 return $self->add_directory($full_path, $baton,
2434                                                 undef, -1, $self->{pool});
2435         } elsif ($t == $SVN::Node::dir) {
2436                 return $self->open_directory($full_path, $baton,
2437                                                 $self->{r}, $self->{pool});
2438         }
2439         print STDERR "$full_path already exists in repository at ",
2440                 "r$self->{r} and it is not a directory (",
2441                 ($t == $SVN::Node::file ? 'file' : 'unknown'),"/$t)\n";
2442         exit 1;
2445 sub ensure_path {
2446         my ($self, $path) = @_;
2447         my $bat = $self->{bat};
2448         $path = $self->repo_path($path);
2449         return $bat->{''} unless (length $path);
2450         my @p = split m#/+#, $path;
2451         my $c = shift @p;
2452         $bat->{$c} ||= $self->open_or_add_dir($c, $bat->{''});
2453         while (@p) {
2454                 my $c0 = $c;
2455                 $c .= '/' . shift @p;
2456                 $bat->{$c} ||= $self->open_or_add_dir($c, $bat->{$c0});
2457         }
2458         return $bat->{$c};
2461 sub A {
2462         my ($self, $m) = @_;
2463         my ($dir, $file) = split_path($m->{file_b});
2464         my $pbat = $self->ensure_path($dir);
2465         my $fbat = $self->add_file($self->repo_path($m->{file_b}), $pbat,
2466                                         undef, -1);
2467         print "\tA\t$m->{file_b}\n" unless $::_q;
2468         $self->chg_file($fbat, $m);
2469         $self->close_file($fbat,undef,$self->{pool});
2472 sub C {
2473         my ($self, $m) = @_;
2474         my ($dir, $file) = split_path($m->{file_b});
2475         my $pbat = $self->ensure_path($dir);
2476         my $fbat = $self->add_file($self->repo_path($m->{file_b}), $pbat,
2477                                 $self->url_path($m->{file_a}), $self->{r});
2478         print "\tC\t$m->{file_a} => $m->{file_b}\n" unless $::_q;
2479         $self->chg_file($fbat, $m);
2480         $self->close_file($fbat,undef,$self->{pool});
2483 sub delete_entry {
2484         my ($self, $path, $pbat) = @_;
2485         my $rpath = $self->repo_path($path);
2486         my ($dir, $file) = split_path($rpath);
2487         $self->{rm}->{$dir} = 1;
2488         $self->SUPER::delete_entry($rpath, $self->{r}, $pbat, $self->{pool});
2491 sub R {
2492         my ($self, $m) = @_;
2493         my ($dir, $file) = split_path($m->{file_b});
2494         my $pbat = $self->ensure_path($dir);
2495         my $fbat = $self->add_file($self->repo_path($m->{file_b}), $pbat,
2496                                 $self->url_path($m->{file_a}), $self->{r});
2497         print "\tR\t$m->{file_a} => $m->{file_b}\n" unless $::_q;
2498         $self->chg_file($fbat, $m);
2499         $self->close_file($fbat,undef,$self->{pool});
2501         ($dir, $file) = split_path($m->{file_a});
2502         $pbat = $self->ensure_path($dir);
2503         $self->delete_entry($m->{file_a}, $pbat);
2506 sub M {
2507         my ($self, $m) = @_;
2508         my ($dir, $file) = split_path($m->{file_b});
2509         my $pbat = $self->ensure_path($dir);
2510         my $fbat = $self->open_file($self->repo_path($m->{file_b}),
2511                                 $pbat,$self->{r},$self->{pool});
2512         print "\t$m->{chg}\t$m->{file_b}\n" unless $::_q;
2513         $self->chg_file($fbat, $m);
2514         $self->close_file($fbat,undef,$self->{pool});
2517 sub T { shift->M(@_) }
2519 sub change_file_prop {
2520         my ($self, $fbat, $pname, $pval) = @_;
2521         $self->SUPER::change_file_prop($fbat, $pname, $pval, $self->{pool});
2524 sub chg_file {
2525         my ($self, $fbat, $m) = @_;
2526         if ($m->{mode_b} =~ /755$/ && $m->{mode_a} !~ /755$/) {
2527                 $self->change_file_prop($fbat,'svn:executable','*');
2528         } elsif ($m->{mode_b} !~ /755$/ && $m->{mode_a} =~ /755$/) {
2529                 $self->change_file_prop($fbat,'svn:executable',undef);
2530         }
2531         my $fh = IO::File->new_tmpfile or croak $!;
2532         if ($m->{mode_b} =~ /^120/) {
2533                 print $fh 'link ' or croak $!;
2534                 $self->change_file_prop($fbat,'svn:special','*');
2535         } elsif ($m->{mode_a} =~ /^120/ && $m->{mode_b} !~ /^120/) {
2536                 $self->change_file_prop($fbat,'svn:special',undef);
2537         }
2538         defined(my $pid = fork) or croak $!;
2539         if (!$pid) {
2540                 open STDOUT, '>&', $fh or croak $!;
2541                 exec qw/git-cat-file blob/, $m->{sha1_b} or croak $!;
2542         }
2543         waitpid $pid, 0;
2544         croak $? if $?;
2545         $fh->flush == 0 or croak $!;
2546         seek $fh, 0, 0 or croak $!;
2548         my $md5 = Digest::MD5->new;
2549         $md5->addfile($fh) or croak $!;
2550         seek $fh, 0, 0 or croak $!;
2552         my $exp = $md5->hexdigest;
2553         my $pool = SVN::Pool->new;
2554         my $atd = $self->apply_textdelta($fbat, undef, $pool);
2555         my $got = SVN::TxDelta::send_stream($fh, @$atd, $pool);
2556         die "Checksum mismatch\nexpected: $exp\ngot: $got\n" if ($got ne $exp);
2557         $pool->clear;
2559         close $fh or croak $!;
2562 sub D {
2563         my ($self, $m) = @_;
2564         my ($dir, $file) = split_path($m->{file_b});
2565         my $pbat = $self->ensure_path($dir);
2566         print "\tD\t$m->{file_b}\n" unless $::_q;
2567         $self->delete_entry($m->{file_b}, $pbat);
2570 sub close_edit {
2571         my ($self) = @_;
2572         my ($p,$bat) = ($self->{pool}, $self->{bat});
2573         foreach (sort { $b =~ tr#/#/# <=> $a =~ tr#/#/# } keys %$bat) {
2574                 $self->close_directory($bat->{$_}, $p);
2575         }
2576         $self->SUPER::close_edit($p);
2577         $p->clear;
2580 sub abort_edit {
2581         my ($self) = @_;
2582         $self->SUPER::abort_edit($self->{pool});
2583         $self->{pool}->clear;
2586 # this drives the editor
2587 sub apply_diff {
2588         my ($self, $tree_a, $tree_b) = @_;
2589         my @diff_tree = qw(diff-tree -z -r);
2590         if ($::_cp_similarity) {
2591                 push @diff_tree, "-C$::_cp_similarity";
2592         } else {
2593                 push @diff_tree, '-C';
2594         }
2595         push @diff_tree, '--find-copies-harder' if $::_find_copies_harder;
2596         push @diff_tree, "-l$::_l" if defined $::_l;
2597         push @diff_tree, $tree_a, $tree_b;
2598         my ($diff_fh, $ctx) = command_output_pipe(@diff_tree);
2599         my $nl = $/;
2600         local $/ = "\0";
2601         my $state = 'meta';
2602         my @mods;
2603         while (<$diff_fh>) {
2604                 chomp $_; # this gets rid of the trailing "\0"
2605                 if ($state eq 'meta' && /^:(\d{6})\s(\d{6})\s
2606                                         $::sha1\s($::sha1)\s
2607                                         ([MTCRAD])\d*$/xo) {
2608                         push @mods, {   mode_a => $1, mode_b => $2,
2609                                         sha1_b => $3, chg => $4 };
2610                         if ($4 =~ /^(?:C|R)$/) {
2611                                 $state = 'file_a';
2612                         } else {
2613                                 $state = 'file_b';
2614                         }
2615                 } elsif ($state eq 'file_a') {
2616                         my $x = $mods[$#mods] or croak "Empty array\n";
2617                         if ($x->{chg} !~ /^(?:C|R)$/) {
2618                                 croak "Error parsing $_, $x->{chg}\n";
2619                         }
2620                         $x->{file_a} = $_;
2621                         $state = 'file_b';
2622                 } elsif ($state eq 'file_b') {
2623                         my $x = $mods[$#mods] or croak "Empty array\n";
2624                         if (exists $x->{file_a} && $x->{chg} !~ /^(?:C|R)$/) {
2625                                 croak "Error parsing $_, $x->{chg}\n";
2626                         }
2627                         if (!exists $x->{file_a} && $x->{chg} =~ /^(?:C|R)$/) {
2628                                 croak "Error parsing $_, $x->{chg}\n";
2629                         }
2630                         $x->{file_b} = $_;
2631                         $state = 'meta';
2632                 } else {
2633                         croak "Error parsing $_\n";
2634                 }
2635         }
2636         command_close_pipe($diff_fh, $ctx);
2637         $/ = $nl;
2639         my %o = ( D => 1, R => 0, C => -1, A => 3, M => 3, T => 3 );
2640         foreach my $m (sort { $o{$a->{chg}} <=> $o{$b->{chg}} } @mods) {
2641                 my $f = $m->{chg};
2642                 if (defined $o{$f}) {
2643                         $self->$f($m);
2644                 } else {
2645                         fatal("Invalid change type: $f\n");
2646                 }
2647         }
2648         $self->rmdirs($tree_b) if $::_rmdir;
2649         if (@mods == 0) {
2650                 $self->abort_edit;
2651         } else {
2652                 $self->close_edit;
2653         }
2654         \@mods;
2657 package Git::SVN::Ra;
2658 use vars qw/@ISA $config_dir/;
2659 use strict;
2660 use warnings;
2661 my ($can_do_switch);
2663 BEGIN {
2664         # enforce temporary pool usage for some simple functions
2665         my $e;
2666         foreach (qw/get_latest_revnum rev_proplist get_file
2667                     check_path get_dir get_uuid get_repos_root/) {
2668                 $e .= "sub $_ {
2669                         my \$self = shift;
2670                         my \$pool = SVN::Pool->new;
2671                         my \@ret = \$self->SUPER::$_(\@_,\$pool);
2672                         \$pool->clear;
2673                         wantarray ? \@ret : \$ret[0]; }\n";
2674         }
2675         eval $e;
2678 sub new {
2679         my ($class, $url) = @_;
2680         SVN::_Core::svn_config_ensure($config_dir, undef);
2681         my ($baton, $callbacks) = SVN::Core::auth_open_helper([
2682             SVN::Client::get_simple_provider(),
2683             SVN::Client::get_ssl_server_trust_file_provider(),
2684             SVN::Client::get_simple_prompt_provider(
2685               \&Git::SVN::Prompt::simple, 2),
2686             SVN::Client::get_ssl_client_cert_prompt_provider(
2687               \&Git::SVN::Prompt::ssl_client_cert, 2),
2688             SVN::Client::get_ssl_client_cert_pw_prompt_provider(
2689               \&Git::SVN::Prompt::ssl_client_cert_pw, 2),
2690             SVN::Client::get_username_provider(),
2691             SVN::Client::get_ssl_server_trust_prompt_provider(
2692               \&Git::SVN::Prompt::ssl_server_trust),
2693             SVN::Client::get_username_prompt_provider(
2694               \&Git::SVN::Prompt::username, 2),
2695           ]);
2696         my $config = SVN::Core::config_get_config($config_dir);
2697         my $self = SVN::Ra->new(url => $url, auth => $baton,
2698                               config => $config,
2699                               pool => SVN::Pool->new,
2700                               auth_provider_callbacks => $callbacks);
2701         $self->{svn_path} = $url;
2702         $self->{repos_root} = $self->get_repos_root;
2703         $self->{svn_path} =~ s#^\Q$self->{repos_root}\E/*##;
2704         bless $self, $class;
2707 sub DESTROY {
2708         my $self = shift;
2709         $self->{pool}->clear if $self->{pool};
2710         $self->SUPER::DESTROY(@_);
2713 sub dup {
2714         my ($self) = @_;
2715         my $dup = SVN::Ra->new(pool => SVN::Pool->new,
2716                                 map { $_ => $self->{$_} } qw/config url
2717                      auth auth_provider_callbacks repos_root svn_path/);
2718         bless $dup, ref $self;
2721 sub get_log {
2722         my ($self, @args) = @_;
2723         my $pool = SVN::Pool->new;
2724         $args[4]-- if $args[4] && ! $::_follow_parent;
2725         splice(@args, 3, 1) if ($SVN::Core::VERSION le '1.2.0');
2726         my $ret = $self->SUPER::get_log(@args, $pool);
2727         $pool->clear;
2728         $ret;
2731 sub get_commit_editor {
2732         my ($self, $log, $cb, $pool) = @_;
2733         my @lock = $SVN::Core::VERSION ge '1.2.0' ? (undef, 0) : ();
2734         $self->SUPER::get_commit_editor($log, $cb, @lock, $pool);
2737 sub uuid {
2738         my ($self) = @_;
2739         $self->{uuid} ||= $self->get_uuid;
2742 sub gs_do_update {
2743         my ($self, $rev_a, $rev_b, $path, $recurse, $editor) = @_;
2744         my $pool = SVN::Pool->new;
2745         my $reporter = $self->do_update($rev_b, $path, $recurse,
2746                                         $editor, $pool);
2747         my @lock = $SVN::Core::VERSION ge '1.2.0' ? (undef) : ();
2748         my $new = ($rev_a == $rev_b);
2749         $reporter->set_path($path, $rev_a, $new, @lock, $pool);
2750         $reporter->finish_report($pool);
2751         $pool->clear;
2752         $editor->{git_commit_ok};
2755 sub gs_do_switch {
2756         my ($self, $rev_a, $rev_b, $path, $recurse, $url_b, $editor) = @_;
2757         my $pool = SVN::Pool->new;
2758         my $reporter = $self->do_switch($rev_b, $path, $recurse,
2759                                         $url_b, $editor, $pool);
2760         my @lock = $SVN::Core::VERSION ge '1.2.0' ? (undef) : ();
2761         $reporter->set_path($path, $rev_a, 0, @lock, $pool);
2762         $reporter->finish_report($pool);
2763         $pool->clear;
2764         $editor->{git_commit_ok};
2767 sub can_do_switch {
2768         my $self = shift;
2769         unless (defined $can_do_switch) {
2770                 my $pool = SVN::Pool->new;
2771                 my $rep = eval {
2772                         $self->do_switch(1, '', 0, $self->{url},
2773                                          SVN::Delta::Editor->new, $pool);
2774                 };
2775                 if ($@) {
2776                         $can_do_switch = 0;
2777                 } else {
2778                         $rep->abort_report($pool);
2779                         $can_do_switch = 1;
2780                 }
2781                 $pool->clear;
2782         }
2783         $can_do_switch;
2786 package Git::SVN::Log;
2787 use strict;
2788 use warnings;
2789 use POSIX qw/strftime/;
2790 use vars qw/$TZ $limit $color $pager $non_recursive $verbose $oneline
2791             %rusers $show_commit $incremental/;
2792 my $l_fmt;
2794 sub cmt_showable {
2795         my ($c) = @_;
2796         return 1 if defined $c->{r};
2797         if ($c->{l} && $c->{l}->[-1] eq "...\n" &&
2798                                 $c->{a_raw} =~ /\@([a-f\d\-]+)>$/) {
2799                 my @log = command(qw/cat-file commit/, $c->{c});
2800                 shift @log while ($log[0] ne "\n");
2801                 shift @log;
2802                 @{$c->{l}} = grep !/^git-svn-id: /, @log;
2804                 (undef, $c->{r}, undef) = ::extract_metadata(
2805                                 (grep(/^git-svn-id: /, @log))[-1]);
2806         }
2807         return defined $c->{r};
2810 sub log_use_color {
2811         return 1 if $color;
2812         my ($dc, $dcvar);
2813         $dcvar = 'color.diff';
2814         $dc = `git-config --get $dcvar`;
2815         if ($dc eq '') {
2816                 # nothing at all; fallback to "diff.color"
2817                 $dcvar = 'diff.color';
2818                 $dc = `git-config --get $dcvar`;
2819         }
2820         chomp($dc);
2821         if ($dc eq 'auto') {
2822                 my $pc;
2823                 $pc = `git-config --get color.pager`;
2824                 if ($pc eq '') {
2825                         # does not have it -- fallback to pager.color
2826                         $pc = `git-config --bool --get pager.color`;
2827                 }
2828                 else {
2829                         $pc = `git-config --bool --get color.pager`;
2830                         if ($?) {
2831                                 $pc = 'false';
2832                         }
2833                 }
2834                 chomp($pc);
2835                 if (-t *STDOUT || (defined $pager && $pc eq 'true')) {
2836                         return ($ENV{TERM} && $ENV{TERM} ne 'dumb');
2837                 }
2838                 return 0;
2839         }
2840         return 0 if $dc eq 'never';
2841         return 1 if $dc eq 'always';
2842         chomp($dc = `git-config --bool --get $dcvar`);
2843         return ($dc eq 'true');
2846 sub git_svn_log_cmd {
2847         my ($r_min, $r_max) = @_;
2848         my $gs = Git::SVN->_new;
2849         my @cmd = (qw/log --abbrev-commit --pretty=raw --default/,
2850                    $gs->refname);
2851         push @cmd, '-r' unless $non_recursive;
2852         push @cmd, qw/--raw --name-status/ if $verbose;
2853         push @cmd, '--color' if log_use_color();
2854         return @cmd unless defined $r_max;
2855         if ($r_max == $r_min) {
2856                 push @cmd, '--max-count=1';
2857                 if (my $c = $gs->rev_db_get($r_max)) {
2858                         push @cmd, $c;
2859                 }
2860         } else {
2861                 my ($c_min, $c_max);
2862                 $c_max = $gs->rev_db_get($r_max);
2863                 $c_min = $gs->rev_db_get($r_min);
2864                 if (defined $c_min && defined $c_max) {
2865                         if ($r_max > $r_max) {
2866                                 push @cmd, "$c_min..$c_max";
2867                         } else {
2868                                 push @cmd, "$c_max..$c_min";
2869                         }
2870                 } elsif ($r_max > $r_min) {
2871                         push @cmd, $c_max;
2872                 } else {
2873                         push @cmd, $c_min;
2874                 }
2875         }
2876         return @cmd;
2879 # adapted from pager.c
2880 sub config_pager {
2881         $pager ||= $ENV{GIT_PAGER} || $ENV{PAGER};
2882         if (!defined $pager) {
2883                 $pager = 'less';
2884         } elsif (length $pager == 0 || $pager eq 'cat') {
2885                 $pager = undef;
2886         }
2889 sub run_pager {
2890         return unless -t *STDOUT;
2891         pipe my $rfd, my $wfd or return;
2892         defined(my $pid = fork) or ::fatal "Can't fork: $!\n";
2893         if (!$pid) {
2894                 open STDOUT, '>&', $wfd or
2895                                      ::fatal "Can't redirect to stdout: $!\n";
2896                 return;
2897         }
2898         open STDIN, '<&', $rfd or ::fatal "Can't redirect stdin: $!\n";
2899         $ENV{LESS} ||= 'FRSX';
2900         exec $pager or ::fatal "Can't run pager: $! ($pager)\n";
2903 sub get_author_info {
2904         my ($dest, $author, $t, $tz) = @_;
2905         $author =~ s/(?:^\s*|\s*$)//g;
2906         $dest->{a_raw} = $author;
2907         my $au;
2908         if ($::_authors) {
2909                 $au = $rusers{$author} || undef;
2910         }
2911         if (!$au) {
2912                 ($au) = ($author =~ /<([^>]+)\@[^>]+>$/);
2913         }
2914         $dest->{t} = $t;
2915         $dest->{tz} = $tz;
2916         $dest->{a} = $au;
2917         # Date::Parse isn't in the standard Perl distro :(
2918         if ($tz =~ s/^\+//) {
2919                 $t += ::tz_to_s_offset($tz);
2920         } elsif ($tz =~ s/^\-//) {
2921                 $t -= ::tz_to_s_offset($tz);
2922         }
2923         $dest->{t_utc} = $t;
2926 sub process_commit {
2927         my ($c, $r_min, $r_max, $defer) = @_;
2928         if (defined $r_min && defined $r_max) {
2929                 if ($r_min == $c->{r} && $r_min == $r_max) {
2930                         show_commit($c);
2931                         return 0;
2932                 }
2933                 return 1 if $r_min == $r_max;
2934                 if ($r_min < $r_max) {
2935                         # we need to reverse the print order
2936                         return 0 if (defined $limit && --$limit < 0);
2937                         push @$defer, $c;
2938                         return 1;
2939                 }
2940                 if ($r_min != $r_max) {
2941                         return 1 if ($r_min < $c->{r});
2942                         return 1 if ($r_max > $c->{r});
2943                 }
2944         }
2945         return 0 if (defined $limit && --$limit < 0);
2946         show_commit($c);
2947         return 1;
2950 sub show_commit {
2951         my $c = shift;
2952         if ($oneline) {
2953                 my $x = "\n";
2954                 if (my $l = $c->{l}) {
2955                         while ($l->[0] =~ /^\s*$/) { shift @$l }
2956                         $x = $l->[0];
2957                 }
2958                 $l_fmt ||= 'A' . length($c->{r});
2959                 print 'r',pack($l_fmt, $c->{r}),' | ';
2960                 print "$c->{c} | " if $show_commit;
2961                 print $x;
2962         } else {
2963                 show_commit_normal($c);
2964         }
2967 sub show_commit_changed_paths {
2968         my ($c) = @_;
2969         return unless $c->{changed};
2970         print "Changed paths:\n", @{$c->{changed}};
2973 sub show_commit_normal {
2974         my ($c) = @_;
2975         print '-' x72, "\nr$c->{r} | ";
2976         print "$c->{c} | " if $show_commit;
2977         print "$c->{a} | ", strftime("%Y-%m-%d %H:%M:%S %z (%a, %d %b %Y)",
2978                                  localtime($c->{t_utc})), ' | ';
2979         my $nr_line = 0;
2981         if (my $l = $c->{l}) {
2982                 while ($l->[$#$l] eq "\n" && $#$l > 0
2983                                           && $l->[($#$l - 1)] eq "\n") {
2984                         pop @$l;
2985                 }
2986                 $nr_line = scalar @$l;
2987                 if (!$nr_line) {
2988                         print "1 line\n\n\n";
2989                 } else {
2990                         if ($nr_line == 1) {
2991                                 $nr_line = '1 line';
2992                         } else {
2993                                 $nr_line .= ' lines';
2994                         }
2995                         print $nr_line, "\n";
2996                         show_commit_changed_paths($c);
2997                         print "\n";
2998                         print $_ foreach @$l;
2999                 }
3000         } else {
3001                 print "1 line\n";
3002                 show_commit_changed_paths($c);
3003                 print "\n";
3005         }
3006         foreach my $x (qw/raw diff/) {
3007                 if ($c->{$x}) {
3008                         print "\n";
3009                         print $_ foreach @{$c->{$x}}
3010                 }
3011         }
3014 sub cmd_show_log {
3015         my (@args) = @_;
3016         my ($r_min, $r_max);
3017         my $r_last = -1; # prevent dupes
3018         if (defined $TZ) {
3019                 $ENV{TZ} = $TZ;
3020         } else {
3021                 delete $ENV{TZ};
3022         }
3023         if (defined $::_revision) {
3024                 if ($::_revision =~ /^(\d+):(\d+)$/) {
3025                         ($r_min, $r_max) = ($1, $2);
3026                 } elsif ($::_revision =~ /^\d+$/) {
3027                         $r_min = $r_max = $::_revision;
3028                 } else {
3029                         ::fatal "-r$::_revision is not supported, use ",
3030                                 "standard \'git log\' arguments instead\n";
3031                 }
3032         }
3034         config_pager();
3035         @args = (git_svn_log_cmd($r_min, $r_max), @args);
3036         my $log = command_output_pipe(@args);
3037         run_pager();
3038         my (@k, $c, $d);
3039         my $esc_color = qr/(?:\033\[(?:(?:\d+;)*\d*)?m)*/;
3040         while (<$log>) {
3041                 if (/^${esc_color}commit ($::sha1_short)/o) {
3042                         my $cmt = $1;
3043                         if ($c && cmt_showable($c) && $c->{r} != $r_last) {
3044                                 $r_last = $c->{r};
3045                                 process_commit($c, $r_min, $r_max, \@k) or
3046                                                                 goto out;
3047                         }
3048                         $d = undef;
3049                         $c = { c => $cmt };
3050                 } elsif (/^${esc_color}author (.+) (\d+) ([\-\+]?\d+)$/o) {
3051                         get_author_info($c, $1, $2, $3);
3052                 } elsif (/^${esc_color}(?:tree|parent|committer) /o) {
3053                         # ignore
3054                 } elsif (/^${esc_color}:\d{6} \d{6} $::sha1_short/o) {
3055                         push @{$c->{raw}}, $_;
3056                 } elsif (/^${esc_color}[ACRMDT]\t/) {
3057                         # we could add $SVN->{svn_path} here, but that requires
3058                         # remote access at the moment (repo_path_split)...
3059                         s#^(${esc_color})([ACRMDT])\t#$1   $2 #o;
3060                         push @{$c->{changed}}, $_;
3061                 } elsif (/^${esc_color}diff /o) {
3062                         $d = 1;
3063                         push @{$c->{diff}}, $_;
3064                 } elsif ($d) {
3065                         push @{$c->{diff}}, $_;
3066                 } elsif (/^${esc_color}    (git-svn-id:.+)$/o) {
3067                         ($c->{url}, $c->{r}, undef) = ::extract_metadata($1);
3068                 } elsif (s/^${esc_color}    //o) {
3069                         push @{$c->{l}}, $_;
3070                 }
3071         }
3072         if ($c && defined $c->{r} && $c->{r} != $r_last) {
3073                 $r_last = $c->{r};
3074                 process_commit($c, $r_min, $r_max, \@k);
3075         }
3076         if (@k) {
3077                 my $swap = $r_max;
3078                 $r_max = $r_min;
3079                 $r_min = $swap;
3080                 process_commit($_, $r_min, $r_max) foreach reverse @k;
3081         }
3082 out:
3083         close $log;
3084         print '-' x72,"\n" unless $incremental || $oneline;
3087 __END__
3089 Data structures:
3091 $log_entry hashref as returned by libsvn_log_entry()
3093         log => 'whitespace-formatted log entry
3094 ',                                              # trailing newline is preserved
3095         revision => '8',                        # integer
3096         date => '2004-02-24T17:01:44.108345Z',  # commit date
3097         author => 'committer name'
3098 };
3100 @mods = array of diff-index line hashes, each element represents one line
3101         of diff-index output
3103 diff-index line ($m hash)
3105         mode_a => first column of diff-index output, no leading ':',
3106         mode_b => second column of diff-index output,
3107         sha1_b => sha1sum of the final blob,
3108         chg => change type [MCRADT],
3109         file_a => original file name of a file (iff chg is 'C' or 'R')
3110         file_b => new/current file name of a file (any chg)
3114 # retval of read_url_paths{,_all}();
3115 $l_map = {
3116         # repository root url
3117         'https://svn.musicpd.org' => {
3118                 # repository path               # GIT_SVN_ID
3119                 'mpd/trunk'             =>      'trunk',
3120                 'mpd/tags/0.11.5'       =>      'tags/0.11.5',
3121         },
3124 Notes:
3125         I don't trust the each() function on unless I created %hash myself
3126         because the internal iterator may not have started at base.