Code

git-svn: Save init/clone --ignore-paths in config
[git.git] / git-svn.perl
1 #!/usr/bin/env perl
2 # Copyright (C) 2006, Eric Wong <normalperson@yhbt.net>
3 # License: GPL v2 or later
4 use warnings;
5 use strict;
6 use vars qw/    $AUTHOR $VERSION
7                 $sha1 $sha1_short $_revision $_repository
8                 $_q $_authors %users/;
9 $AUTHOR = 'Eric Wong <normalperson@yhbt.net>';
10 $VERSION = '@@GIT_VERSION@@';
12 # From which subdir have we been invoked?
13 my $cmd_dir_prefix = eval {
14         command_oneline([qw/rev-parse --show-prefix/], STDERR => 0)
15 } || '';
17 my $git_dir_user_set = 1 if defined $ENV{GIT_DIR};
18 $ENV{GIT_DIR} ||= '.git';
19 $Git::SVN::default_repo_id = 'svn';
20 $Git::SVN::default_ref_id = $ENV{GIT_SVN_ID} || 'git-svn';
21 $Git::SVN::Ra::_log_window_size = 100;
23 $Git::SVN::Log::TZ = $ENV{TZ};
24 $ENV{TZ} = 'UTC';
25 $| = 1; # unbuffer STDOUT
27 sub fatal (@) { print STDERR "@_\n"; 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)";
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 Digest::MD5;
39 use IO::File qw//;
40 use File::Basename qw/dirname basename/;
41 use File::Path qw/mkpath/;
42 use Getopt::Long qw/:config gnu_getopt no_ignore_case auto_abbrev/;
43 use IPC::Open3;
44 use Git;
46 BEGIN {
47         # import functions from Git into our packages, en masse
48         no strict 'refs';
49         foreach (qw/command command_oneline command_noisy command_output_pipe
50                     command_input_pipe command_close_pipe
51                     command_bidi_pipe command_close_bidi_pipe/) {
52                 for my $package ( qw(SVN::Git::Editor SVN::Git::Fetcher
53                         Git::SVN::Migration Git::SVN::Log Git::SVN),
54                         __PACKAGE__) {
55                         *{"${package}::$_"} = \&{"Git::$_"};
56                 }
57         }
58 }
60 my ($SVN);
62 $sha1 = qr/[a-f\d]{40}/;
63 $sha1_short = qr/[a-f\d]{4,40}/;
64 my ($_stdin, $_help, $_edit,
65         $_message, $_file,
66         $_template, $_shared,
67         $_version, $_fetch_all, $_no_rebase, $_fetch_parent,
68         $_merge, $_strategy, $_dry_run, $_local,
69         $_prefix, $_no_checkout, $_url, $_verbose,
70         $_git_format, $_commit_url, $_tag);
71 $Git::SVN::_follow_parent = 1;
72 $_q ||= 0;
73 my %remote_opts = ( 'username=s' => \$Git::SVN::Prompt::_username,
74                     'config-dir=s' => \$Git::SVN::Ra::config_dir,
75                     'no-auth-cache' => \$Git::SVN::Prompt::_no_auth_cache,
76                     'ignore-paths=s' => \$SVN::Git::Fetcher::_ignore_regex );
77 my %fc_opts = ( 'follow-parent|follow!' => \$Git::SVN::_follow_parent,
78                 'authors-file|A=s' => \$_authors,
79                 'repack:i' => \$Git::SVN::_repack,
80                 'noMetadata' => \$Git::SVN::_no_metadata,
81                 'useSvmProps' => \$Git::SVN::_use_svm_props,
82                 'useSvnsyncProps' => \$Git::SVN::_use_svnsync_props,
83                 'log-window-size=i' => \$Git::SVN::Ra::_log_window_size,
84                 'no-checkout' => \$_no_checkout,
85                 'quiet|q+' => \$_q,
86                 'repack-flags|repack-args|repack-opts=s' =>
87                    \$Git::SVN::_repack_flags,
88                 'use-log-author' => \$Git::SVN::_use_log_author,
89                 'add-author-from' => \$Git::SVN::_add_author_from,
90                 'localtime' => \$Git::SVN::_localtime,
91                 %remote_opts );
93 my ($_trunk, $_tags, $_branches, $_stdlayout);
94 my %icv;
95 my %init_opts = ( 'template=s' => \$_template, 'shared:s' => \$_shared,
96                   'trunk|T=s' => \$_trunk, 'tags|t=s' => \$_tags,
97                   'branches|b=s' => \$_branches, 'prefix=s' => \$_prefix,
98                   'stdlayout|s' => \$_stdlayout,
99                   'minimize-url|m' => \$Git::SVN::_minimize_url,
100                   'no-metadata' => sub { $icv{noMetadata} = 1 },
101                   'use-svm-props' => sub { $icv{useSvmProps} = 1 },
102                   'use-svnsync-props' => sub { $icv{useSvnsyncProps} = 1 },
103                   'rewrite-root=s' => sub { $icv{rewriteRoot} = $_[1] },
104                   %remote_opts );
105 my %cmt_opts = ( 'edit|e' => \$_edit,
106                 'rmdir' => \$SVN::Git::Editor::_rmdir,
107                 'find-copies-harder' => \$SVN::Git::Editor::_find_copies_harder,
108                 'l=i' => \$SVN::Git::Editor::_rename_limit,
109                 'copy-similarity|C=i'=> \$SVN::Git::Editor::_cp_similarity
110 );
112 my %cmd = (
113         fetch => [ \&cmd_fetch, "Download new revisions from SVN",
114                         { 'revision|r=s' => \$_revision,
115                           'fetch-all|all' => \$_fetch_all,
116                           'parent|p' => \$_fetch_parent,
117                            %fc_opts } ],
118         clone => [ \&cmd_clone, "Initialize and fetch revisions",
119                         { 'revision|r=s' => \$_revision,
120                            %fc_opts, %init_opts } ],
121         init => [ \&cmd_init, "Initialize a repo for tracking" .
122                           " (requires URL argument)",
123                           \%init_opts ],
124         'multi-init' => [ \&cmd_multi_init,
125                           "Deprecated alias for ".
126                           "'$0 init -T<trunk> -b<branches> -t<tags>'",
127                           \%init_opts ],
128         dcommit => [ \&cmd_dcommit,
129                      'Commit several diffs to merge with upstream',
130                         { 'merge|m|M' => \$_merge,
131                           'strategy|s=s' => \$_strategy,
132                           'verbose|v' => \$_verbose,
133                           'dry-run|n' => \$_dry_run,
134                           'fetch-all|all' => \$_fetch_all,
135                           'commit-url=s' => \$_commit_url,
136                           'revision|r=i' => \$_revision,
137                           'no-rebase' => \$_no_rebase,
138                         %cmt_opts, %fc_opts } ],
139         branch => [ \&cmd_branch,
140                     'Create a branch in the SVN repository',
141                     { 'message|m=s' => \$_message,
142                       'dry-run|n' => \$_dry_run,
143                       'tag|t' => \$_tag } ],
144         tag => [ sub { $_tag = 1; cmd_branch(@_) },
145                  'Create a tag in the SVN repository',
146                  { 'message|m=s' => \$_message,
147                    'dry-run|n' => \$_dry_run } ],
148         'set-tree' => [ \&cmd_set_tree,
149                         "Set an SVN repository to a git tree-ish",
150                         { 'stdin|' => \$_stdin, %cmt_opts, %fc_opts, } ],
151         'create-ignore' => [ \&cmd_create_ignore,
152                              'Create a .gitignore per svn:ignore',
153                              { 'revision|r=i' => \$_revision
154                              } ],
155         'propget' => [ \&cmd_propget,
156                        'Print the value of a property on a file or directory',
157                        { 'revision|r=i' => \$_revision } ],
158         'proplist' => [ \&cmd_proplist,
159                        'List all properties of a file or directory',
160                        { 'revision|r=i' => \$_revision } ],
161         'show-ignore' => [ \&cmd_show_ignore, "Show svn:ignore listings",
162                         { 'revision|r=i' => \$_revision
163                         } ],
164         'show-externals' => [ \&cmd_show_externals, "Show svn:externals listings",
165                         { 'revision|r=i' => \$_revision
166                         } ],
167         'multi-fetch' => [ \&cmd_multi_fetch,
168                            "Deprecated alias for $0 fetch --all",
169                            { 'revision|r=s' => \$_revision, %fc_opts } ],
170         'migrate' => [ sub { },
171                        # no-op, we automatically run this anyways,
172                        'Migrate configuration/metadata/layout from
173                         previous versions of git-svn',
174                        { 'minimize' => \$Git::SVN::Migration::_minimize,
175                          %remote_opts } ],
176         'log' => [ \&Git::SVN::Log::cmd_show_log, 'Show commit logs',
177                         { 'limit=i' => \$Git::SVN::Log::limit,
178                           'revision|r=s' => \$_revision,
179                           'verbose|v' => \$Git::SVN::Log::verbose,
180                           'incremental' => \$Git::SVN::Log::incremental,
181                           'oneline' => \$Git::SVN::Log::oneline,
182                           'show-commit' => \$Git::SVN::Log::show_commit,
183                           'non-recursive' => \$Git::SVN::Log::non_recursive,
184                           'authors-file|A=s' => \$_authors,
185                           'color' => \$Git::SVN::Log::color,
186                           'pager=s' => \$Git::SVN::Log::pager
187                         } ],
188         'find-rev' => [ \&cmd_find_rev,
189                         "Translate between SVN revision numbers and tree-ish",
190                         {} ],
191         'rebase' => [ \&cmd_rebase, "Fetch and rebase your working directory",
192                         { 'merge|m|M' => \$_merge,
193                           'verbose|v' => \$_verbose,
194                           'strategy|s=s' => \$_strategy,
195                           'local|l' => \$_local,
196                           'fetch-all|all' => \$_fetch_all,
197                           'dry-run|n' => \$_dry_run,
198                           %fc_opts } ],
199         'commit-diff' => [ \&cmd_commit_diff,
200                            'Commit a diff between two trees',
201                         { 'message|m=s' => \$_message,
202                           'file|F=s' => \$_file,
203                           'revision|r=s' => \$_revision,
204                         %cmt_opts } ],
205         'info' => [ \&cmd_info,
206                     "Show info about the latest SVN revision
207                      on the current branch",
208                     { 'url' => \$_url, } ],
209         'blame' => [ \&Git::SVN::Log::cmd_blame,
210                     "Show what revision and author last modified each line of a file",
211                     { 'git-format' => \$_git_format } ],
212 );
214 my $cmd;
215 for (my $i = 0; $i < @ARGV; $i++) {
216         if (defined $cmd{$ARGV[$i]}) {
217                 $cmd = $ARGV[$i];
218                 splice @ARGV, $i, 1;
219                 last;
220         }
221 };
223 # make sure we're always running at the top-level working directory
224 unless ($cmd && $cmd =~ /(?:clone|init|multi-init)$/) {
225         unless (-d $ENV{GIT_DIR}) {
226                 if ($git_dir_user_set) {
227                         die "GIT_DIR=$ENV{GIT_DIR} explicitly set, ",
228                             "but it is not a directory\n";
229                 }
230                 my $git_dir = delete $ENV{GIT_DIR};
231                 my $cdup = undef;
232                 git_cmd_try {
233                         $cdup = command_oneline(qw/rev-parse --show-cdup/);
234                         $git_dir = '.' unless ($cdup);
235                         chomp $cdup if ($cdup);
236                         $cdup = "." unless ($cdup && length $cdup);
237                 } "Already at toplevel, but $git_dir not found\n";
238                 chdir $cdup or die "Unable to chdir up to '$cdup'\n";
239                 unless (-d $git_dir) {
240                         die "$git_dir still not found after going to ",
241                             "'$cdup'\n";
242                 }
243                 $ENV{GIT_DIR} = $git_dir;
244         }
245         $_repository = Git->repository(Repository => $ENV{GIT_DIR});
248 my %opts = %{$cmd{$cmd}->[2]} if (defined $cmd);
250 read_repo_config(\%opts);
251 if ($cmd && ($cmd eq 'log' || $cmd eq 'blame')) {
252         Getopt::Long::Configure('pass_through');
254 my $rv = GetOptions(%opts, 'help|H|h' => \$_help, 'version|V' => \$_version,
255                     'minimize-connections' => \$Git::SVN::Migration::_minimize,
256                     'id|i=s' => \$Git::SVN::default_ref_id,
257                     'svn-remote|remote|R=s' => sub {
258                        $Git::SVN::no_reuse_existing = 1;
259                        $Git::SVN::default_repo_id = $_[1] });
260 exit 1 if (!$rv && $cmd && $cmd ne 'log');
262 usage(0) if $_help;
263 version() if $_version;
264 usage(1) unless defined $cmd;
265 load_authors() if $_authors;
267 unless ($cmd =~ /^(?:clone|init|multi-init|commit-diff)$/) {
268         Git::SVN::Migration::migration_check();
270 Git::SVN::init_vars();
271 eval {
272         Git::SVN::verify_remotes_sanity();
273         $cmd{$cmd}->[0]->(@ARGV);
274 };
275 fatal $@ if $@;
276 post_fetch_checkout();
277 exit 0;
279 ####################### primary functions ######################
280 sub usage {
281         my $exit = shift || 0;
282         my $fd = $exit ? \*STDERR : \*STDOUT;
283         print $fd <<"";
284 git-svn - bidirectional operations between a single Subversion tree and git
285 Usage: git svn <command> [options] [arguments]\n
287         print $fd "Available commands:\n" unless $cmd;
289         foreach (sort keys %cmd) {
290                 next if $cmd && $cmd ne $_;
291                 next if /^multi-/; # don't show deprecated commands
292                 print $fd '  ',pack('A17',$_),$cmd{$_}->[1],"\n";
293                 foreach (sort keys %{$cmd{$_}->[2]}) {
294                         # mixed-case options are for .git/config only
295                         next if /[A-Z]/ && /^[a-z]+$/i;
296                         # prints out arguments as they should be passed:
297                         my $x = s#[:=]s$## ? '<arg>' : s#[:=]i$## ? '<num>' : '';
298                         print $fd ' ' x 21, join(', ', map { length $_ > 1 ?
299                                                         "--$_" : "-$_" }
300                                                 split /\|/,$_)," $x\n";
301                 }
302         }
303         print $fd <<"";
304 \nGIT_SVN_ID may be set in the environment or via the --id/-i switch to an
305 arbitrary identifier if you're tracking multiple SVN branches/repositories in
306 one git repository and want to keep them separate.  See git-svn(1) for more
307 information.
309         exit $exit;
312 sub version {
313         print "git-svn version $VERSION (svn $SVN::Core::VERSION)\n";
314         exit 0;
317 sub do_git_init_db {
318         unless (-d $ENV{GIT_DIR}) {
319                 my @init_db = ('init');
320                 push @init_db, "--template=$_template" if defined $_template;
321                 if (defined $_shared) {
322                         if ($_shared =~ /[a-z]/) {
323                                 push @init_db, "--shared=$_shared";
324                         } else {
325                                 push @init_db, "--shared";
326                         }
327                 }
328                 command_noisy(@init_db);
329                 $_repository = Git->repository(Repository => ".git");
330         }
331         my $set;
332         my $pfx = "svn-remote.$Git::SVN::default_repo_id";
333         foreach my $i (keys %icv) {
334                 die "'$set' and '$i' cannot both be set\n" if $set;
335                 next unless defined $icv{$i};
336                 command_noisy('config', "$pfx.$i", $icv{$i});
337                 $set = $i;
338         }
339         my $ignore_regex = \$SVN::Git::Fetcher::_ignore_regex;
340         command_noisy('config', "$pfx.ignore-paths", $$ignore_regex)
341                 if defined $$ignore_regex;
344 sub init_subdir {
345         my $repo_path = shift or return;
346         mkpath([$repo_path]) unless -d $repo_path;
347         chdir $repo_path or die "Couldn't chdir to $repo_path: $!\n";
348         $ENV{GIT_DIR} = '.git';
349         $_repository = Git->repository(Repository => $ENV{GIT_DIR});
352 sub cmd_clone {
353         my ($url, $path) = @_;
354         if (!defined $path &&
355             (defined $_trunk || defined $_branches || defined $_tags ||
356              defined $_stdlayout) &&
357             $url !~ m#^[a-z\+]+://#) {
358                 $path = $url;
359         }
360         $path = basename($url) if !defined $path || !length $path;
361         cmd_init($url, $path);
362         Git::SVN::fetch_all($Git::SVN::default_repo_id);
365 sub cmd_init {
366         if (defined $_stdlayout) {
367                 $_trunk = 'trunk' if (!defined $_trunk);
368                 $_tags = 'tags' if (!defined $_tags);
369                 $_branches = 'branches' if (!defined $_branches);
370         }
371         if (defined $_trunk || defined $_branches || defined $_tags) {
372                 return cmd_multi_init(@_);
373         }
374         my $url = shift or die "SVN repository location required ",
375                                "as a command-line argument\n";
376         init_subdir(@_);
377         do_git_init_db();
379         Git::SVN->init($url);
382 sub cmd_fetch {
383         if (grep /^\d+=./, @_) {
384                 die "'<rev>=<commit>' fetch arguments are ",
385                     "no longer supported.\n";
386         }
387         my ($remote) = @_;
388         if (@_ > 1) {
389                 die "Usage: $0 fetch [--all] [--parent] [svn-remote]\n";
390         }
391         if ($_fetch_parent) {
392                 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
393                 unless ($gs) {
394                         die "Unable to determine upstream SVN information from ",
395                             "working tree history\n";
396                 }
397                 # just fetch, don't checkout.
398                 $_no_checkout = 'true';
399                 $_fetch_all ? $gs->fetch_all : $gs->fetch;
400         } elsif ($_fetch_all) {
401                 cmd_multi_fetch();
402         } else {
403                 $remote ||= $Git::SVN::default_repo_id;
404                 Git::SVN::fetch_all($remote, Git::SVN::read_all_remotes());
405         }
408 sub cmd_set_tree {
409         my (@commits) = @_;
410         if ($_stdin || !@commits) {
411                 print "Reading from stdin...\n";
412                 @commits = ();
413                 while (<STDIN>) {
414                         if (/\b($sha1_short)\b/o) {
415                                 unshift @commits, $1;
416                         }
417                 }
418         }
419         my @revs;
420         foreach my $c (@commits) {
421                 my @tmp = command('rev-parse',$c);
422                 if (scalar @tmp == 1) {
423                         push @revs, $tmp[0];
424                 } elsif (scalar @tmp > 1) {
425                         push @revs, reverse(command('rev-list',@tmp));
426                 } else {
427                         fatal "Failed to rev-parse $c";
428                 }
429         }
430         my $gs = Git::SVN->new;
431         my ($r_last, $cmt_last) = $gs->last_rev_commit;
432         $gs->fetch;
433         if (defined $gs->{last_rev} && $r_last != $gs->{last_rev}) {
434                 fatal "There are new revisions that were fetched ",
435                       "and need to be merged (or acknowledged) ",
436                       "before committing.\nlast rev: $r_last\n",
437                       " current: $gs->{last_rev}";
438         }
439         $gs->set_tree($_) foreach @revs;
440         print "Done committing ",scalar @revs," revisions to SVN\n";
441         unlink $gs->{index};
444 sub cmd_dcommit {
445         my $head = shift;
446         git_cmd_try { command_oneline(qw/diff-index --quiet HEAD/) }
447                 'Cannot dcommit with a dirty index.  Commit your changes first, '
448                 . "or stash them with `git stash'.\n";
449         $head ||= 'HEAD';
450         my @refs;
451         my ($url, $rev, $uuid, $gs) = working_head_info($head, \@refs);
452         unless ($gs) {
453                 die "Unable to determine upstream SVN information from ",
454                     "$head history.\nPerhaps the repository is empty.";
455         }
457         if (defined $_commit_url) {
458                 $url = $_commit_url;
459         } else {
460                 $url = eval { command_oneline('config', '--get',
461                               "svn-remote.$gs->{repo_id}.commiturl") };
462                 if (!$url) {
463                         $url = $gs->full_url
464                 }
465         }
467         my $last_rev = $_revision if defined $_revision;
468         if ($url) {
469                 print "Committing to $url ...\n";
470         }
471         my ($linear_refs, $parents) = linearize_history($gs, \@refs);
472         if ($_no_rebase && scalar(@$linear_refs) > 1) {
473                 warn "Attempting to commit more than one change while ",
474                      "--no-rebase is enabled.\n",
475                      "If these changes depend on each other, re-running ",
476                      "without --no-rebase may be required."
477         }
478         my $expect_url = $url;
479         Git::SVN::remove_username($expect_url);
480         while (1) {
481                 my $d = shift @$linear_refs or last;
482                 unless (defined $last_rev) {
483                         (undef, $last_rev, undef) = cmt_metadata("$d~1");
484                         unless (defined $last_rev) {
485                                 fatal "Unable to extract revision information ",
486                                       "from commit $d~1";
487                         }
488                 }
489                 if ($_dry_run) {
490                         print "diff-tree $d~1 $d\n";
491                 } else {
492                         my $cmt_rev;
493                         my %ed_opts = ( r => $last_rev,
494                                         log => get_commit_entry($d)->{log},
495                                         ra => Git::SVN::Ra->new($url),
496                                         config => SVN::Core::config_get_config(
497                                                 $Git::SVN::Ra::config_dir
498                                         ),
499                                         tree_a => "$d~1",
500                                         tree_b => $d,
501                                         editor_cb => sub {
502                                                print "Committed r$_[0]\n";
503                                                $cmt_rev = $_[0];
504                                         },
505                                         svn_path => '');
506                         if (!SVN::Git::Editor->new(\%ed_opts)->apply_diff) {
507                                 print "No changes\n$d~1 == $d\n";
508                         } elsif ($parents->{$d} && @{$parents->{$d}}) {
509                                 $gs->{inject_parents_dcommit}->{$cmt_rev} =
510                                                                $parents->{$d};
511                         }
512                         $_fetch_all ? $gs->fetch_all : $gs->fetch;
513                         $last_rev = $cmt_rev;
514                         next if $_no_rebase;
516                         # we always want to rebase against the current HEAD,
517                         # not any head that was passed to us
518                         my @diff = command('diff-tree', $d,
519                                            $gs->refname, '--');
520                         my @finish;
521                         if (@diff) {
522                                 @finish = rebase_cmd();
523                                 print STDERR "W: $d and ", $gs->refname,
524                                              " differ, using @finish:\n",
525                                              join("\n", @diff), "\n";
526                         } else {
527                                 print "No changes between current HEAD and ",
528                                       $gs->refname,
529                                       "\nResetting to the latest ",
530                                       $gs->refname, "\n";
531                                 @finish = qw/reset --mixed/;
532                         }
533                         command_noisy(@finish, $gs->refname);
534                         if (@diff) {
535                                 @refs = ();
536                                 my ($url_, $rev_, $uuid_, $gs_) =
537                                               working_head_info($head, \@refs);
538                                 my ($linear_refs_, $parents_) =
539                                               linearize_history($gs_, \@refs);
540                                 if (scalar(@$linear_refs) !=
541                                     scalar(@$linear_refs_)) {
542                                         fatal "# of revisions changed ",
543                                           "\nbefore:\n",
544                                           join("\n", @$linear_refs),
545                                           "\n\nafter:\n",
546                                           join("\n", @$linear_refs_), "\n",
547                                           'If you are attempting to commit ',
548                                           "merges, try running:\n\t",
549                                           'git rebase --interactive',
550                                           '--preserve-merges ',
551                                           $gs->refname,
552                                           "\nBefore dcommitting";
553                                 }
554                                 if ($url_ ne $expect_url) {
555                                         fatal "URL mismatch after rebase: ",
556                                               "$url_ != $expect_url";
557                                 }
558                                 if ($uuid_ ne $uuid) {
559                                         fatal "uuid mismatch after rebase: ",
560                                               "$uuid_ != $uuid";
561                                 }
562                                 # remap parents
563                                 my (%p, @l, $i);
564                                 for ($i = 0; $i < scalar @$linear_refs; $i++) {
565                                         my $new = $linear_refs_->[$i] or next;
566                                         $p{$new} =
567                                                 $parents->{$linear_refs->[$i]};
568                                         push @l, $new;
569                                 }
570                                 $parents = \%p;
571                                 $linear_refs = \@l;
572                         }
573                 }
574         }
575         unlink $gs->{index};
578 sub cmd_branch {
579         my ($branch_name, $head) = @_;
581         unless (defined $branch_name && length $branch_name) {
582                 die(($_tag ? "tag" : "branch") . " name required\n");
583         }
584         $head ||= 'HEAD';
586         my ($src, $rev, undef, $gs) = working_head_info($head);
588         my $remote = Git::SVN::read_all_remotes()->{$gs->{repo_id}};
589         my $glob = $remote->{ $_tag ? 'tags' : 'branches' };
590         my ($lft, $rgt) = @{ $glob->{path} }{qw/left right/};
591         my $dst = join '/', $remote->{url}, $lft, $branch_name, ($rgt || ());
593         my $ctx = SVN::Client->new(
594                 auth    => Git::SVN::Ra::_auth_providers(),
595                 log_msg => sub {
596                         ${ $_[0] } = defined $_message
597                                 ? $_message
598                                 : 'Create ' . ($_tag ? 'tag ' : 'branch ' )
599                                 . $branch_name;
600                 },
601         );
603         eval {
604                 $ctx->ls($dst, 'HEAD', 0);
605         } and die "branch ${branch_name} already exists\n";
607         print "Copying ${src} at r${rev} to ${dst}...\n";
608         $ctx->copy($src, $rev, $dst)
609                 unless $_dry_run;
611         $gs->fetch_all;
614 sub cmd_find_rev {
615         my $revision_or_hash = shift or die "SVN or git revision required ",
616                                             "as a command-line argument\n";
617         my $result;
618         if ($revision_or_hash =~ /^r\d+$/) {
619                 my $head = shift;
620                 $head ||= 'HEAD';
621                 my @refs;
622                 my (undef, undef, $uuid, $gs) = working_head_info($head, \@refs);
623                 unless ($gs) {
624                         die "Unable to determine upstream SVN information from ",
625                             "$head history\n";
626                 }
627                 my $desired_revision = substr($revision_or_hash, 1);
628                 $result = $gs->rev_map_get($desired_revision, $uuid);
629         } else {
630                 my (undef, $rev, undef) = cmt_metadata($revision_or_hash);
631                 $result = $rev;
632         }
633         print "$result\n" if $result;
636 sub cmd_rebase {
637         command_noisy(qw/update-index --refresh/);
638         my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
639         unless ($gs) {
640                 die "Unable to determine upstream SVN information from ",
641                     "working tree history\n";
642         }
643         if ($_dry_run) {
644                 print "Remote Branch: " . $gs->refname . "\n";
645                 print "SVN URL: " . $url . "\n";
646                 return;
647         }
648         if (command(qw/diff-index HEAD --/)) {
649                 print STDERR "Cannot rebase with uncommited changes:\n";
650                 command_noisy('status');
651                 exit 1;
652         }
653         unless ($_local) {
654                 # rebase will checkout for us, so no need to do it explicitly
655                 $_no_checkout = 'true';
656                 $_fetch_all ? $gs->fetch_all : $gs->fetch;
657         }
658         command_noisy(rebase_cmd(), $gs->refname);
661 sub cmd_show_ignore {
662         my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
663         $gs ||= Git::SVN->new;
664         my $r = (defined $_revision ? $_revision : $gs->ra->get_latest_revnum);
665         $gs->prop_walk($gs->{path}, $r, sub {
666                 my ($gs, $path, $props) = @_;
667                 print STDOUT "\n# $path\n";
668                 my $s = $props->{'svn:ignore'} or return;
669                 $s =~ s/[\r\n]+/\n/g;
670                 chomp $s;
671                 $s =~ s#^#$path#gm;
672                 print STDOUT "$s\n";
673         });
676 sub cmd_show_externals {
677         my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
678         $gs ||= Git::SVN->new;
679         my $r = (defined $_revision ? $_revision : $gs->ra->get_latest_revnum);
680         $gs->prop_walk($gs->{path}, $r, sub {
681                 my ($gs, $path, $props) = @_;
682                 print STDOUT "\n# $path\n";
683                 my $s = $props->{'svn:externals'} or return;
684                 $s =~ s/[\r\n]+/\n/g;
685                 chomp $s;
686                 $s =~ s#^#$path#gm;
687                 print STDOUT "$s\n";
688         });
691 sub cmd_create_ignore {
692         my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
693         $gs ||= Git::SVN->new;
694         my $r = (defined $_revision ? $_revision : $gs->ra->get_latest_revnum);
695         $gs->prop_walk($gs->{path}, $r, sub {
696                 my ($gs, $path, $props) = @_;
697                 # $path is of the form /path/to/dir/
698                 $path = '.' . $path;
699                 # SVN can have attributes on empty directories,
700                 # which git won't track
701                 mkpath([$path]) unless -d $path;
702                 my $ignore = $path . '.gitignore';
703                 my $s = $props->{'svn:ignore'} or return;
704                 open(GITIGNORE, '>', $ignore)
705                   or fatal("Failed to open `$ignore' for writing: $!");
706                 $s =~ s/[\r\n]+/\n/g;
707                 chomp $s;
708                 # Prefix all patterns so that the ignore doesn't apply
709                 # to sub-directories.
710                 $s =~ s#^#/#gm;
711                 print GITIGNORE "$s\n";
712                 close(GITIGNORE)
713                   or fatal("Failed to close `$ignore': $!");
714                 command_noisy('add', '-f', $ignore);
715         });
718 sub canonicalize_path {
719         my ($path) = @_;
720         my $dot_slash_added = 0;
721         if (substr($path, 0, 1) ne "/") {
722                 $path = "./" . $path;
723                 $dot_slash_added = 1;
724         }
725         # File::Spec->canonpath doesn't collapse x/../y into y (for a
726         # good reason), so let's do this manually.
727         $path =~ s#/+#/#g;
728         $path =~ s#/\.(?:/|$)#/#g;
729         $path =~ s#/[^/]+/\.\.##g;
730         $path =~ s#/$##g;
731         $path =~ s#^\./## if $dot_slash_added;
732         $path =~ s#^/##;
733         $path =~ s#^\.$##;
734         return $path;
737 # get_svnprops(PATH)
738 # ------------------
739 # Helper for cmd_propget and cmd_proplist below.
740 sub get_svnprops {
741         my $path = shift;
742         my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
743         $gs ||= Git::SVN->new;
745         # prefix THE PATH by the sub-directory from which the user
746         # invoked us.
747         $path = $cmd_dir_prefix . $path;
748         fatal("No such file or directory: $path") unless -e $path;
749         my $is_dir = -d $path ? 1 : 0;
750         $path = $gs->{path} . '/' . $path;
752         # canonicalize the path (otherwise libsvn will abort or fail to
753         # find the file)
754         $path = canonicalize_path($path);
756         my $r = (defined $_revision ? $_revision : $gs->ra->get_latest_revnum);
757         my $props;
758         if ($is_dir) {
759                 (undef, undef, $props) = $gs->ra->get_dir($path, $r);
760         }
761         else {
762                 (undef, $props) = $gs->ra->get_file($path, $r, undef);
763         }
764         return $props;
767 # cmd_propget (PROP, PATH)
768 # ------------------------
769 # Print the SVN property PROP for PATH.
770 sub cmd_propget {
771         my ($prop, $path) = @_;
772         $path = '.' if not defined $path;
773         usage(1) if not defined $prop;
774         my $props = get_svnprops($path);
775         if (not defined $props->{$prop}) {
776                 fatal("`$path' does not have a `$prop' SVN property.");
777         }
778         print $props->{$prop} . "\n";
781 # cmd_proplist (PATH)
782 # -------------------
783 # Print the list of SVN properties for PATH.
784 sub cmd_proplist {
785         my $path = shift;
786         $path = '.' if not defined $path;
787         my $props = get_svnprops($path);
788         print "Properties on '$path':\n";
789         foreach (sort keys %{$props}) {
790                 print "  $_\n";
791         }
794 sub cmd_multi_init {
795         my $url = shift;
796         unless (defined $_trunk || defined $_branches || defined $_tags) {
797                 usage(1);
798         }
800         # there are currently some bugs that prevent multi-init/multi-fetch
801         # setups from working well without this.
802         $Git::SVN::_minimize_url = 1;
804         $_prefix = '' unless defined $_prefix;
805         if (defined $url) {
806                 $url =~ s#/+$##;
807                 init_subdir(@_);
808         }
809         do_git_init_db();
810         if (defined $_trunk) {
811                 my $trunk_ref = $_prefix . 'trunk';
812                 # try both old-style and new-style lookups:
813                 my $gs_trunk = eval { Git::SVN->new($trunk_ref) };
814                 unless ($gs_trunk) {
815                         my ($trunk_url, $trunk_path) =
816                                               complete_svn_url($url, $_trunk);
817                         $gs_trunk = Git::SVN->init($trunk_url, $trunk_path,
818                                                    undef, $trunk_ref);
819                 }
820         }
821         return unless defined $_branches || defined $_tags;
822         my $ra = $url ? Git::SVN::Ra->new($url) : undef;
823         complete_url_ls_init($ra, $_branches, '--branches/-b', $_prefix);
824         complete_url_ls_init($ra, $_tags, '--tags/-t', $_prefix . 'tags/');
827 sub cmd_multi_fetch {
828         my $remotes = Git::SVN::read_all_remotes();
829         foreach my $repo_id (sort keys %$remotes) {
830                 if ($remotes->{$repo_id}->{url}) {
831                         Git::SVN::fetch_all($repo_id, $remotes);
832                 }
833         }
836 # this command is special because it requires no metadata
837 sub cmd_commit_diff {
838         my ($ta, $tb, $url) = @_;
839         my $usage = "Usage: $0 commit-diff -r<revision> ".
840                     "<tree-ish> <tree-ish> [<URL>]";
841         fatal($usage) if (!defined $ta || !defined $tb);
842         my $svn_path = '';
843         if (!defined $url) {
844                 my $gs = eval { Git::SVN->new };
845                 if (!$gs) {
846                         fatal("Needed URL or usable git-svn --id in ",
847                               "the command-line\n", $usage);
848                 }
849                 $url = $gs->{url};
850                 $svn_path = $gs->{path};
851         }
852         unless (defined $_revision) {
853                 fatal("-r|--revision is a required argument\n", $usage);
854         }
855         if (defined $_message && defined $_file) {
856                 fatal("Both --message/-m and --file/-F specified ",
857                       "for the commit message.\n",
858                       "I have no idea what you mean");
859         }
860         if (defined $_file) {
861                 $_message = file_to_s($_file);
862         } else {
863                 $_message ||= get_commit_entry($tb)->{log};
864         }
865         my $ra ||= Git::SVN::Ra->new($url);
866         my $r = $_revision;
867         if ($r eq 'HEAD') {
868                 $r = $ra->get_latest_revnum;
869         } elsif ($r !~ /^\d+$/) {
870                 die "revision argument: $r not understood by git-svn\n";
871         }
872         my %ed_opts = ( r => $r,
873                         log => $_message,
874                         ra => $ra,
875                         tree_a => $ta,
876                         tree_b => $tb,
877                         editor_cb => sub { print "Committed r$_[0]\n" },
878                         svn_path => $svn_path );
879         if (!SVN::Git::Editor->new(\%ed_opts)->apply_diff) {
880                 print "No changes\n$ta == $tb\n";
881         }
884 sub escape_uri_only {
885         my ($uri) = @_;
886         my @tmp;
887         foreach (split m{/}, $uri) {
888                 s/([^~\w.%+-]|%(?![a-fA-F0-9]{2}))/sprintf("%%%02X",ord($1))/eg;
889                 push @tmp, $_;
890         }
891         join('/', @tmp);
894 sub escape_url {
895         my ($url) = @_;
896         if ($url =~ m#^([^:]+)://([^/]*)(.*)$#) {
897                 my ($scheme, $domain, $uri) = ($1, $2, escape_uri_only($3));
898                 $url = "$scheme://$domain$uri";
899         }
900         $url;
903 sub cmd_info {
904         my $path = canonicalize_path(defined($_[0]) ? $_[0] : ".");
905         my $fullpath = canonicalize_path($cmd_dir_prefix . $path);
906         if (exists $_[1]) {
907                 die "Too many arguments specified\n";
908         }
910         my ($file_type, $diff_status) = find_file_type_and_diff_status($path);
912         if (!$file_type && !$diff_status) {
913                 print STDERR "svn: '$path' is not under version control\n";
914                 exit 1;
915         }
917         my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
918         unless ($gs) {
919                 die "Unable to determine upstream SVN information from ",
920                     "working tree history\n";
921         }
923         # canonicalize_path() will return "" to make libsvn 1.5.x happy,
924         $path = "." if $path eq "";
926         my $full_url = $url . ($fullpath eq "" ? "" : "/$fullpath");
928         if ($_url) {
929                 print escape_url($full_url), "\n";
930                 return;
931         }
933         my $result = "Path: $path\n";
934         $result .= "Name: " . basename($path) . "\n" if $file_type ne "dir";
935         $result .= "URL: " . escape_url($full_url) . "\n";
937         eval {
938                 my $repos_root = $gs->repos_root;
939                 Git::SVN::remove_username($repos_root);
940                 $result .= "Repository Root: " . escape_url($repos_root) . "\n";
941         };
942         if ($@) {
943                 $result .= "Repository Root: (offline)\n";
944         }
945         $result .= "Repository UUID: $uuid\n" unless $diff_status eq "A" &&
946                 ($SVN::Core::VERSION le '1.5.4' || $file_type ne "dir");
947         $result .= "Revision: " . ($diff_status eq "A" ? 0 : $rev) . "\n";
949         $result .= "Node Kind: " .
950                    ($file_type eq "dir" ? "directory" : "file") . "\n";
952         my $schedule = $diff_status eq "A"
953                        ? "add"
954                        : ($diff_status eq "D" ? "delete" : "normal");
955         $result .= "Schedule: $schedule\n";
957         if ($diff_status eq "A") {
958                 print $result, "\n";
959                 return;
960         }
962         my ($lc_author, $lc_rev, $lc_date_utc);
963         my @args = Git::SVN::Log::git_svn_log_cmd($rev, $rev, "--", $fullpath);
964         my $log = command_output_pipe(@args);
965         my $esc_color = qr/(?:\033\[(?:(?:\d+;)*\d*)?m)*/;
966         while (<$log>) {
967                 if (/^${esc_color}author (.+) <[^>]+> (\d+) ([\-\+]?\d+)$/o) {
968                         $lc_author = $1;
969                         $lc_date_utc = Git::SVN::Log::parse_git_date($2, $3);
970                 } elsif (/^${esc_color}    (git-svn-id:.+)$/o) {
971                         (undef, $lc_rev, undef) = ::extract_metadata($1);
972                 }
973         }
974         close $log;
976         Git::SVN::Log::set_local_timezone();
978         $result .= "Last Changed Author: $lc_author\n";
979         $result .= "Last Changed Rev: $lc_rev\n";
980         $result .= "Last Changed Date: " .
981                    Git::SVN::Log::format_svn_date($lc_date_utc) . "\n";
983         if ($file_type ne "dir") {
984                 my $text_last_updated_date =
985                     ($diff_status eq "D" ? $lc_date_utc : (stat $path)[9]);
986                 $result .=
987                     "Text Last Updated: " .
988                     Git::SVN::Log::format_svn_date($text_last_updated_date) .
989                     "\n";
990                 my $checksum;
991                 if ($diff_status eq "D") {
992                         my ($fh, $ctx) =
993                             command_output_pipe(qw(cat-file blob), "HEAD:$path");
994                         if ($file_type eq "link") {
995                                 my $file_name = <$fh>;
996                                 $checksum = md5sum("link $file_name");
997                         } else {
998                                 $checksum = md5sum($fh);
999                         }
1000                         command_close_pipe($fh, $ctx);
1001                 } elsif ($file_type eq "link") {
1002                         my $file_name =
1003                             command(qw(cat-file blob), "HEAD:$path");
1004                         $checksum =
1005                             md5sum("link " . $file_name);
1006                 } else {
1007                         open FILE, "<", $path or die $!;
1008                         $checksum = md5sum(\*FILE);
1009                         close FILE or die $!;
1010                 }
1011                 $result .= "Checksum: " . $checksum . "\n";
1012         }
1014         print $result, "\n";
1017 ########################### utility functions #########################
1019 sub rebase_cmd {
1020         my @cmd = qw/rebase/;
1021         push @cmd, '-v' if $_verbose;
1022         push @cmd, qw/--merge/ if $_merge;
1023         push @cmd, "--strategy=$_strategy" if $_strategy;
1024         @cmd;
1027 sub post_fetch_checkout {
1028         return if $_no_checkout;
1029         my $gs = $Git::SVN::_head or return;
1030         return if verify_ref('refs/heads/master^0');
1032         my $valid_head = verify_ref('HEAD^0');
1033         command_noisy(qw(update-ref refs/heads/master), $gs->refname);
1034         return if ($valid_head || !verify_ref('HEAD^0'));
1036         return if $ENV{GIT_DIR} !~ m#^(?:.*/)?\.git$#;
1037         my $index = $ENV{GIT_INDEX_FILE} || "$ENV{GIT_DIR}/index";
1038         return if -f $index;
1040         return if command_oneline(qw/rev-parse --is-inside-work-tree/) eq 'false';
1041         return if command_oneline(qw/rev-parse --is-inside-git-dir/) eq 'true';
1042         command_noisy(qw/read-tree -m -u -v HEAD HEAD/);
1043         print STDERR "Checked out HEAD:\n  ",
1044                      $gs->full_url, " r", $gs->last_rev, "\n";
1047 sub complete_svn_url {
1048         my ($url, $path) = @_;
1049         $path =~ s#/+$##;
1050         if ($path !~ m#^[a-z\+]+://#) {
1051                 if (!defined $url || $url !~ m#^[a-z\+]+://#) {
1052                         fatal("E: '$path' is not a complete URL ",
1053                               "and a separate URL is not specified");
1054                 }
1055                 return ($url, $path);
1056         }
1057         return ($path, '');
1060 sub complete_url_ls_init {
1061         my ($ra, $repo_path, $switch, $pfx) = @_;
1062         unless ($repo_path) {
1063                 print STDERR "W: $switch not specified\n";
1064                 return;
1065         }
1066         $repo_path =~ s#/+$##;
1067         if ($repo_path =~ m#^[a-z\+]+://#) {
1068                 $ra = Git::SVN::Ra->new($repo_path);
1069                 $repo_path = '';
1070         } else {
1071                 $repo_path =~ s#^/+##;
1072                 unless ($ra) {
1073                         fatal("E: '$repo_path' is not a complete URL ",
1074                               "and a separate URL is not specified");
1075                 }
1076         }
1077         my $url = $ra->{url};
1078         my $gs = Git::SVN->init($url, undef, undef, undef, 1);
1079         my $k = "svn-remote.$gs->{repo_id}.url";
1080         my $orig_url = eval { command_oneline(qw/config --get/, $k) };
1081         if ($orig_url && ($orig_url ne $gs->{url})) {
1082                 die "$k already set: $orig_url\n",
1083                     "wanted to set to: $gs->{url}\n";
1084         }
1085         command_oneline('config', $k, $gs->{url}) unless $orig_url;
1086         my $remote_path = "$ra->{svn_path}/$repo_path";
1087         $remote_path =~ s#/+#/#g;
1088         $remote_path =~ s#^/##g;
1089         $remote_path .= "/*" if $remote_path !~ /\*/;
1090         my ($n) = ($switch =~ /^--(\w+)/);
1091         if (length $pfx && $pfx !~ m#/$#) {
1092                 die "--prefix='$pfx' must have a trailing slash '/'\n";
1093         }
1094         command_noisy('config',
1095                       "svn-remote.$gs->{repo_id}.$n",
1096                       "$remote_path:refs/remotes/$pfx*" .
1097                         ('/*' x (($remote_path =~ tr/*/*/) - 1)) );
1100 sub verify_ref {
1101         my ($ref) = @_;
1102         eval { command_oneline([ 'rev-parse', '--verify', $ref ],
1103                                { STDERR => 0 }); };
1106 sub get_tree_from_treeish {
1107         my ($treeish) = @_;
1108         # $treeish can be a symbolic ref, too:
1109         my $type = command_oneline(qw/cat-file -t/, $treeish);
1110         my $expected;
1111         while ($type eq 'tag') {
1112                 ($treeish, $type) = command(qw/cat-file tag/, $treeish);
1113         }
1114         if ($type eq 'commit') {
1115                 $expected = (grep /^tree /, command(qw/cat-file commit/,
1116                                                     $treeish))[0];
1117                 ($expected) = ($expected =~ /^tree ($sha1)$/o);
1118                 die "Unable to get tree from $treeish\n" unless $expected;
1119         } elsif ($type eq 'tree') {
1120                 $expected = $treeish;
1121         } else {
1122                 die "$treeish is a $type, expected tree, tag or commit\n";
1123         }
1124         return $expected;
1127 sub get_commit_entry {
1128         my ($treeish) = shift;
1129         my %log_entry = ( log => '', tree => get_tree_from_treeish($treeish) );
1130         my $commit_editmsg = "$ENV{GIT_DIR}/COMMIT_EDITMSG";
1131         my $commit_msg = "$ENV{GIT_DIR}/COMMIT_MSG";
1132         open my $log_fh, '>', $commit_editmsg or croak $!;
1134         my $type = command_oneline(qw/cat-file -t/, $treeish);
1135         if ($type eq 'commit' || $type eq 'tag') {
1136                 my ($msg_fh, $ctx) = command_output_pipe('cat-file',
1137                                                          $type, $treeish);
1138                 my $in_msg = 0;
1139                 my $author;
1140                 my $saw_from = 0;
1141                 my $msgbuf = "";
1142                 while (<$msg_fh>) {
1143                         if (!$in_msg) {
1144                                 $in_msg = 1 if (/^\s*$/);
1145                                 $author = $1 if (/^author (.*>)/);
1146                         } elsif (/^git-svn-id: /) {
1147                                 # skip this for now, we regenerate the
1148                                 # correct one on re-fetch anyways
1149                                 # TODO: set *:merge properties or like...
1150                         } else {
1151                                 if (/^From:/ || /^Signed-off-by:/) {
1152                                         $saw_from = 1;
1153                                 }
1154                                 $msgbuf .= $_;
1155                         }
1156                 }
1157                 $msgbuf =~ s/\s+$//s;
1158                 if ($Git::SVN::_add_author_from && defined($author)
1159                     && !$saw_from) {
1160                         $msgbuf .= "\n\nFrom: $author";
1161                 }
1162                 print $log_fh $msgbuf or croak $!;
1163                 command_close_pipe($msg_fh, $ctx);
1164         }
1165         close $log_fh or croak $!;
1167         if ($_edit || ($type eq 'tree')) {
1168                 my $editor = $ENV{VISUAL} || $ENV{EDITOR} || 'vi';
1169                 # TODO: strip out spaces, comments, like git-commit.sh
1170                 system($editor, $commit_editmsg);
1171         }
1172         rename $commit_editmsg, $commit_msg or croak $!;
1173         {
1174                 # SVN requires messages to be UTF-8 when entering the repo
1175                 local $/;
1176                 open $log_fh, '<', $commit_msg or croak $!;
1177                 binmode $log_fh;
1178                 chomp($log_entry{log} = <$log_fh>);
1180                 if (my $enc = Git::config('i18n.commitencoding')) {
1181                         require Encode;
1182                         Encode::from_to($log_entry{log}, $enc, 'UTF-8');
1183                 }
1184                 close $log_fh or croak $!;
1185         }
1186         unlink $commit_msg;
1187         \%log_entry;
1190 sub s_to_file {
1191         my ($str, $file, $mode) = @_;
1192         open my $fd,'>',$file or croak $!;
1193         print $fd $str,"\n" or croak $!;
1194         close $fd or croak $!;
1195         chmod ($mode &~ umask, $file) if (defined $mode);
1198 sub file_to_s {
1199         my $file = shift;
1200         open my $fd,'<',$file or croak "$!: file: $file\n";
1201         local $/;
1202         my $ret = <$fd>;
1203         close $fd or croak $!;
1204         $ret =~ s/\s*$//s;
1205         return $ret;
1208 # '<svn username> = real-name <email address>' mapping based on git-svnimport:
1209 sub load_authors {
1210         open my $authors, '<', $_authors or die "Can't open $_authors $!\n";
1211         my $log = $cmd eq 'log';
1212         while (<$authors>) {
1213                 chomp;
1214                 next unless /^(.+?|\(no author\))\s*=\s*(.+?)\s*<(.+)>\s*$/;
1215                 my ($user, $name, $email) = ($1, $2, $3);
1216                 if ($log) {
1217                         $Git::SVN::Log::rusers{"$name <$email>"} = $user;
1218                 } else {
1219                         $users{$user} = [$name, $email];
1220                 }
1221         }
1222         close $authors or croak $!;
1225 # convert GetOpt::Long specs for use by git-config
1226 sub read_repo_config {
1227         return unless -d $ENV{GIT_DIR};
1228         my $opts = shift;
1229         my @config_only;
1230         foreach my $o (keys %$opts) {
1231                 # if we have mixedCase and a long option-only, then
1232                 # it's a config-only variable that we don't need for
1233                 # the command-line.
1234                 push @config_only, $o if ($o =~ /[A-Z]/ && $o =~ /^[a-z]+$/i);
1235                 my $v = $opts->{$o};
1236                 my ($key) = ($o =~ /^([a-zA-Z\-]+)/);
1237                 $key =~ s/-//g;
1238                 my $arg = 'git config';
1239                 $arg .= ' --int' if ($o =~ /[:=]i$/);
1240                 $arg .= ' --bool' if ($o !~ /[:=][sfi]$/);
1241                 if (ref $v eq 'ARRAY') {
1242                         chomp(my @tmp = `$arg --get-all svn.$key`);
1243                         @$v = @tmp if @tmp;
1244                 } else {
1245                         chomp(my $tmp = `$arg --get svn.$key`);
1246                         if ($tmp && !($arg =~ / --bool/ && $tmp eq 'false')) {
1247                                 $$v = $tmp;
1248                         }
1249                 }
1250         }
1251         delete @$opts{@config_only} if @config_only;
1254 sub extract_metadata {
1255         my $id = shift or return (undef, undef, undef);
1256         my ($url, $rev, $uuid) = ($id =~ /^\s*git-svn-id:\s+(.*)\@(\d+)
1257                                                         \s([a-f\d\-]+)$/x);
1258         if (!defined $rev || !$uuid || !$url) {
1259                 # some of the original repositories I made had
1260                 # identifiers like this:
1261                 ($rev, $uuid) = ($id =~/^\s*git-svn-id:\s(\d+)\@([a-f\d\-]+)/);
1262         }
1263         return ($url, $rev, $uuid);
1266 sub cmt_metadata {
1267         return extract_metadata((grep(/^git-svn-id: /,
1268                 command(qw/cat-file commit/, shift)))[-1]);
1271 sub cmt_sha2rev_batch {
1272         my %s2r;
1273         my ($pid, $in, $out, $ctx) = command_bidi_pipe(qw/cat-file --batch/);
1274         my $list = shift;
1276         foreach my $sha (@{$list}) {
1277                 my $first = 1;
1278                 my $size = 0;
1279                 print $out $sha, "\n";
1281                 while (my $line = <$in>) {
1282                         if ($first && $line =~ /^[[:xdigit:]]{40}\smissing$/) {
1283                                 last;
1284                         } elsif ($first &&
1285                                $line =~ /^[[:xdigit:]]{40}\scommit\s(\d+)$/) {
1286                                 $first = 0;
1287                                 $size = $1;
1288                                 next;
1289                         } elsif ($line =~ /^(git-svn-id: )/) {
1290                                 my (undef, $rev, undef) =
1291                                                       extract_metadata($line);
1292                                 $s2r{$sha} = $rev;
1293                         }
1295                         $size -= length($line);
1296                         last if ($size == 0);
1297                 }
1298         }
1300         command_close_bidi_pipe($pid, $in, $out, $ctx);
1302         return \%s2r;
1305 sub working_head_info {
1306         my ($head, $refs) = @_;
1307         my @args = ('log', '--no-color', '--first-parent', '--pretty=medium');
1308         my ($fh, $ctx) = command_output_pipe(@args, $head);
1309         my $hash;
1310         my %max;
1311         while (<$fh>) {
1312                 if ( m{^commit ($::sha1)$} ) {
1313                         unshift @$refs, $hash if $hash and $refs;
1314                         $hash = $1;
1315                         next;
1316                 }
1317                 next unless s{^\s*(git-svn-id:)}{$1};
1318                 my ($url, $rev, $uuid) = extract_metadata($_);
1319                 if (defined $url && defined $rev) {
1320                         next if $max{$url} and $max{$url} < $rev;
1321                         if (my $gs = Git::SVN->find_by_url($url)) {
1322                                 my $c = $gs->rev_map_get($rev, $uuid);
1323                                 if ($c && $c eq $hash) {
1324                                         close $fh; # break the pipe
1325                                         return ($url, $rev, $uuid, $gs);
1326                                 } else {
1327                                         $max{$url} ||= $gs->rev_map_max;
1328                                 }
1329                         }
1330                 }
1331         }
1332         command_close_pipe($fh, $ctx);
1333         (undef, undef, undef, undef);
1336 sub read_commit_parents {
1337         my ($parents, $c) = @_;
1338         chomp(my $p = command_oneline(qw/rev-list --parents -1/, $c));
1339         $p =~ s/^($c)\s*// or die "rev-list --parents -1 $c failed!\n";
1340         @{$parents->{$c}} = split(/ /, $p);
1343 sub linearize_history {
1344         my ($gs, $refs) = @_;
1345         my %parents;
1346         foreach my $c (@$refs) {
1347                 read_commit_parents(\%parents, $c);
1348         }
1350         my @linear_refs;
1351         my %skip = ();
1352         my $last_svn_commit = $gs->last_commit;
1353         foreach my $c (reverse @$refs) {
1354                 next if $c eq $last_svn_commit;
1355                 last if $skip{$c};
1357                 unshift @linear_refs, $c;
1358                 $skip{$c} = 1;
1360                 # we only want the first parent to diff against for linear
1361                 # history, we save the rest to inject when we finalize the
1362                 # svn commit
1363                 my $fp_a = verify_ref("$c~1");
1364                 my $fp_b = shift @{$parents{$c}} if $parents{$c};
1365                 if (!$fp_a || !$fp_b) {
1366                         die "Commit $c\n",
1367                             "has no parent commit, and therefore ",
1368                             "nothing to diff against.\n",
1369                             "You should be working from a repository ",
1370                             "originally created by git-svn\n";
1371                 }
1372                 if ($fp_a ne $fp_b) {
1373                         die "$c~1 = $fp_a, however parsing commit $c ",
1374                             "revealed that:\n$c~1 = $fp_b\nBUG!\n";
1375                 }
1377                 foreach my $p (@{$parents{$c}}) {
1378                         $skip{$p} = 1;
1379                 }
1380         }
1381         (\@linear_refs, \%parents);
1384 sub find_file_type_and_diff_status {
1385         my ($path) = @_;
1386         return ('dir', '') if $path eq '';
1388         my $diff_output =
1389             command_oneline(qw(diff --cached --name-status --), $path) || "";
1390         my $diff_status = (split(' ', $diff_output))[0] || "";
1392         my $ls_tree = command_oneline(qw(ls-tree HEAD), $path) || "";
1394         return (undef, undef) if !$diff_status && !$ls_tree;
1396         if ($diff_status eq "A") {
1397                 return ("link", $diff_status) if -l $path;
1398                 return ("dir", $diff_status) if -d $path;
1399                 return ("file", $diff_status);
1400         }
1402         my $mode = (split(' ', $ls_tree))[0] || "";
1404         return ("link", $diff_status) if $mode eq "120000";
1405         return ("dir", $diff_status) if $mode eq "040000";
1406         return ("file", $diff_status);
1409 sub md5sum {
1410         my $arg = shift;
1411         my $ref = ref $arg;
1412         my $md5 = Digest::MD5->new();
1413         if ($ref eq 'GLOB' || $ref eq 'IO::File' || $ref eq 'File::Temp') {
1414                 $md5->addfile($arg) or croak $!;
1415         } elsif ($ref eq 'SCALAR') {
1416                 $md5->add($$arg) or croak $!;
1417         } elsif (!$ref) {
1418                 $md5->add($arg) or croak $!;
1419         } else {
1420                 ::fatal "Can't provide MD5 hash for unknown ref type: '", $ref, "'";
1421         }
1422         return $md5->hexdigest();
1425 package Git::SVN;
1426 use strict;
1427 use warnings;
1428 use Fcntl qw/:DEFAULT :seek/;
1429 use constant rev_map_fmt => 'NH40';
1430 use vars qw/$default_repo_id $default_ref_id $_no_metadata $_follow_parent
1431             $_repack $_repack_flags $_use_svm_props $_head
1432             $_use_svnsync_props $no_reuse_existing $_minimize_url
1433             $_use_log_author $_add_author_from $_localtime/;
1434 use Carp qw/croak/;
1435 use File::Path qw/mkpath/;
1436 use File::Copy qw/copy/;
1437 use IPC::Open3;
1439 my ($_gc_nr, $_gc_period);
1441 # properties that we do not log:
1442 my %SKIP_PROP;
1443 BEGIN {
1444         %SKIP_PROP = map { $_ => 1 } qw/svn:wc:ra_dav:version-url
1445                                         svn:special svn:executable
1446                                         svn:entry:committed-rev
1447                                         svn:entry:last-author
1448                                         svn:entry:uuid
1449                                         svn:entry:committed-date/;
1451         # some options are read globally, but can be overridden locally
1452         # per [svn-remote "..."] section.  Command-line options will *NOT*
1453         # override options set in an [svn-remote "..."] section
1454         no strict 'refs';
1455         for my $option (qw/follow_parent no_metadata use_svm_props
1456                            use_svnsync_props/) {
1457                 my $key = $option;
1458                 $key =~ tr/_//d;
1459                 my $prop = "-$option";
1460                 *$option = sub {
1461                         my ($self) = @_;
1462                         return $self->{$prop} if exists $self->{$prop};
1463                         my $k = "svn-remote.$self->{repo_id}.$key";
1464                         eval { command_oneline(qw/config --get/, $k) };
1465                         if ($@) {
1466                                 $self->{$prop} = ${"Git::SVN::_$option"};
1467                         } else {
1468                                 my $v = command_oneline(qw/config --bool/,$k);
1469                                 $self->{$prop} = $v eq 'false' ? 0 : 1;
1470                         }
1471                         return $self->{$prop};
1472                 }
1473         }
1477 my (%LOCKFILES, %INDEX_FILES);
1478 END {
1479         unlink keys %LOCKFILES if %LOCKFILES;
1480         unlink keys %INDEX_FILES if %INDEX_FILES;
1483 sub resolve_local_globs {
1484         my ($url, $fetch, $glob_spec) = @_;
1485         return unless defined $glob_spec;
1486         my $ref = $glob_spec->{ref};
1487         my $path = $glob_spec->{path};
1488         foreach (command(qw#for-each-ref --format=%(refname) refs/remotes#)) {
1489                 next unless m#^refs/remotes/$ref->{regex}$#;
1490                 my $p = $1;
1491                 my $pathname = desanitize_refname($path->full_path($p));
1492                 my $refname = desanitize_refname($ref->full_path($p));
1493                 if (my $existing = $fetch->{$pathname}) {
1494                         if ($existing ne $refname) {
1495                                 die "Refspec conflict:\n",
1496                                     "existing: refs/remotes/$existing\n",
1497                                     " globbed: refs/remotes/$refname\n";
1498                         }
1499                         my $u = (::cmt_metadata("refs/remotes/$refname"))[0];
1500                         $u =~ s!^\Q$url\E(/|$)!! or die
1501                           "refs/remotes/$refname: '$url' not found in '$u'\n";
1502                         if ($pathname ne $u) {
1503                                 warn "W: Refspec glob conflict ",
1504                                      "(ref: refs/remotes/$refname):\n",
1505                                      "expected path: $pathname\n",
1506                                      "    real path: $u\n",
1507                                      "Continuing ahead with $u\n";
1508                                 next;
1509                         }
1510                 } else {
1511                         $fetch->{$pathname} = $refname;
1512                 }
1513         }
1516 sub parse_revision_argument {
1517         my ($base, $head) = @_;
1518         if (!defined $::_revision || $::_revision eq 'BASE:HEAD') {
1519                 return ($base, $head);
1520         }
1521         return ($1, $2) if ($::_revision =~ /^(\d+):(\d+)$/);
1522         return ($::_revision, $::_revision) if ($::_revision =~ /^\d+$/);
1523         return ($head, $head) if ($::_revision eq 'HEAD');
1524         return ($base, $1) if ($::_revision =~ /^BASE:(\d+)$/);
1525         return ($1, $head) if ($::_revision =~ /^(\d+):HEAD$/);
1526         die "revision argument: $::_revision not understood by git-svn\n";
1529 sub fetch_all {
1530         my ($repo_id, $remotes) = @_;
1531         if (ref $repo_id) {
1532                 my $gs = $repo_id;
1533                 $repo_id = undef;
1534                 $repo_id = $gs->{repo_id};
1535         }
1536         $remotes ||= read_all_remotes();
1537         my $remote = $remotes->{$repo_id} or
1538                      die "[svn-remote \"$repo_id\"] unknown\n";
1539         my $fetch = $remote->{fetch};
1540         my $url = $remote->{url} or die "svn-remote.$repo_id.url not defined\n";
1541         my (@gs, @globs);
1542         my $ra = Git::SVN::Ra->new($url);
1543         my $uuid = $ra->get_uuid;
1544         my $head = $ra->get_latest_revnum;
1545         my $base = defined $fetch ? $head : 0;
1547         # read the max revs for wildcard expansion (branches/*, tags/*)
1548         foreach my $t (qw/branches tags/) {
1549                 defined $remote->{$t} or next;
1550                 push @globs, $remote->{$t};
1551                 my $max_rev = eval { tmp_config(qw/--int --get/,
1552                                          "svn-remote.$repo_id.${t}-maxRev") };
1553                 if (defined $max_rev && ($max_rev < $base)) {
1554                         $base = $max_rev;
1555                 } elsif (!defined $max_rev) {
1556                         $base = 0;
1557                 }
1558         }
1560         if ($fetch) {
1561                 foreach my $p (sort keys %$fetch) {
1562                         my $gs = Git::SVN->new($fetch->{$p}, $repo_id, $p);
1563                         my $lr = $gs->rev_map_max;
1564                         if (defined $lr) {
1565                                 $base = $lr if ($lr < $base);
1566                         }
1567                         push @gs, $gs;
1568                 }
1569         }
1571         ($base, $head) = parse_revision_argument($base, $head);
1572         $ra->gs_fetch_loop_common($base, $head, \@gs, \@globs);
1575 sub read_all_remotes {
1576         my $r = {};
1577         my $use_svm_props = eval { command_oneline(qw/config --bool
1578             svn.useSvmProps/) };
1579         $use_svm_props = $use_svm_props eq 'true' if $use_svm_props;
1580         foreach (grep { s/^svn-remote\.// } command(qw/config -l/)) {
1581                 if (m!^(.+)\.fetch=\s*(.*)\s*:\s*(.+)\s*$!) {
1582                         my ($remote, $local_ref, $_remote_ref) = ($1, $2, $3);
1583                         die("svn-remote.$remote: remote ref '$_remote_ref' "
1584                             . "must start with 'refs/remotes/'\n")
1585                                 unless $_remote_ref =~ m{^refs/remotes/(.+)};
1586                         my $remote_ref = $1;
1587                         $local_ref =~ s{^/}{};
1588                         $r->{$remote}->{fetch}->{$local_ref} = $remote_ref;
1589                         $r->{$remote}->{svm} = {} if $use_svm_props;
1590                 } elsif (m!^(.+)\.usesvmprops=\s*(.*)\s*$!) {
1591                         $r->{$1}->{svm} = {};
1592                 } elsif (m!^(.+)\.url=\s*(.*)\s*$!) {
1593                         $r->{$1}->{url} = $2;
1594                 } elsif (m!^(.+)\.(branches|tags)=
1595                            (.*):refs/remotes/(.+)\s*$/!x) {
1596                         my ($p, $g) = ($3, $4);
1597                         my $rs = $r->{$1}->{$2} = {
1598                                           t => $2,
1599                                           remote => $1,
1600                                           path => Git::SVN::GlobSpec->new($p),
1601                                           ref => Git::SVN::GlobSpec->new($g) };
1602                         if (length($rs->{ref}->{right}) != 0) {
1603                                 die "The '*' glob character must be the last ",
1604                                     "character of '$g'\n";
1605                         }
1606                 }
1607         }
1609         map {
1610                 if (defined $r->{$_}->{svm}) {
1611                         my $svm;
1612                         eval {
1613                                 my $section = "svn-remote.$_";
1614                                 $svm = {
1615                                         source => tmp_config('--get',
1616                                             "$section.svm-source"),
1617                                         replace => tmp_config('--get',
1618                                             "$section.svm-replace"),
1619                                 }
1620                         };
1621                         $r->{$_}->{svm} = $svm;
1622                 }
1623         } keys %$r;
1625         $r;
1628 sub init_vars {
1629         $_gc_nr = $_gc_period = 1000;
1630         if (defined $_repack || defined $_repack_flags) {
1631                warn "Repack options are obsolete; they have no effect.\n";
1632         }
1635 sub verify_remotes_sanity {
1636         return unless -d $ENV{GIT_DIR};
1637         my %seen;
1638         foreach (command(qw/config -l/)) {
1639                 if (m!^svn-remote\.(?:.+)\.fetch=.*:refs/remotes/(\S+)\s*$!) {
1640                         if ($seen{$1}) {
1641                                 die "Remote ref refs/remote/$1 is tracked by",
1642                                     "\n  \"$_\"\nand\n  \"$seen{$1}\"\n",
1643                                     "Please resolve this ambiguity in ",
1644                                     "your git configuration file before ",
1645                                     "continuing\n";
1646                         }
1647                         $seen{$1} = $_;
1648                 }
1649         }
1652 sub find_existing_remote {
1653         my ($url, $remotes) = @_;
1654         return undef if $no_reuse_existing;
1655         my $existing;
1656         foreach my $repo_id (keys %$remotes) {
1657                 my $u = $remotes->{$repo_id}->{url} or next;
1658                 next if $u ne $url;
1659                 $existing = $repo_id;
1660                 last;
1661         }
1662         $existing;
1665 sub init_remote_config {
1666         my ($self, $url, $no_write) = @_;
1667         $url =~ s!/+$!!; # strip trailing slash
1668         my $r = read_all_remotes();
1669         my $existing = find_existing_remote($url, $r);
1670         if ($existing) {
1671                 unless ($no_write) {
1672                         print STDERR "Using existing ",
1673                                      "[svn-remote \"$existing\"]\n";
1674                 }
1675                 $self->{repo_id} = $existing;
1676         } elsif ($_minimize_url) {
1677                 my $min_url = Git::SVN::Ra->new($url)->minimize_url;
1678                 $existing = find_existing_remote($min_url, $r);
1679                 if ($existing) {
1680                         unless ($no_write) {
1681                                 print STDERR "Using existing ",
1682                                              "[svn-remote \"$existing\"]\n";
1683                         }
1684                         $self->{repo_id} = $existing;
1685                 }
1686                 if ($min_url ne $url) {
1687                         unless ($no_write) {
1688                                 print STDERR "Using higher level of URL: ",
1689                                              "$url => $min_url\n";
1690                         }
1691                         my $old_path = $self->{path};
1692                         $self->{path} = $url;
1693                         $self->{path} =~ s!^\Q$min_url\E(/|$)!!;
1694                         if (length $old_path) {
1695                                 $self->{path} .= "/$old_path";
1696                         }
1697                         $url = $min_url;
1698                 }
1699         }
1700         my $orig_url;
1701         if (!$existing) {
1702                 # verify that we aren't overwriting anything:
1703                 $orig_url = eval {
1704                         command_oneline('config', '--get',
1705                                         "svn-remote.$self->{repo_id}.url")
1706                 };
1707                 if ($orig_url && ($orig_url ne $url)) {
1708                         die "svn-remote.$self->{repo_id}.url already set: ",
1709                             "$orig_url\nwanted to set to: $url\n";
1710                 }
1711         }
1712         my ($xrepo_id, $xpath) = find_ref($self->refname);
1713         if (defined $xpath) {
1714                 die "svn-remote.$xrepo_id.fetch already set to track ",
1715                     "$xpath:refs/remotes/", $self->refname, "\n";
1716         }
1717         unless ($no_write) {
1718                 command_noisy('config',
1719                               "svn-remote.$self->{repo_id}.url", $url);
1720                 $self->{path} =~ s{^/}{};
1721                 command_noisy('config', '--add',
1722                               "svn-remote.$self->{repo_id}.fetch",
1723                               "$self->{path}:".$self->refname);
1724         }
1725         $self->{url} = $url;
1728 sub find_by_url { # repos_root and, path are optional
1729         my ($class, $full_url, $repos_root, $path) = @_;
1731         return undef unless defined $full_url;
1732         remove_username($full_url);
1733         remove_username($repos_root) if defined $repos_root;
1734         my $remotes = read_all_remotes();
1735         if (defined $full_url && defined $repos_root && !defined $path) {
1736                 $path = $full_url;
1737                 $path =~ s#^\Q$repos_root\E(?:/|$)##;
1738         }
1739         foreach my $repo_id (keys %$remotes) {
1740                 my $u = $remotes->{$repo_id}->{url} or next;
1741                 remove_username($u);
1742                 next if defined $repos_root && $repos_root ne $u;
1744                 my $fetch = $remotes->{$repo_id}->{fetch} || {};
1745                 foreach (qw/branches tags/) {
1746                         resolve_local_globs($u, $fetch,
1747                                             $remotes->{$repo_id}->{$_});
1748                 }
1749                 my $p = $path;
1750                 my $rwr = rewrite_root({repo_id => $repo_id});
1751                 my $svm = $remotes->{$repo_id}->{svm}
1752                         if defined $remotes->{$repo_id}->{svm};
1753                 unless (defined $p) {
1754                         $p = $full_url;
1755                         my $z = $u;
1756                         my $prefix = '';
1757                         if ($rwr) {
1758                                 $z = $rwr;
1759                                 remove_username($z);
1760                         } elsif (defined $svm) {
1761                                 $z = $svm->{source};
1762                                 $prefix = $svm->{replace};
1763                                 $prefix =~ s#^\Q$u\E(?:/|$)##;
1764                                 $prefix =~ s#/$##;
1765                         }
1766                         $p =~ s#^\Q$z\E(?:/|$)#$prefix# or next;
1767                 }
1768                 foreach my $f (keys %$fetch) {
1769                         next if $f ne $p;
1770                         return Git::SVN->new($fetch->{$f}, $repo_id, $f);
1771                 }
1772         }
1773         undef;
1776 sub init {
1777         my ($class, $url, $path, $repo_id, $ref_id, $no_write) = @_;
1778         my $self = _new($class, $repo_id, $ref_id, $path);
1779         if (defined $url) {
1780                 $self->init_remote_config($url, $no_write);
1781         }
1782         $self;
1785 sub find_ref {
1786         my ($ref_id) = @_;
1787         foreach (command(qw/config -l/)) {
1788                 next unless m!^svn-remote\.(.+)\.fetch=
1789                               \s*(.*)\s*:\s*refs/remotes/(.+)\s*$!x;
1790                 my ($repo_id, $path, $ref) = ($1, $2, $3);
1791                 if ($ref eq $ref_id) {
1792                         $path = '' if ($path =~ m#^\./?#);
1793                         return ($repo_id, $path);
1794                 }
1795         }
1796         (undef, undef, undef);
1799 sub new {
1800         my ($class, $ref_id, $repo_id, $path) = @_;
1801         if (defined $ref_id && !defined $repo_id && !defined $path) {
1802                 ($repo_id, $path) = find_ref($ref_id);
1803                 if (!defined $repo_id) {
1804                         die "Could not find a \"svn-remote.*.fetch\" key ",
1805                             "in the repository configuration matching: ",
1806                             "refs/remotes/$ref_id\n";
1807                 }
1808         }
1809         my $self = _new($class, $repo_id, $ref_id, $path);
1810         if (!defined $self->{path} || !length $self->{path}) {
1811                 my $fetch = command_oneline('config', '--get',
1812                                             "svn-remote.$repo_id.fetch",
1813                                             ":refs/remotes/$ref_id\$") or
1814                      die "Failed to read \"svn-remote.$repo_id.fetch\" ",
1815                          "\":refs/remotes/$ref_id\$\" in config\n";
1816                 ($self->{path}, undef) = split(/\s*:\s*/, $fetch);
1817         }
1818         $self->{url} = command_oneline('config', '--get',
1819                                        "svn-remote.$repo_id.url") or
1820                   die "Failed to read \"svn-remote.$repo_id.url\" in config\n";
1821         $self->rebuild;
1822         $self;
1825 sub refname {
1826         my ($refname) = "refs/remotes/$_[0]->{ref_id}" ;
1828         # It cannot end with a slash /, we'll throw up on this because
1829         # SVN can't have directories with a slash in their name, either:
1830         if ($refname =~ m{/$}) {
1831                 die "ref: '$refname' ends with a trailing slash, this is ",
1832                     "not permitted by git nor Subversion\n";
1833         }
1835         # It cannot have ASCII control character space, tilde ~, caret ^,
1836         # colon :, question-mark ?, asterisk *, space, or open bracket [
1837         # anywhere.
1838         #
1839         # Additionally, % must be escaped because it is used for escaping
1840         # and we want our escaped refname to be reversible
1841         $refname =~ s{([ \%~\^:\?\*\[\t])}{uc sprintf('%%%02x',ord($1))}eg;
1843         # no slash-separated component can begin with a dot .
1844         # /.* becomes /%2E*
1845         $refname =~ s{/\.}{/%2E}g;
1847         # It cannot have two consecutive dots .. anywhere
1848         # .. becomes %2E%2E
1849         $refname =~ s{\.\.}{%2E%2E}g;
1851         return $refname;
1854 sub desanitize_refname {
1855         my ($refname) = @_;
1856         $refname =~ s{%(?:([0-9A-F]{2}))}{chr hex($1)}eg;
1857         return $refname;
1860 sub svm_uuid {
1861         my ($self) = @_;
1862         return $self->{svm}->{uuid} if $self->svm;
1863         $self->ra;
1864         unless ($self->{svm}) {
1865                 die "SVM UUID not cached, and reading remotely failed\n";
1866         }
1867         $self->{svm}->{uuid};
1870 sub svm {
1871         my ($self) = @_;
1872         return $self->{svm} if $self->{svm};
1873         my $svm;
1874         # see if we have it in our config, first:
1875         eval {
1876                 my $section = "svn-remote.$self->{repo_id}";
1877                 $svm = {
1878                   source => tmp_config('--get', "$section.svm-source"),
1879                   uuid => tmp_config('--get', "$section.svm-uuid"),
1880                   replace => tmp_config('--get', "$section.svm-replace"),
1881                 }
1882         };
1883         if ($svm && $svm->{source} && $svm->{uuid} && $svm->{replace}) {
1884                 $self->{svm} = $svm;
1885         }
1886         $self->{svm};
1889 sub _set_svm_vars {
1890         my ($self, $ra) = @_;
1891         return $ra if $self->svm;
1893         my @err = ( "useSvmProps set, but failed to read SVM properties\n",
1894                     "(svm:source, svm:uuid) ",
1895                     "from the following URLs:\n" );
1896         sub read_svm_props {
1897                 my ($self, $ra, $path, $r) = @_;
1898                 my $props = ($ra->get_dir($path, $r))[2];
1899                 my $src = $props->{'svm:source'};
1900                 my $uuid = $props->{'svm:uuid'};
1901                 return undef if (!$src || !$uuid);
1903                 chomp($src, $uuid);
1905                 $uuid =~ m{^[0-9a-f\-]{30,}$}
1906                     or die "doesn't look right - svm:uuid is '$uuid'\n";
1908                 # the '!' is used to mark the repos_root!/relative/path
1909                 $src =~ s{/?!/?}{/};
1910                 $src =~ s{/+$}{}; # no trailing slashes please
1911                 # username is of no interest
1912                 $src =~ s{(^[a-z\+]*://)[^/@]*@}{$1};
1914                 my $replace = $ra->{url};
1915                 $replace .= "/$path" if length $path;
1917                 my $section = "svn-remote.$self->{repo_id}";
1918                 tmp_config("$section.svm-source", $src);
1919                 tmp_config("$section.svm-replace", $replace);
1920                 tmp_config("$section.svm-uuid", $uuid);
1921                 $self->{svm} = {
1922                         source => $src,
1923                         uuid => $uuid,
1924                         replace => $replace
1925                 };
1926         }
1928         my $r = $ra->get_latest_revnum;
1929         my $path = $self->{path};
1930         my %tried;
1931         while (length $path) {
1932                 unless ($tried{"$self->{url}/$path"}) {
1933                         return $ra if $self->read_svm_props($ra, $path, $r);
1934                         $tried{"$self->{url}/$path"} = 1;
1935                 }
1936                 $path =~ s#/?[^/]+$##;
1937         }
1938         die "Path: '$path' should be ''\n" if $path ne '';
1939         return $ra if $self->read_svm_props($ra, $path, $r);
1940         $tried{"$self->{url}/$path"} = 1;
1942         if ($ra->{repos_root} eq $self->{url}) {
1943                 die @err, (map { "  $_\n" } keys %tried), "\n";
1944         }
1946         # nope, make sure we're connected to the repository root:
1947         my $ok;
1948         my @tried_b;
1949         $path = $ra->{svn_path};
1950         $ra = Git::SVN::Ra->new($ra->{repos_root});
1951         while (length $path) {
1952                 unless ($tried{"$ra->{url}/$path"}) {
1953                         $ok = $self->read_svm_props($ra, $path, $r);
1954                         last if $ok;
1955                         $tried{"$ra->{url}/$path"} = 1;
1956                 }
1957                 $path =~ s#/?[^/]+$##;
1958         }
1959         die "Path: '$path' should be ''\n" if $path ne '';
1960         $ok ||= $self->read_svm_props($ra, $path, $r);
1961         $tried{"$ra->{url}/$path"} = 1;
1962         if (!$ok) {
1963                 die @err, (map { "  $_\n" } keys %tried), "\n";
1964         }
1965         Git::SVN::Ra->new($self->{url});
1968 sub svnsync {
1969         my ($self) = @_;
1970         return $self->{svnsync} if $self->{svnsync};
1972         if ($self->no_metadata) {
1973                 die "Can't have both 'noMetadata' and ",
1974                     "'useSvnsyncProps' options set!\n";
1975         }
1976         if ($self->rewrite_root) {
1977                 die "Can't have both 'useSvnsyncProps' and 'rewriteRoot' ",
1978                     "options set!\n";
1979         }
1981         my $svnsync;
1982         # see if we have it in our config, first:
1983         eval {
1984                 my $section = "svn-remote.$self->{repo_id}";
1986                 my $url = tmp_config('--get', "$section.svnsync-url");
1987                 ($url) = ($url =~ m{^([a-z\+]+://\S+)$}) or
1988                    die "doesn't look right - svn:sync-from-url is '$url'\n";
1990                 my $uuid = tmp_config('--get', "$section.svnsync-uuid");
1991                 ($uuid) = ($uuid =~ m{^([0-9a-f\-]{30,})$}) or
1992                    die "doesn't look right - svn:sync-from-uuid is '$uuid'\n";
1994                 $svnsync = { url => $url, uuid => $uuid }
1995         };
1996         if ($svnsync && $svnsync->{url} && $svnsync->{uuid}) {
1997                 return $self->{svnsync} = $svnsync;
1998         }
2000         my $err = "useSvnsyncProps set, but failed to read " .
2001                   "svnsync property: svn:sync-from-";
2002         my $rp = $self->ra->rev_proplist(0);
2004         my $url = $rp->{'svn:sync-from-url'} or die $err . "url\n";
2005         ($url) = ($url =~ m{^([a-z\+]+://\S+)$}) or
2006                    die "doesn't look right - svn:sync-from-url is '$url'\n";
2008         my $uuid = $rp->{'svn:sync-from-uuid'} or die $err . "uuid\n";
2009         ($uuid) = ($uuid =~ m{^([0-9a-f\-]{30,})$}) or
2010                    die "doesn't look right - svn:sync-from-uuid is '$uuid'\n";
2012         my $section = "svn-remote.$self->{repo_id}";
2013         tmp_config('--add', "$section.svnsync-uuid", $uuid);
2014         tmp_config('--add', "$section.svnsync-url", $url);
2015         return $self->{svnsync} = { url => $url, uuid => $uuid };
2018 # this allows us to memoize our SVN::Ra UUID locally and avoid a
2019 # remote lookup (useful for 'git svn log').
2020 sub ra_uuid {
2021         my ($self) = @_;
2022         unless ($self->{ra_uuid}) {
2023                 my $key = "svn-remote.$self->{repo_id}.uuid";
2024                 my $uuid = eval { tmp_config('--get', $key) };
2025                 if (!$@ && $uuid && $uuid =~ /^([a-f\d\-]{30,})$/) {
2026                         $self->{ra_uuid} = $uuid;
2027                 } else {
2028                         die "ra_uuid called without URL\n" unless $self->{url};
2029                         $self->{ra_uuid} = $self->ra->get_uuid;
2030                         tmp_config('--add', $key, $self->{ra_uuid});
2031                 }
2032         }
2033         $self->{ra_uuid};
2036 sub _set_repos_root {
2037         my ($self, $repos_root) = @_;
2038         my $k = "svn-remote.$self->{repo_id}.reposRoot";
2039         $repos_root ||= $self->ra->{repos_root};
2040         tmp_config($k, $repos_root);
2041         $repos_root;
2044 sub repos_root {
2045         my ($self) = @_;
2046         my $k = "svn-remote.$self->{repo_id}.reposRoot";
2047         eval { tmp_config('--get', $k) } || $self->_set_repos_root;
2050 sub ra {
2051         my ($self) = shift;
2052         my $ra = Git::SVN::Ra->new($self->{url});
2053         $self->_set_repos_root($ra->{repos_root});
2054         if ($self->use_svm_props && !$self->{svm}) {
2055                 if ($self->no_metadata) {
2056                         die "Can't have both 'noMetadata' and ",
2057                             "'useSvmProps' options set!\n";
2058                 } elsif ($self->use_svnsync_props) {
2059                         die "Can't have both 'useSvnsyncProps' and ",
2060                             "'useSvmProps' options set!\n";
2061                 }
2062                 $ra = $self->_set_svm_vars($ra);
2063                 $self->{-want_revprops} = 1;
2064         }
2065         $ra;
2068 sub rel_path {
2069         my ($self) = @_;
2070         my $repos_root = $self->ra->{repos_root};
2071         return $self->{path} if ($self->{url} eq $repos_root);
2072         my $url = $self->{url} .
2073                   (length $self->{path} ? "/$self->{path}" : $self->{path});
2074         $url =~ s!^\Q$repos_root\E(?:/+|$)!!g;
2075         $url;
2078 # prop_walk(PATH, REV, SUB)
2079 # -------------------------
2080 # Recursively traverse PATH at revision REV and invoke SUB for each
2081 # directory that contains a SVN property.  SUB will be invoked as
2082 # follows:  &SUB(gs, path, props);  where `gs' is this instance of
2083 # Git::SVN, `path' the path to the directory where the properties
2084 # `props' were found.  The `path' will be relative to point of checkout,
2085 # that is, if url://repo/trunk is the current Git branch, and that
2086 # directory contains a sub-directory `d', SUB will be invoked with `/d/'
2087 # as `path' (note the trailing `/').
2088 sub prop_walk {
2089         my ($self, $path, $rev, $sub) = @_;
2091         $path =~ s#^/##;
2092         my ($dirent, undef, $props) = $self->ra->get_dir($path, $rev);
2093         $path =~ s#^/*#/#g;
2094         my $p = $path;
2095         # Strip the irrelevant part of the path.
2096         $p =~ s#^/+\Q$self->{path}\E(/|$)#/#;
2097         # Ensure the path is terminated by a `/'.
2098         $p =~ s#/*$#/#;
2100         # The properties contain all the internal SVN stuff nobody
2101         # (usually) cares about.
2102         my $interesting_props = 0;
2103         foreach (keys %{$props}) {
2104                 # If it doesn't start with `svn:', it must be a
2105                 # user-defined property.
2106                 ++$interesting_props and next if $_ !~ /^svn:/;
2107                 # FIXME: Fragile, if SVN adds new public properties,
2108                 # this needs to be updated.
2109                 ++$interesting_props if /^svn:(?:ignore|keywords|executable
2110                                                  |eol-style|mime-type
2111                                                  |externals|needs-lock)$/x;
2112         }
2113         &$sub($self, $p, $props) if $interesting_props;
2115         foreach (sort keys %$dirent) {
2116                 next if $dirent->{$_}->{kind} != $SVN::Node::dir;
2117                 $self->prop_walk($self->{path} . $p . $_, $rev, $sub);
2118         }
2121 sub last_rev { ($_[0]->last_rev_commit)[0] }
2122 sub last_commit { ($_[0]->last_rev_commit)[1] }
2124 # returns the newest SVN revision number and newest commit SHA1
2125 sub last_rev_commit {
2126         my ($self) = @_;
2127         if (defined $self->{last_rev} && defined $self->{last_commit}) {
2128                 return ($self->{last_rev}, $self->{last_commit});
2129         }
2130         my $c = ::verify_ref($self->refname.'^0');
2131         if ($c && !$self->use_svm_props && !$self->no_metadata) {
2132                 my $rev = (::cmt_metadata($c))[1];
2133                 if (defined $rev) {
2134                         ($self->{last_rev}, $self->{last_commit}) = ($rev, $c);
2135                         return ($rev, $c);
2136                 }
2137         }
2138         my $map_path = $self->map_path;
2139         unless (-e $map_path) {
2140                 ($self->{last_rev}, $self->{last_commit}) = (undef, undef);
2141                 return (undef, undef);
2142         }
2143         my ($rev, $commit) = $self->rev_map_max(1);
2144         ($self->{last_rev}, $self->{last_commit}) = ($rev, $commit);
2145         return ($rev, $commit);
2148 sub get_fetch_range {
2149         my ($self, $min, $max) = @_;
2150         $max ||= $self->ra->get_latest_revnum;
2151         $min ||= $self->rev_map_max;
2152         (++$min, $max);
2155 sub tmp_config {
2156         my (@args) = @_;
2157         my $old_def_config = "$ENV{GIT_DIR}/svn/config";
2158         my $config = "$ENV{GIT_DIR}/svn/.metadata";
2159         if (! -f $config && -f $old_def_config) {
2160                 rename $old_def_config, $config or
2161                        die "Failed rename $old_def_config => $config: $!\n";
2162         }
2163         my $old_config = $ENV{GIT_CONFIG};
2164         $ENV{GIT_CONFIG} = $config;
2165         $@ = undef;
2166         my @ret = eval {
2167                 unless (-f $config) {
2168                         mkfile($config);
2169                         open my $fh, '>', $config or
2170                             die "Can't open $config: $!\n";
2171                         print $fh "; This file is used internally by ",
2172                                   "git-svn\n" or die
2173                                   "Couldn't write to $config: $!\n";
2174                         print $fh "; You should not have to edit it\n" or
2175                               die "Couldn't write to $config: $!\n";
2176                         close $fh or die "Couldn't close $config: $!\n";
2177                 }
2178                 command('config', @args);
2179         };
2180         my $err = $@;
2181         if (defined $old_config) {
2182                 $ENV{GIT_CONFIG} = $old_config;
2183         } else {
2184                 delete $ENV{GIT_CONFIG};
2185         }
2186         die $err if $err;
2187         wantarray ? @ret : $ret[0];
2190 sub tmp_index_do {
2191         my ($self, $sub) = @_;
2192         my $old_index = $ENV{GIT_INDEX_FILE};
2193         $ENV{GIT_INDEX_FILE} = $self->{index};
2194         $@ = undef;
2195         my @ret = eval {
2196                 my ($dir, $base) = ($self->{index} =~ m#^(.*?)/?([^/]+)$#);
2197                 mkpath([$dir]) unless -d $dir;
2198                 &$sub;
2199         };
2200         my $err = $@;
2201         if (defined $old_index) {
2202                 $ENV{GIT_INDEX_FILE} = $old_index;
2203         } else {
2204                 delete $ENV{GIT_INDEX_FILE};
2205         }
2206         die $err if $err;
2207         wantarray ? @ret : $ret[0];
2210 sub assert_index_clean {
2211         my ($self, $treeish) = @_;
2213         $self->tmp_index_do(sub {
2214                 command_noisy('read-tree', $treeish) unless -e $self->{index};
2215                 my $x = command_oneline('write-tree');
2216                 my ($y) = (command(qw/cat-file commit/, $treeish) =~
2217                            /^tree ($::sha1)/mo);
2218                 return if $y eq $x;
2220                 warn "Index mismatch: $y != $x\nrereading $treeish\n";
2221                 unlink $self->{index} or die "unlink $self->{index}: $!\n";
2222                 command_noisy('read-tree', $treeish);
2223                 $x = command_oneline('write-tree');
2224                 if ($y ne $x) {
2225                         ::fatal "trees ($treeish) $y != $x\n",
2226                                 "Something is seriously wrong...";
2227                 }
2228         });
2231 sub get_commit_parents {
2232         my ($self, $log_entry) = @_;
2233         my (%seen, @ret, @tmp);
2234         # legacy support for 'set-tree'; this is only used by set_tree_cb:
2235         if (my $ip = $self->{inject_parents}) {
2236                 if (my $commit = delete $ip->{$log_entry->{revision}}) {
2237                         push @tmp, $commit;
2238                 }
2239         }
2240         if (my $cur = ::verify_ref($self->refname.'^0')) {
2241                 push @tmp, $cur;
2242         }
2243         if (my $ipd = $self->{inject_parents_dcommit}) {
2244                 if (my $commit = delete $ipd->{$log_entry->{revision}}) {
2245                         push @tmp, @$commit;
2246                 }
2247         }
2248         push @tmp, $_ foreach (@{$log_entry->{parents}}, @tmp);
2249         while (my $p = shift @tmp) {
2250                 next if $seen{$p};
2251                 $seen{$p} = 1;
2252                 push @ret, $p;
2253                 # MAXPARENT is defined to 16 in commit-tree.c:
2254                 last if @ret >= 16;
2255         }
2256         if (@tmp) {
2257                 die "r$log_entry->{revision}: No room for parents:\n\t",
2258                     join("\n\t", @tmp), "\n";
2259         }
2260         @ret;
2263 sub rewrite_root {
2264         my ($self) = @_;
2265         return $self->{-rewrite_root} if exists $self->{-rewrite_root};
2266         my $k = "svn-remote.$self->{repo_id}.rewriteRoot";
2267         my $rwr = eval { command_oneline(qw/config --get/, $k) };
2268         if ($rwr) {
2269                 $rwr =~ s#/+$##;
2270                 if ($rwr !~ m#^[a-z\+]+://#) {
2271                         die "$rwr is not a valid URL (key: $k)\n";
2272                 }
2273         }
2274         $self->{-rewrite_root} = $rwr;
2277 sub metadata_url {
2278         my ($self) = @_;
2279         ($self->rewrite_root || $self->{url}) .
2280            (length $self->{path} ? '/' . $self->{path} : '');
2283 sub full_url {
2284         my ($self) = @_;
2285         $self->{url} . (length $self->{path} ? '/' . $self->{path} : '');
2289 sub set_commit_header_env {
2290         my ($log_entry) = @_;
2291         my %env;
2292         foreach my $ned (qw/NAME EMAIL DATE/) {
2293                 foreach my $ac (qw/AUTHOR COMMITTER/) {
2294                         $env{"GIT_${ac}_${ned}"} = $ENV{"GIT_${ac}_${ned}"};
2295                 }
2296         }
2298         $ENV{GIT_AUTHOR_NAME} = $log_entry->{name};
2299         $ENV{GIT_AUTHOR_EMAIL} = $log_entry->{email};
2300         $ENV{GIT_AUTHOR_DATE} = $ENV{GIT_COMMITTER_DATE} = $log_entry->{date};
2302         $ENV{GIT_COMMITTER_NAME} = (defined $log_entry->{commit_name})
2303                                                 ? $log_entry->{commit_name}
2304                                                 : $log_entry->{name};
2305         $ENV{GIT_COMMITTER_EMAIL} = (defined $log_entry->{commit_email})
2306                                                 ? $log_entry->{commit_email}
2307                                                 : $log_entry->{email};
2308         \%env;
2311 sub restore_commit_header_env {
2312         my ($env) = @_;
2313         foreach my $ned (qw/NAME EMAIL DATE/) {
2314                 foreach my $ac (qw/AUTHOR COMMITTER/) {
2315                         my $k = "GIT_${ac}_${ned}";
2316                         if (defined $env->{$k}) {
2317                                 $ENV{$k} = $env->{$k};
2318                         } else {
2319                                 delete $ENV{$k};
2320                         }
2321                 }
2322         }
2325 sub gc {
2326         command_noisy('gc', '--auto');
2327 };
2329 sub do_git_commit {
2330         my ($self, $log_entry) = @_;
2331         my $lr = $self->last_rev;
2332         if (defined $lr && $lr >= $log_entry->{revision}) {
2333                 die "Last fetched revision of ", $self->refname,
2334                     " was r$lr, but we are about to fetch: ",
2335                     "r$log_entry->{revision}!\n";
2336         }
2337         if (my $c = $self->rev_map_get($log_entry->{revision})) {
2338                 croak "$log_entry->{revision} = $c already exists! ",
2339                       "Why are we refetching it?\n";
2340         }
2341         my $old_env = set_commit_header_env($log_entry);
2342         my $tree = $log_entry->{tree};
2343         if (!defined $tree) {
2344                 $tree = $self->tmp_index_do(sub {
2345                                             command_oneline('write-tree') });
2346         }
2347         die "Tree is not a valid sha1: $tree\n" if $tree !~ /^$::sha1$/o;
2349         my @exec = ('git', 'commit-tree', $tree);
2350         foreach ($self->get_commit_parents($log_entry)) {
2351                 push @exec, '-p', $_;
2352         }
2353         defined(my $pid = open3(my $msg_fh, my $out_fh, '>&STDERR', @exec))
2354                                                                    or croak $!;
2355         binmode $msg_fh;
2357         # we always get UTF-8 from SVN, but we may want our commits in
2358         # a different encoding.
2359         if (my $enc = Git::config('i18n.commitencoding')) {
2360                 require Encode;
2361                 Encode::from_to($log_entry->{log}, 'UTF-8', $enc);
2362         }
2363         print $msg_fh $log_entry->{log} or croak $!;
2364         restore_commit_header_env($old_env);
2365         unless ($self->no_metadata) {
2366                 print $msg_fh "\ngit-svn-id: $log_entry->{metadata}\n"
2367                               or croak $!;
2368         }
2369         $msg_fh->flush == 0 or croak $!;
2370         close $msg_fh or croak $!;
2371         chomp(my $commit = do { local $/; <$out_fh> });
2372         close $out_fh or croak $!;
2373         waitpid $pid, 0;
2374         croak $? if $?;
2375         if ($commit !~ /^$::sha1$/o) {
2376                 die "Failed to commit, invalid sha1: $commit\n";
2377         }
2379         $self->rev_map_set($log_entry->{revision}, $commit, 1);
2381         $self->{last_rev} = $log_entry->{revision};
2382         $self->{last_commit} = $commit;
2383         print "r$log_entry->{revision}" unless $::_q > 1;
2384         if (defined $log_entry->{svm_revision}) {
2385                  print " (\@$log_entry->{svm_revision})" unless $::_q > 1;
2386                  $self->rev_map_set($log_entry->{svm_revision}, $commit,
2387                                    0, $self->svm_uuid);
2388         }
2389         print " = $commit ($self->{ref_id})\n" unless $::_q > 1;
2390         if (--$_gc_nr == 0) {
2391                 $_gc_nr = $_gc_period;
2392                 gc();
2393         }
2394         return $commit;
2397 sub match_paths {
2398         my ($self, $paths, $r) = @_;
2399         return 1 if $self->{path} eq '';
2400         if (my $path = $paths->{"/$self->{path}"}) {
2401                 return ($path->{action} eq 'D') ? 0 : 1;
2402         }
2403         my $repos_root = $self->ra->{repos_root};
2404         my $extended_path = $self->{url} . '/' . $self->{path};
2405         $extended_path =~ s#^\Q$repos_root\E(/|$)##;
2406         $self->{path_regex} ||= qr/^\/\Q$extended_path\E\//;
2407         if (grep /$self->{path_regex}/, keys %$paths) {
2408                 return 1;
2409         }
2410         my $c = '';
2411         foreach (split m#/#, $self->{path}) {
2412                 $c .= "/$_";
2413                 next unless ($paths->{$c} &&
2414                              ($paths->{$c}->{action} =~ /^[AR]$/));
2415                 if ($self->ra->check_path($self->{path}, $r) ==
2416                     $SVN::Node::dir) {
2417                         return 1;
2418                 }
2419         }
2420         return 0;
2423 sub find_parent_branch {
2424         my ($self, $paths, $rev) = @_;
2425         return undef unless $self->follow_parent;
2426         unless (defined $paths) {
2427                 my $err_handler = $SVN::Error::handler;
2428                 $SVN::Error::handler = \&Git::SVN::Ra::skip_unknown_revs;
2429                 $self->ra->get_log([$self->{path}], $rev, $rev, 0, 1, 1, sub {
2430                                    $paths =
2431                                       Git::SVN::Ra::dup_changed_paths($_[0]) });
2432                 $SVN::Error::handler = $err_handler;
2433         }
2434         return undef unless defined $paths;
2436         # look for a parent from another branch:
2437         my @b_path_components = split m#/#, $self->rel_path;
2438         my @a_path_components;
2439         my $i;
2440         while (@b_path_components) {
2441                 $i = $paths->{'/'.join('/', @b_path_components)};
2442                 last if $i && defined $i->{copyfrom_path};
2443                 unshift(@a_path_components, pop(@b_path_components));
2444         }
2445         return undef unless defined $i && defined $i->{copyfrom_path};
2446         my $branch_from = $i->{copyfrom_path};
2447         if (@a_path_components) {
2448                 print STDERR "branch_from: $branch_from => ";
2449                 $branch_from .= '/'.join('/', @a_path_components);
2450                 print STDERR $branch_from, "\n";
2451         }
2452         my $r = $i->{copyfrom_rev};
2453         my $repos_root = $self->ra->{repos_root};
2454         my $url = $self->ra->{url};
2455         my $new_url = $repos_root . $branch_from;
2456         print STDERR  "Found possible branch point: ",
2457                       "$new_url => ", $self->full_url, ", $r\n";
2458         $branch_from =~ s#^/##;
2459         my $gs = $self->other_gs($new_url, $url, $repos_root,
2460                                  $branch_from, $r, $self->{ref_id});
2461         my ($r0, $parent) = $gs->find_rev_before($r, 1);
2462         {
2463                 my ($base, $head);
2464                 if (!defined $r0 || !defined $parent) {
2465                         ($base, $head) = parse_revision_argument(0, $r);
2466                 } else {
2467                         if ($r0 < $r) {
2468                                 $gs->ra->get_log([$gs->{path}], $r0 + 1, $r, 1,
2469                                         0, 1, sub { $base = $_[1] - 1 });
2470                         }
2471                 }
2472                 if (defined $base && $base <= $r) {
2473                         $gs->fetch($base, $r);
2474                 }
2475                 ($r0, $parent) = $gs->find_rev_before($r, 1);
2476         }
2477         if (defined $r0 && defined $parent) {
2478                 print STDERR "Found branch parent: ($self->{ref_id}) $parent\n";
2479                 my $ed;
2480                 if ($self->ra->can_do_switch) {
2481                         $self->assert_index_clean($parent);
2482                         print STDERR "Following parent with do_switch\n";
2483                         # do_switch works with svn/trunk >= r22312, but that
2484                         # is not included with SVN 1.4.3 (the latest version
2485                         # at the moment), so we can't rely on it
2486                         $self->{last_rev} = $r0;
2487                         $self->{last_commit} = $parent;
2488                         $ed = SVN::Git::Fetcher->new($self, $gs->{path});
2489                         $gs->ra->gs_do_switch($r0, $rev, $gs,
2490                                               $self->full_url, $ed)
2491                           or die "SVN connection failed somewhere...\n";
2492                 } elsif ($self->ra->trees_match($new_url, $r0,
2493                                                 $self->full_url, $rev)) {
2494                         print STDERR "Trees match:\n",
2495                                      "  $new_url\@$r0\n",
2496                                      "  ${\$self->full_url}\@$rev\n",
2497                                      "Following parent with no changes\n";
2498                         $self->tmp_index_do(sub {
2499                             command_noisy('read-tree', $parent);
2500                         });
2501                         $self->{last_commit} = $parent;
2502                 } else {
2503                         print STDERR "Following parent with do_update\n";
2504                         $ed = SVN::Git::Fetcher->new($self);
2505                         $self->ra->gs_do_update($rev, $rev, $self, $ed)
2506                           or die "SVN connection failed somewhere...\n";
2507                 }
2508                 print STDERR "Successfully followed parent\n";
2509                 return $self->make_log_entry($rev, [$parent], $ed);
2510         }
2511         return undef;
2514 sub do_fetch {
2515         my ($self, $paths, $rev) = @_;
2516         my $ed;
2517         my ($last_rev, @parents);
2518         if (my $lc = $self->last_commit) {
2519                 # we can have a branch that was deleted, then re-added
2520                 # under the same name but copied from another path, in
2521                 # which case we'll have multiple parents (we don't
2522                 # want to break the original ref, nor lose copypath info):
2523                 if (my $log_entry = $self->find_parent_branch($paths, $rev)) {
2524                         push @{$log_entry->{parents}}, $lc;
2525                         return $log_entry;
2526                 }
2527                 $ed = SVN::Git::Fetcher->new($self);
2528                 $last_rev = $self->{last_rev};
2529                 $ed->{c} = $lc;
2530                 @parents = ($lc);
2531         } else {
2532                 $last_rev = $rev;
2533                 if (my $log_entry = $self->find_parent_branch($paths, $rev)) {
2534                         return $log_entry;
2535                 }
2536                 $ed = SVN::Git::Fetcher->new($self);
2537         }
2538         unless ($self->ra->gs_do_update($last_rev, $rev, $self, $ed)) {
2539                 die "SVN connection failed somewhere...\n";
2540         }
2541         $self->make_log_entry($rev, \@parents, $ed);
2544 sub get_untracked {
2545         my ($self, $ed) = @_;
2546         my @out;
2547         my $h = $ed->{empty};
2548         foreach (sort keys %$h) {
2549                 my $act = $h->{$_} ? '+empty_dir' : '-empty_dir';
2550                 push @out, "  $act: " . uri_encode($_);
2551                 warn "W: $act: $_\n";
2552         }
2553         foreach my $t (qw/dir_prop file_prop/) {
2554                 $h = $ed->{$t} or next;
2555                 foreach my $path (sort keys %$h) {
2556                         my $ppath = $path eq '' ? '.' : $path;
2557                         foreach my $prop (sort keys %{$h->{$path}}) {
2558                                 next if $SKIP_PROP{$prop};
2559                                 my $v = $h->{$path}->{$prop};
2560                                 my $t_ppath_prop = "$t: " .
2561                                                     uri_encode($ppath) . ' ' .
2562                                                     uri_encode($prop);
2563                                 if (defined $v) {
2564                                         push @out, "  +$t_ppath_prop " .
2565                                                    uri_encode($v);
2566                                 } else {
2567                                         push @out, "  -$t_ppath_prop";
2568                                 }
2569                         }
2570                 }
2571         }
2572         foreach my $t (qw/absent_file absent_directory/) {
2573                 $h = $ed->{$t} or next;
2574                 foreach my $parent (sort keys %$h) {
2575                         foreach my $path (sort @{$h->{$parent}}) {
2576                                 push @out, "  $t: " .
2577                                            uri_encode("$parent/$path");
2578                                 warn "W: $t: $parent/$path ",
2579                                      "Insufficient permissions?\n";
2580                         }
2581                 }
2582         }
2583         \@out;
2586 # parse_svn_date(DATE)
2587 # --------------------
2588 # Given a date (in UTC) from Subversion, return a string in the format
2589 # "<TZ Offset> <local date/time>" that Git will use.
2591 # By default the parsed date will be in UTC; if $Git::SVN::_localtime
2592 # is true we'll convert it to the local timezone instead.
2593 sub parse_svn_date {
2594         my $date = shift || return '+0000 1970-01-01 00:00:00';
2595         my ($Y,$m,$d,$H,$M,$S) = ($date =~ /^(\d{4})\-(\d\d)\-(\d\d)T
2596                                             (\d\d)\:(\d\d)\:(\d\d)\.\d*Z$/x) or
2597                                          croak "Unable to parse date: $date\n";
2598         my $parsed_date;    # Set next.
2600         if ($Git::SVN::_localtime) {
2601                 # Translate the Subversion datetime to an epoch time.
2602                 # Begin by switching ourselves to $date's timezone, UTC.
2603                 my $old_env_TZ = $ENV{TZ};
2604                 $ENV{TZ} = 'UTC';
2606                 my $epoch_in_UTC =
2607                     POSIX::strftime('%s', $S, $M, $H, $d, $m - 1, $Y - 1900);
2609                 # Determine our local timezone (including DST) at the
2610                 # time of $epoch_in_UTC.  $Git::SVN::Log::TZ stored the
2611                 # value of TZ, if any, at the time we were run.
2612                 if (defined $Git::SVN::Log::TZ) {
2613                         $ENV{TZ} = $Git::SVN::Log::TZ;
2614                 } else {
2615                         delete $ENV{TZ};
2616                 }
2618                 my $our_TZ =
2619                     POSIX::strftime('%Z', $S, $M, $H, $d, $m - 1, $Y - 1900);
2621                 # This converts $epoch_in_UTC into our local timezone.
2622                 my ($sec, $min, $hour, $mday, $mon, $year,
2623                     $wday, $yday, $isdst) = localtime($epoch_in_UTC);
2625                 $parsed_date = sprintf('%s %04d-%02d-%02d %02d:%02d:%02d',
2626                                        $our_TZ, $year + 1900, $mon + 1,
2627                                        $mday, $hour, $min, $sec);
2629                 # Reset us to the timezone in effect when we entered
2630                 # this routine.
2631                 if (defined $old_env_TZ) {
2632                         $ENV{TZ} = $old_env_TZ;
2633                 } else {
2634                         delete $ENV{TZ};
2635                 }
2636         } else {
2637                 $parsed_date = "+0000 $Y-$m-$d $H:$M:$S";
2638         }
2640         return $parsed_date;
2643 sub other_gs {
2644         my ($self, $new_url, $url, $repos_root,
2645             $branch_from, $r, $old_ref_id) = @_;
2646         my $gs = Git::SVN->find_by_url($new_url, $repos_root, $branch_from);
2647         unless ($gs) {
2648                 my $ref_id = $old_ref_id;
2649                 $ref_id =~ s/\@\d+$//;
2650                 $ref_id .= "\@$r";
2651                 # just grow a tail if we're not unique enough :x
2652                 $ref_id .= '-' while find_ref($ref_id);
2653                 print STDERR "Initializing parent: $ref_id\n";
2654                 my ($u, $p, $repo_id) = ($new_url, '', $ref_id);
2655                 if ($u =~ s#^\Q$url\E(/|$)##) {
2656                         $p = $u;
2657                         $u = $url;
2658                         $repo_id = $self->{repo_id};
2659                 }
2660                 $gs = Git::SVN->init($u, $p, $repo_id, $ref_id, 1);
2661         }
2662         $gs
2665 sub check_author {
2666         my ($author) = @_;
2667         if (!defined $author || length $author == 0) {
2668                 $author = '(no author)';
2669         } elsif (defined $::_authors && ! defined $::users{$author}) {
2670                 die "Author: $author not defined in $::_authors file\n";
2671         }
2672         $author;
2675 sub make_log_entry {
2676         my ($self, $rev, $parents, $ed) = @_;
2677         my $untracked = $self->get_untracked($ed);
2679         open my $un, '>>', "$self->{dir}/unhandled.log" or croak $!;
2680         print $un "r$rev\n" or croak $!;
2681         print $un $_, "\n" foreach @$untracked;
2682         my %log_entry = ( parents => $parents || [], revision => $rev,
2683                           log => '');
2685         my $headrev;
2686         my $logged = delete $self->{logged_rev_props};
2687         if (!$logged || $self->{-want_revprops}) {
2688                 my $rp = $self->ra->rev_proplist($rev);
2689                 foreach (sort keys %$rp) {
2690                         my $v = $rp->{$_};
2691                         if (/^svn:(author|date|log)$/) {
2692                                 $log_entry{$1} = $v;
2693                         } elsif ($_ eq 'svm:headrev') {
2694                                 $headrev = $v;
2695                         } else {
2696                                 print $un "  rev_prop: ", uri_encode($_), ' ',
2697                                           uri_encode($v), "\n";
2698                         }
2699                 }
2700         } else {
2701                 map { $log_entry{$_} = $logged->{$_} } keys %$logged;
2702         }
2703         close $un or croak $!;
2705         $log_entry{date} = parse_svn_date($log_entry{date});
2706         $log_entry{log} .= "\n";
2707         my $author = $log_entry{author} = check_author($log_entry{author});
2708         my ($name, $email) = defined $::users{$author} ? @{$::users{$author}}
2709                                                        : ($author, undef);
2711         my ($commit_name, $commit_email) = ($name, $email);
2712         if ($_use_log_author) {
2713                 my $name_field;
2714                 if ($log_entry{log} =~ /From:\s+(.*\S)\s*\n/i) {
2715                         $name_field = $1;
2716                 } elsif ($log_entry{log} =~ /Signed-off-by:\s+(.*\S)\s*\n/i) {
2717                         $name_field = $1;
2718                 }
2719                 if (!defined $name_field) {
2720                         if (!defined $email) {
2721                                 $email = $name;
2722                         }
2723                 } elsif ($name_field =~ /(.*?)\s+<(.*)>/) {
2724                         ($name, $email) = ($1, $2);
2725                 } elsif ($name_field =~ /(.*)@/) {
2726                         ($name, $email) = ($1, $name_field);
2727                 } else {
2728                         ($name, $email) = ($name_field, $name_field);
2729                 }
2730         }
2731         if (defined $headrev && $self->use_svm_props) {
2732                 if ($self->rewrite_root) {
2733                         die "Can't have both 'useSvmProps' and 'rewriteRoot' ",
2734                             "options set!\n";
2735                 }
2736                 my ($uuid, $r) = $headrev =~ m{^([a-f\d\-]{30,}):(\d+)$};
2737                 # we don't want "SVM: initializing mirror for junk" ...
2738                 return undef if $r == 0;
2739                 my $svm = $self->svm;
2740                 if ($uuid ne $svm->{uuid}) {
2741                         die "UUID mismatch on SVM path:\n",
2742                             "expected: $svm->{uuid}\n",
2743                             "     got: $uuid\n";
2744                 }
2745                 my $full_url = $self->full_url;
2746                 $full_url =~ s#^\Q$svm->{replace}\E(/|$)#$svm->{source}$1# or
2747                              die "Failed to replace '$svm->{replace}' with ",
2748                                  "'$svm->{source}' in $full_url\n";
2749                 # throw away username for storing in records
2750                 remove_username($full_url);
2751                 $log_entry{metadata} = "$full_url\@$r $uuid";
2752                 $log_entry{svm_revision} = $r;
2753                 $email ||= "$author\@$uuid";
2754                 $commit_email ||= "$author\@$uuid";
2755         } elsif ($self->use_svnsync_props) {
2756                 my $full_url = $self->svnsync->{url};
2757                 $full_url .= "/$self->{path}" if length $self->{path};
2758                 remove_username($full_url);
2759                 my $uuid = $self->svnsync->{uuid};
2760                 $log_entry{metadata} = "$full_url\@$rev $uuid";
2761                 $email ||= "$author\@$uuid";
2762                 $commit_email ||= "$author\@$uuid";
2763         } else {
2764                 my $url = $self->metadata_url;
2765                 remove_username($url);
2766                 $log_entry{metadata} = "$url\@$rev " .
2767                                        $self->ra->get_uuid;
2768                 $email ||= "$author\@" . $self->ra->get_uuid;
2769                 $commit_email ||= "$author\@" . $self->ra->get_uuid;
2770         }
2771         $log_entry{name} = $name;
2772         $log_entry{email} = $email;
2773         $log_entry{commit_name} = $commit_name;
2774         $log_entry{commit_email} = $commit_email;
2775         \%log_entry;
2778 sub fetch {
2779         my ($self, $min_rev, $max_rev, @parents) = @_;
2780         my ($last_rev, $last_commit) = $self->last_rev_commit;
2781         my ($base, $head) = $self->get_fetch_range($min_rev, $max_rev);
2782         $self->ra->gs_fetch_loop_common($base, $head, [$self]);
2785 sub set_tree_cb {
2786         my ($self, $log_entry, $tree, $rev, $date, $author) = @_;
2787         $self->{inject_parents} = { $rev => $tree };
2788         $self->fetch(undef, undef);
2791 sub set_tree {
2792         my ($self, $tree) = (shift, shift);
2793         my $log_entry = ::get_commit_entry($tree);
2794         unless ($self->{last_rev}) {
2795                 ::fatal("Must have an existing revision to commit");
2796         }
2797         my %ed_opts = ( r => $self->{last_rev},
2798                         log => $log_entry->{log},
2799                         ra => $self->ra,
2800                         tree_a => $self->{last_commit},
2801                         tree_b => $tree,
2802                         editor_cb => sub {
2803                                $self->set_tree_cb($log_entry, $tree, @_) },
2804                         svn_path => $self->{path} );
2805         if (!SVN::Git::Editor->new(\%ed_opts)->apply_diff) {
2806                 print "No changes\nr$self->{last_rev} = $tree\n";
2807         }
2810 sub rebuild_from_rev_db {
2811         my ($self, $path) = @_;
2812         my $r = -1;
2813         open my $fh, '<', $path or croak "open: $!";
2814         binmode $fh or croak "binmode: $!";
2815         while (<$fh>) {
2816                 length($_) == 41 or croak "inconsistent size in ($_) != 41";
2817                 chomp($_);
2818                 ++$r;
2819                 next if $_ eq ('0' x 40);
2820                 $self->rev_map_set($r, $_);
2821                 print "r$r = $_\n";
2822         }
2823         close $fh or croak "close: $!";
2824         unlink $path or croak "unlink: $!";
2827 sub rebuild {
2828         my ($self) = @_;
2829         my $map_path = $self->map_path;
2830         my $partial = (-e $map_path && ! -z $map_path);
2831         return unless ::verify_ref($self->refname.'^0');
2832         if (!$partial && ($self->use_svm_props || $self->no_metadata)) {
2833                 my $rev_db = $self->rev_db_path;
2834                 $self->rebuild_from_rev_db($rev_db);
2835                 if ($self->use_svm_props) {
2836                         my $svm_rev_db = $self->rev_db_path($self->svm_uuid);
2837                         $self->rebuild_from_rev_db($svm_rev_db);
2838                 }
2839                 $self->unlink_rev_db_symlink;
2840                 return;
2841         }
2842         print "Rebuilding $map_path ...\n" if (!$partial);
2843         my ($base_rev, $head) = ($partial ? $self->rev_map_max_norebuild(1) :
2844                 (undef, undef));
2845         my ($log, $ctx) =
2846             command_output_pipe(qw/rev-list --pretty=raw --no-color --reverse/,
2847                                 ($head ? "$head.." : "") . $self->refname,
2848                                 '--');
2849         my $metadata_url = $self->metadata_url;
2850         remove_username($metadata_url);
2851         my $svn_uuid = $self->ra_uuid;
2852         my $c;
2853         while (<$log>) {
2854                 if ( m{^commit ($::sha1)$} ) {
2855                         $c = $1;
2856                         next;
2857                 }
2858                 next unless s{^\s*(git-svn-id:)}{$1};
2859                 my ($url, $rev, $uuid) = ::extract_metadata($_);
2860                 remove_username($url);
2862                 # ignore merges (from set-tree)
2863                 next if (!defined $rev || !$uuid);
2865                 # if we merged or otherwise started elsewhere, this is
2866                 # how we break out of it
2867                 if (($uuid ne $svn_uuid) ||
2868                     ($metadata_url && $url && ($url ne $metadata_url))) {
2869                         next;
2870                 }
2871                 if ($partial && $head) {
2872                         print "Partial-rebuilding $map_path ...\n";
2873                         print "Currently at $base_rev = $head\n";
2874                         $head = undef;
2875                 }
2877                 $self->rev_map_set($rev, $c);
2878                 print "r$rev = $c\n";
2879         }
2880         command_close_pipe($log, $ctx);
2881         print "Done rebuilding $map_path\n" if (!$partial || !$head);
2882         my $rev_db_path = $self->rev_db_path;
2883         if (-f $self->rev_db_path) {
2884                 unlink $self->rev_db_path or croak "unlink: $!";
2885         }
2886         $self->unlink_rev_db_symlink;
2889 # rev_map:
2890 # Tie::File seems to be prone to offset errors if revisions get sparse,
2891 # it's not that fast, either.  Tie::File is also not in Perl 5.6.  So
2892 # one of my favorite modules is out :<  Next up would be one of the DBM
2893 # modules, but I'm not sure which is most portable...
2895 # This is the replacement for the rev_db format, which was too big
2896 # and inefficient for large repositories with a lot of sparse history
2897 # (mainly tags)
2899 # The format is this:
2900 #   - 24 bytes for every record,
2901 #     * 4 bytes for the integer representing an SVN revision number
2902 #     * 20 bytes representing the sha1 of a git commit
2903 #   - No empty padding records like the old format
2904 #     (except the last record, which can be overwritten)
2905 #   - new records are written append-only since SVN revision numbers
2906 #     increase monotonically
2907 #   - lookups on SVN revision number are done via a binary search
2908 #   - Piping the file to xxd -c24 is a good way of dumping it for
2909 #     viewing or editing (piped back through xxd -r), should the need
2910 #     ever arise.
2911 #   - The last record can be padding revision with an all-zero sha1
2912 #     This is used to optimize fetch performance when using multiple
2913 #     "fetch" directives in .git/config
2915 # These files are disposable unless noMetadata or useSvmProps is set
2917 sub _rev_map_set {
2918         my ($fh, $rev, $commit) = @_;
2920         binmode $fh or croak "binmode: $!";
2921         my $size = (stat($fh))[7];
2922         ($size % 24) == 0 or croak "inconsistent size: $size";
2924         my $wr_offset = 0;
2925         if ($size > 0) {
2926                 sysseek($fh, -24, SEEK_END) or croak "seek: $!";
2927                 my $read = sysread($fh, my $buf, 24) or croak "read: $!";
2928                 $read == 24 or croak "read only $read bytes (!= 24)";
2929                 my ($last_rev, $last_commit) = unpack(rev_map_fmt, $buf);
2930                 if ($last_commit eq ('0' x40)) {
2931                         if ($size >= 48) {
2932                                 sysseek($fh, -48, SEEK_END) or croak "seek: $!";
2933                                 $read = sysread($fh, $buf, 24) or
2934                                     croak "read: $!";
2935                                 $read == 24 or
2936                                     croak "read only $read bytes (!= 24)";
2937                                 ($last_rev, $last_commit) =
2938                                     unpack(rev_map_fmt, $buf);
2939                                 if ($last_commit eq ('0' x40)) {
2940                                         croak "inconsistent .rev_map\n";
2941                                 }
2942                         }
2943                         if ($last_rev >= $rev) {
2944                                 croak "last_rev is higher!: $last_rev >= $rev";
2945                         }
2946                         $wr_offset = -24;
2947                 }
2948         }
2949         sysseek($fh, $wr_offset, SEEK_END) or croak "seek: $!";
2950         syswrite($fh, pack(rev_map_fmt, $rev, $commit), 24) == 24 or
2951           croak "write: $!";
2954 sub mkfile {
2955         my ($path) = @_;
2956         unless (-e $path) {
2957                 my ($dir, $base) = ($path =~ m#^(.*?)/?([^/]+)$#);
2958                 mkpath([$dir]) unless -d $dir;
2959                 open my $fh, '>>', $path or die "Couldn't create $path: $!\n";
2960                 close $fh or die "Couldn't close (create) $path: $!\n";
2961         }
2964 sub rev_map_set {
2965         my ($self, $rev, $commit, $update_ref, $uuid) = @_;
2966         length $commit == 40 or die "arg3 must be a full SHA1 hexsum\n";
2967         my $db = $self->map_path($uuid);
2968         my $db_lock = "$db.lock";
2969         my $sig;
2970         if ($update_ref) {
2971                 $SIG{INT} = $SIG{HUP} = $SIG{TERM} = $SIG{ALRM} = $SIG{PIPE} =
2972                             $SIG{USR1} = $SIG{USR2} = sub { $sig = $_[0] };
2973         }
2974         mkfile($db);
2976         $LOCKFILES{$db_lock} = 1;
2977         my $sync;
2978         # both of these options make our .rev_db file very, very important
2979         # and we can't afford to lose it because rebuild() won't work
2980         if ($self->use_svm_props || $self->no_metadata) {
2981                 $sync = 1;
2982                 copy($db, $db_lock) or die "rev_map_set(@_): ",
2983                                            "Failed to copy: ",
2984                                            "$db => $db_lock ($!)\n";
2985         } else {
2986                 rename $db, $db_lock or die "rev_map_set(@_): ",
2987                                             "Failed to rename: ",
2988                                             "$db => $db_lock ($!)\n";
2989         }
2991         sysopen(my $fh, $db_lock, O_RDWR | O_CREAT)
2992              or croak "Couldn't open $db_lock: $!\n";
2993         _rev_map_set($fh, $rev, $commit);
2994         if ($sync) {
2995                 $fh->flush or die "Couldn't flush $db_lock: $!\n";
2996                 $fh->sync or die "Couldn't sync $db_lock: $!\n";
2997         }
2998         close $fh or croak $!;
2999         if ($update_ref) {
3000                 $_head = $self;
3001                 command_noisy('update-ref', '-m', "r$rev",
3002                               $self->refname, $commit);
3003         }
3004         rename $db_lock, $db or die "rev_map_set(@_): ", "Failed to rename: ",
3005                                     "$db_lock => $db ($!)\n";
3006         delete $LOCKFILES{$db_lock};
3007         if ($update_ref) {
3008                 $SIG{INT} = $SIG{HUP} = $SIG{TERM} = $SIG{ALRM} = $SIG{PIPE} =
3009                             $SIG{USR1} = $SIG{USR2} = 'DEFAULT';
3010                 kill $sig, $$ if defined $sig;
3011         }
3014 # If want_commit, this will return an array of (rev, commit) where
3015 # commit _must_ be a valid commit in the archive.
3016 # Otherwise, it'll return the max revision (whether or not the
3017 # commit is valid or just a 0x40 placeholder).
3018 sub rev_map_max {
3019         my ($self, $want_commit) = @_;
3020         $self->rebuild;
3021         my ($r, $c) = $self->rev_map_max_norebuild($want_commit);
3022         $want_commit ? ($r, $c) : $r;
3025 sub rev_map_max_norebuild {
3026         my ($self, $want_commit) = @_;
3027         my $map_path = $self->map_path;
3028         stat $map_path or return $want_commit ? (0, undef) : 0;
3029         sysopen(my $fh, $map_path, O_RDONLY) or croak "open: $!";
3030         binmode $fh or croak "binmode: $!";
3031         my $size = (stat($fh))[7];
3032         ($size % 24) == 0 or croak "inconsistent size: $size";
3034         if ($size == 0) {
3035                 close $fh or croak "close: $!";
3036                 return $want_commit ? (0, undef) : 0;
3037         }
3039         sysseek($fh, -24, SEEK_END) or croak "seek: $!";
3040         sysread($fh, my $buf, 24) == 24 or croak "read: $!";
3041         my ($r, $c) = unpack(rev_map_fmt, $buf);
3042         if ($want_commit && $c eq ('0' x40)) {
3043                 if ($size < 48) {
3044                         return $want_commit ? (0, undef) : 0;
3045                 }
3046                 sysseek($fh, -48, SEEK_END) or croak "seek: $!";
3047                 sysread($fh, $buf, 24) == 24 or croak "read: $!";
3048                 ($r, $c) = unpack(rev_map_fmt, $buf);
3049                 if ($c eq ('0'x40)) {
3050                         croak "Penultimate record is all-zeroes in $map_path";
3051                 }
3052         }
3053         close $fh or croak "close: $!";
3054         $want_commit ? ($r, $c) : $r;
3057 sub rev_map_get {
3058         my ($self, $rev, $uuid) = @_;
3059         my $map_path = $self->map_path($uuid);
3060         return undef unless -e $map_path;
3062         sysopen(my $fh, $map_path, O_RDONLY) or croak "open: $!";
3063         binmode $fh or croak "binmode: $!";
3064         my $size = (stat($fh))[7];
3065         ($size % 24) == 0 or croak "inconsistent size: $size";
3067         if ($size == 0) {
3068                 close $fh or croak "close: $fh";
3069                 return undef;
3070         }
3072         my ($l, $u) = (0, $size - 24);
3073         my ($r, $c, $buf);
3075         while ($l <= $u) {
3076                 my $i = int(($l/24 + $u/24) / 2) * 24;
3077                 sysseek($fh, $i, SEEK_SET) or croak "seek: $!";
3078                 sysread($fh, my $buf, 24) == 24 or croak "read: $!";
3079                 my ($r, $c) = unpack('NH40', $buf);
3081                 if ($r < $rev) {
3082                         $l = $i + 24;
3083                 } elsif ($r > $rev) {
3084                         $u = $i - 24;
3085                 } else { # $r == $rev
3086                         close($fh) or croak "close: $!";
3087                         return $c eq ('0' x 40) ? undef : $c;
3088                 }
3089         }
3090         close($fh) or croak "close: $!";
3091         undef;
3094 # Finds the first svn revision that exists on (if $eq_ok is true) or
3095 # before $rev for the current branch.  It will not search any lower
3096 # than $min_rev.  Returns the git commit hash and svn revision number
3097 # if found, else (undef, undef).
3098 sub find_rev_before {
3099         my ($self, $rev, $eq_ok, $min_rev) = @_;
3100         --$rev unless $eq_ok;
3101         $min_rev ||= 1;
3102         while ($rev >= $min_rev) {
3103                 if (my $c = $self->rev_map_get($rev)) {
3104                         return ($rev, $c);
3105                 }
3106                 --$rev;
3107         }
3108         return (undef, undef);
3111 # Finds the first svn revision that exists on (if $eq_ok is true) or
3112 # after $rev for the current branch.  It will not search any higher
3113 # than $max_rev.  Returns the git commit hash and svn revision number
3114 # if found, else (undef, undef).
3115 sub find_rev_after {
3116         my ($self, $rev, $eq_ok, $max_rev) = @_;
3117         ++$rev unless $eq_ok;
3118         $max_rev ||= $self->rev_map_max;
3119         while ($rev <= $max_rev) {
3120                 if (my $c = $self->rev_map_get($rev)) {
3121                         return ($rev, $c);
3122                 }
3123                 ++$rev;
3124         }
3125         return (undef, undef);
3128 sub _new {
3129         my ($class, $repo_id, $ref_id, $path) = @_;
3130         unless (defined $repo_id && length $repo_id) {
3131                 $repo_id = $Git::SVN::default_repo_id;
3132         }
3133         unless (defined $ref_id && length $ref_id) {
3134                 $_[2] = $ref_id = $Git::SVN::default_ref_id;
3135         }
3136         $_[1] = $repo_id;
3137         my $dir = "$ENV{GIT_DIR}/svn/$ref_id";
3138         $_[3] = $path = '' unless (defined $path);
3139         mkpath(["$ENV{GIT_DIR}/svn"]);
3140         bless {
3141                 ref_id => $ref_id, dir => $dir, index => "$dir/index",
3142                 path => $path, config => "$ENV{GIT_DIR}/svn/config",
3143                 map_root => "$dir/.rev_map", repo_id => $repo_id }, $class;
3146 # for read-only access of old .rev_db formats
3147 sub unlink_rev_db_symlink {
3148         my ($self) = @_;
3149         my $link = $self->rev_db_path;
3150         $link =~ s/\.[\w-]+$// or croak "missing UUID at the end of $link";
3151         if (-l $link) {
3152                 unlink $link or croak "unlink: $link failed!";
3153         }
3156 sub rev_db_path {
3157         my ($self, $uuid) = @_;
3158         my $db_path = $self->map_path($uuid);
3159         $db_path =~ s{/\.rev_map\.}{/\.rev_db\.}
3160             or croak "map_path: $db_path does not contain '/.rev_map.' !";
3161         $db_path;
3164 # the new replacement for .rev_db
3165 sub map_path {
3166         my ($self, $uuid) = @_;
3167         $uuid ||= $self->ra_uuid;
3168         "$self->{map_root}.$uuid";
3171 sub uri_encode {
3172         my ($f) = @_;
3173         $f =~ s#([^a-zA-Z0-9\*!\:_\./\-])#uc sprintf("%%%02x",ord($1))#eg;
3174         $f
3177 sub remove_username {
3178         $_[0] =~ s{^([^:]*://)[^@]+@}{$1};
3181 package Git::SVN::Prompt;
3182 use strict;
3183 use warnings;
3184 require SVN::Core;
3185 use vars qw/$_no_auth_cache $_username/;
3187 sub simple {
3188         my ($cred, $realm, $default_username, $may_save, $pool) = @_;
3189         $may_save = undef if $_no_auth_cache;
3190         $default_username = $_username if defined $_username;
3191         if (defined $default_username && length $default_username) {
3192                 if (defined $realm && length $realm) {
3193                         print STDERR "Authentication realm: $realm\n";
3194                         STDERR->flush;
3195                 }
3196                 $cred->username($default_username);
3197         } else {
3198                 username($cred, $realm, $may_save, $pool);
3199         }
3200         $cred->password(_read_password("Password for '" .
3201                                        $cred->username . "': ", $realm));
3202         $cred->may_save($may_save);
3203         $SVN::_Core::SVN_NO_ERROR;
3206 sub ssl_server_trust {
3207         my ($cred, $realm, $failures, $cert_info, $may_save, $pool) = @_;
3208         $may_save = undef if $_no_auth_cache;
3209         print STDERR "Error validating server certificate for '$realm':\n";
3210         {
3211                 no warnings 'once';
3212                 # All variables SVN::Auth::SSL::* are used only once,
3213                 # so we're shutting up Perl warnings about this.
3214                 if ($failures & $SVN::Auth::SSL::UNKNOWNCA) {
3215                         print STDERR " - The certificate is not issued ",
3216                             "by a trusted authority. Use the\n",
3217                             "   fingerprint to validate ",
3218                             "the certificate manually!\n";
3219                 }
3220                 if ($failures & $SVN::Auth::SSL::CNMISMATCH) {
3221                         print STDERR " - The certificate hostname ",
3222                             "does not match.\n";
3223                 }
3224                 if ($failures & $SVN::Auth::SSL::NOTYETVALID) {
3225                         print STDERR " - The certificate is not yet valid.\n";
3226                 }
3227                 if ($failures & $SVN::Auth::SSL::EXPIRED) {
3228                         print STDERR " - The certificate has expired.\n";
3229                 }
3230                 if ($failures & $SVN::Auth::SSL::OTHER) {
3231                         print STDERR " - The certificate has ",
3232                             "an unknown error.\n";
3233                 }
3234         } # no warnings 'once'
3235         printf STDERR
3236                 "Certificate information:\n".
3237                 " - Hostname: %s\n".
3238                 " - Valid: from %s until %s\n".
3239                 " - Issuer: %s\n".
3240                 " - Fingerprint: %s\n",
3241                 map $cert_info->$_, qw(hostname valid_from valid_until
3242                                        issuer_dname fingerprint);
3243         my $choice;
3244 prompt:
3245         print STDERR $may_save ?
3246               "(R)eject, accept (t)emporarily or accept (p)ermanently? " :
3247               "(R)eject or accept (t)emporarily? ";
3248         STDERR->flush;
3249         $choice = lc(substr(<STDIN> || 'R', 0, 1));
3250         if ($choice =~ /^t$/i) {
3251                 $cred->may_save(undef);
3252         } elsif ($choice =~ /^r$/i) {
3253                 return -1;
3254         } elsif ($may_save && $choice =~ /^p$/i) {
3255                 $cred->may_save($may_save);
3256         } else {
3257                 goto prompt;
3258         }
3259         $cred->accepted_failures($failures);
3260         $SVN::_Core::SVN_NO_ERROR;
3263 sub ssl_client_cert {
3264         my ($cred, $realm, $may_save, $pool) = @_;
3265         $may_save = undef if $_no_auth_cache;
3266         print STDERR "Client certificate filename: ";
3267         STDERR->flush;
3268         chomp(my $filename = <STDIN>);
3269         $cred->cert_file($filename);
3270         $cred->may_save($may_save);
3271         $SVN::_Core::SVN_NO_ERROR;
3274 sub ssl_client_cert_pw {
3275         my ($cred, $realm, $may_save, $pool) = @_;
3276         $may_save = undef if $_no_auth_cache;
3277         $cred->password(_read_password("Password: ", $realm));
3278         $cred->may_save($may_save);
3279         $SVN::_Core::SVN_NO_ERROR;
3282 sub username {
3283         my ($cred, $realm, $may_save, $pool) = @_;
3284         $may_save = undef if $_no_auth_cache;
3285         if (defined $realm && length $realm) {
3286                 print STDERR "Authentication realm: $realm\n";
3287         }
3288         my $username;
3289         if (defined $_username) {
3290                 $username = $_username;
3291         } else {
3292                 print STDERR "Username: ";
3293                 STDERR->flush;
3294                 chomp($username = <STDIN>);
3295         }
3296         $cred->username($username);
3297         $cred->may_save($may_save);
3298         $SVN::_Core::SVN_NO_ERROR;
3301 sub _read_password {
3302         my ($prompt, $realm) = @_;
3303         print STDERR $prompt;
3304         STDERR->flush;
3305         require Term::ReadKey;
3306         Term::ReadKey::ReadMode('noecho');
3307         my $password = '';
3308         while (defined(my $key = Term::ReadKey::ReadKey(0))) {
3309                 last if $key =~ /[\012\015]/; # \n\r
3310                 $password .= $key;
3311         }
3312         Term::ReadKey::ReadMode('restore');
3313         print STDERR "\n";
3314         STDERR->flush;
3315         $password;
3318 package SVN::Git::Fetcher;
3319 use vars qw/@ISA/;
3320 use strict;
3321 use warnings;
3322 use Carp qw/croak/;
3323 use File::Temp qw/tempfile/;
3324 use IO::File qw//;
3325 use vars qw/$_ignore_regex/;
3327 # file baton members: path, mode_a, mode_b, pool, fh, blob, base
3328 sub new {
3329         my ($class, $git_svn, $switch_path) = @_;
3330         my $self = SVN::Delta::Editor->new;
3331         bless $self, $class;
3332         if (exists $git_svn->{last_commit}) {
3333                 $self->{c} = $git_svn->{last_commit};
3334                 $self->{empty_symlinks} =
3335                                   _mark_empty_symlinks($git_svn, $switch_path);
3336         }
3337         $self->{ignore_regex} = eval { command_oneline('config', '--get',
3338                              "svn-remote.$git_svn->{repo_id}.ignore-paths") };
3339         $self->{empty} = {};
3340         $self->{dir_prop} = {};
3341         $self->{file_prop} = {};
3342         $self->{absent_dir} = {};
3343         $self->{absent_file} = {};
3344         $self->{gii} = $git_svn->tmp_index_do(sub { Git::IndexInfo->new });
3345         $self;
3348 # this uses the Ra object, so it must be called before do_{switch,update},
3349 # not inside them (when the Git::SVN::Fetcher object is passed) to
3350 # do_{switch,update}
3351 sub _mark_empty_symlinks {
3352         my ($git_svn, $switch_path) = @_;
3353         my $bool = Git::config_bool('svn.brokenSymlinkWorkaround');
3354         return {} if (!defined($bool)) || (defined($bool) && ! $bool);
3356         my %ret;
3357         my ($rev, $cmt) = $git_svn->last_rev_commit;
3358         return {} unless ($rev && $cmt);
3360         # allow the warning to be printed for each revision we fetch to
3361         # ensure the user sees it.  The user can also disable the workaround
3362         # on the repository even while git svn is running and the next
3363         # revision fetched will skip this expensive function.
3364         my $printed_warning;
3365         chomp(my $empty_blob = `git hash-object -t blob --stdin < /dev/null`);
3366         my ($ls, $ctx) = command_output_pipe(qw/ls-tree -r -z/, $cmt);
3367         local $/ = "\0";
3368         my $pfx = defined($switch_path) ? $switch_path : $git_svn->{path};
3369         $pfx .= '/' if length($pfx);
3370         while (<$ls>) {
3371                 chomp;
3372                 s/\A100644 blob $empty_blob\t//o or next;
3373                 unless ($printed_warning) {
3374                         print STDERR "Scanning for empty symlinks, ",
3375                                      "this may take a while if you have ",
3376                                      "many empty files\n",
3377                                      "You may disable this with `",
3378                                      "git config svn.brokenSymlinkWorkaround ",
3379                                      "false'.\n",
3380                                      "This may be done in a different ",
3381                                      "terminal without restarting ",
3382                                      "git svn\n";
3383                         $printed_warning = 1;
3384                 }
3385                 my $path = $_;
3386                 my (undef, $props) =
3387                                $git_svn->ra->get_file($pfx.$path, $rev, undef);
3388                 if ($props->{'svn:special'}) {
3389                         $ret{$path} = 1;
3390                 }
3391         }
3392         command_close_pipe($ls, $ctx);
3393         \%ret;
3396 # returns true if a given path is inside a ".git" directory
3397 sub in_dot_git {
3398         $_[0] =~ m{(?:^|/)\.git(?:/|$)};
3401 # return value: 0 -- don't ignore, 1 -- ignore
3402 sub is_path_ignored {
3403         my ($self, $path) = @_;
3404         return 1 if in_dot_git($path);
3405         return 1 if defined($self->{ignore_regex}) &&
3406                     $path =~ m!$self->{ignore_regex}!;
3407         return 0 unless defined($_ignore_regex);
3408         return 1 if $path =~ m!$_ignore_regex!o;
3409         return 0;
3412 sub set_path_strip {
3413         my ($self, $path) = @_;
3414         $self->{path_strip} = qr/^\Q$path\E(\/|$)/ if length $path;
3417 sub open_root {
3418         { path => '' };
3421 sub open_directory {
3422         my ($self, $path, $pb, $rev) = @_;
3423         { path => $path };
3426 sub git_path {
3427         my ($self, $path) = @_;
3428         if ($self->{path_strip}) {
3429                 $path =~ s!$self->{path_strip}!! or
3430                   die "Failed to strip path '$path' ($self->{path_strip})\n";
3431         }
3432         $path;
3435 sub delete_entry {
3436         my ($self, $path, $rev, $pb) = @_;
3437         return undef if $self->is_path_ignored($path);
3439         my $gpath = $self->git_path($path);
3440         return undef if ($gpath eq '');
3442         # remove entire directories.
3443         my ($tree) = (command('ls-tree', '-z', $self->{c}, "./$gpath")
3444                          =~ /\A040000 tree ([a-f\d]{40})\t\Q$gpath\E\0/);
3445         if ($tree) {
3446                 my ($ls, $ctx) = command_output_pipe(qw/ls-tree
3447                                                      -r --name-only -z/,
3448                                                      $tree);
3449                 local $/ = "\0";
3450                 while (<$ls>) {
3451                         chomp;
3452                         my $rmpath = "$gpath/$_";
3453                         $self->{gii}->remove($rmpath);
3454                         print "\tD\t$rmpath\n" unless $::_q;
3455                 }
3456                 print "\tD\t$gpath/\n" unless $::_q;
3457                 command_close_pipe($ls, $ctx);
3458                 $self->{empty}->{$path} = 0
3459         } else {
3460                 $self->{gii}->remove($gpath);
3461                 print "\tD\t$gpath\n" unless $::_q;
3462         }
3463         undef;
3466 sub open_file {
3467         my ($self, $path, $pb, $rev) = @_;
3468         my ($mode, $blob);
3470         goto out if $self->is_path_ignored($path);
3472         my $gpath = $self->git_path($path);
3473         ($mode, $blob) = (command('ls-tree', '-z', $self->{c}, "./$gpath")
3474                              =~ /\A(\d{6}) blob ([a-f\d]{40})\t\Q$gpath\E\0/);
3475         unless (defined $mode && defined $blob) {
3476                 die "$path was not found in commit $self->{c} (r$rev)\n";
3477         }
3478         if ($mode eq '100644' && $self->{empty_symlinks}->{$path}) {
3479                 $mode = '120000';
3480         }
3481 out:
3482         { path => $path, mode_a => $mode, mode_b => $mode, blob => $blob,
3483           pool => SVN::Pool->new, action => 'M' };
3486 sub add_file {
3487         my ($self, $path, $pb, $cp_path, $cp_rev) = @_;
3488         my $mode;
3490         if (!$self->is_path_ignored($path)) {
3491                 my ($dir, $file) = ($path =~ m#^(.*?)/?([^/]+)$#);
3492                 delete $self->{empty}->{$dir};
3493                 $mode = '100644';
3494         }
3495         { path => $path, mode_a => $mode, mode_b => $mode,
3496           pool => SVN::Pool->new, action => 'A' };
3499 sub add_directory {
3500         my ($self, $path, $cp_path, $cp_rev) = @_;
3501         goto out if $self->is_path_ignored($path);
3502         my $gpath = $self->git_path($path);
3503         if ($gpath eq '') {
3504                 my ($ls, $ctx) = command_output_pipe(qw/ls-tree
3505                                                      -r --name-only -z/,
3506                                                      $self->{c});
3507                 local $/ = "\0";
3508                 while (<$ls>) {
3509                         chomp;
3510                         $self->{gii}->remove($_);
3511                         print "\tD\t$_\n" unless $::_q;
3512                 }
3513                 command_close_pipe($ls, $ctx);
3514                 $self->{empty}->{$path} = 0;
3515         }
3516         my ($dir, $file) = ($path =~ m#^(.*?)/?([^/]+)$#);
3517         delete $self->{empty}->{$dir};
3518         $self->{empty}->{$path} = 1;
3519 out:
3520         { path => $path };
3523 sub change_dir_prop {
3524         my ($self, $db, $prop, $value) = @_;
3525         return undef if $self->is_path_ignored($db->{path});
3526         $self->{dir_prop}->{$db->{path}} ||= {};
3527         $self->{dir_prop}->{$db->{path}}->{$prop} = $value;
3528         undef;
3531 sub absent_directory {
3532         my ($self, $path, $pb) = @_;
3533         return undef if $self->is_path_ignored($path);
3534         $self->{absent_dir}->{$pb->{path}} ||= [];
3535         push @{$self->{absent_dir}->{$pb->{path}}}, $path;
3536         undef;
3539 sub absent_file {
3540         my ($self, $path, $pb) = @_;
3541         return undef if $self->is_path_ignored($path);
3542         $self->{absent_file}->{$pb->{path}} ||= [];
3543         push @{$self->{absent_file}->{$pb->{path}}}, $path;
3544         undef;
3547 sub change_file_prop {
3548         my ($self, $fb, $prop, $value) = @_;
3549         return undef if $self->is_path_ignored($fb->{path});
3550         if ($prop eq 'svn:executable') {
3551                 if ($fb->{mode_b} != 120000) {
3552                         $fb->{mode_b} = defined $value ? 100755 : 100644;
3553                 }
3554         } elsif ($prop eq 'svn:special') {
3555                 $fb->{mode_b} = defined $value ? 120000 : 100644;
3556         } else {
3557                 $self->{file_prop}->{$fb->{path}} ||= {};
3558                 $self->{file_prop}->{$fb->{path}}->{$prop} = $value;
3559         }
3560         undef;
3563 sub apply_textdelta {
3564         my ($self, $fb, $exp) = @_;
3565         return undef if $self->is_path_ignored($fb->{path});
3566         my $fh = $::_repository->temp_acquire('svn_delta');
3567         # $fh gets auto-closed() by SVN::TxDelta::apply(),
3568         # (but $base does not,) so dup() it for reading in close_file
3569         open my $dup, '<&', $fh or croak $!;
3570         my $base = $::_repository->temp_acquire('git_blob');
3572         if ($fb->{blob}) {
3573                 my ($base_is_link, $size);
3575                 if ($fb->{mode_a} eq '120000' &&
3576                     ! $self->{empty_symlinks}->{$fb->{path}}) {
3577                         print $base 'link ' or die "print $!\n";
3578                         $base_is_link = 1;
3579                 }
3580         retry:
3581                 $size = $::_repository->cat_blob($fb->{blob}, $base);
3582                 die "Failed to read object $fb->{blob}" if ($size < 0);
3584                 if (defined $exp) {
3585                         seek $base, 0, 0 or croak $!;
3586                         my $got = ::md5sum($base);
3587                         if ($got ne $exp) {
3588                                 my $err = "Checksum mismatch: ".
3589                                        "$fb->{path} $fb->{blob}\n" .
3590                                        "expected: $exp\n" .
3591                                        "     got: $got\n";
3592                                 if ($base_is_link) {
3593                                         warn $err,
3594                                              "Retrying... (possibly ",
3595                                              "a bad symlink from SVN)\n";
3596                                         $::_repository->temp_reset($base);
3597                                         $base_is_link = 0;
3598                                         goto retry;
3599                                 }
3600                                 die $err;
3601                         }
3602                 }
3603         }
3604         seek $base, 0, 0 or croak $!;
3605         $fb->{fh} = $fh;
3606         $fb->{base} = $base;
3607         [ SVN::TxDelta::apply($base, $dup, undef, $fb->{path}, $fb->{pool}) ];
3610 sub close_file {
3611         my ($self, $fb, $exp) = @_;
3612         return undef if $self->is_path_ignored($fb->{path});
3614         my $hash;
3615         my $path = $self->git_path($fb->{path});
3616         if (my $fh = $fb->{fh}) {
3617                 if (defined $exp) {
3618                         seek($fh, 0, 0) or croak $!;
3619                         my $got = ::md5sum($fh);
3620                         if ($got ne $exp) {
3621                                 die "Checksum mismatch: $path\n",
3622                                     "expected: $exp\n    got: $got\n";
3623                         }
3624                 }
3625                 if ($fb->{mode_b} == 120000) {
3626                         sysseek($fh, 0, 0) or croak $!;
3627                         my $rd = sysread($fh, my $buf, 5);
3629                         if (!defined $rd) {
3630                                 croak "sysread: $!\n";
3631                         } elsif ($rd == 0) {
3632                                 warn "$path has mode 120000",
3633                                      " but it points to nothing\n",
3634                                      "converting to an empty file with mode",
3635                                      " 100644\n";
3636                                 $fb->{mode_b} = '100644';
3637                         } elsif ($buf ne 'link ') {
3638                                 warn "$path has mode 120000",
3639                                      " but is not a link\n";
3640                         } else {
3641                                 my $tmp_fh = $::_repository->temp_acquire(
3642                                         'svn_hash');
3643                                 my $res;
3644                                 while ($res = sysread($fh, my $str, 1024)) {
3645                                         my $out = syswrite($tmp_fh, $str, $res);
3646                                         defined($out) && $out == $res
3647                                                 or croak("write ",
3648                                                         Git::temp_path($tmp_fh),
3649                                                         ": $!\n");
3650                                 }
3651                                 defined $res or croak $!;
3653                                 ($fh, $tmp_fh) = ($tmp_fh, $fh);
3654                                 Git::temp_release($tmp_fh, 1);
3655                         }
3656                 }
3658                 $hash = $::_repository->hash_and_insert_object(
3659                                 Git::temp_path($fh));
3660                 $hash =~ /^[a-f\d]{40}$/ or die "not a sha1: $hash\n";
3662                 Git::temp_release($fb->{base}, 1);
3663                 Git::temp_release($fh, 1);
3664         } else {
3665                 $hash = $fb->{blob} or die "no blob information\n";
3666         }
3667         $fb->{pool}->clear;
3668         $self->{gii}->update($fb->{mode_b}, $hash, $path) or croak $!;
3669         print "\t$fb->{action}\t$path\n" if $fb->{action} && ! $::_q;
3670         undef;
3673 sub abort_edit {
3674         my $self = shift;
3675         $self->{nr} = $self->{gii}->{nr};
3676         delete $self->{gii};
3677         $self->SUPER::abort_edit(@_);
3680 sub close_edit {
3681         my $self = shift;
3682         $self->{git_commit_ok} = 1;
3683         $self->{nr} = $self->{gii}->{nr};
3684         delete $self->{gii};
3685         $self->SUPER::close_edit(@_);
3688 package SVN::Git::Editor;
3689 use vars qw/@ISA $_rmdir $_cp_similarity $_find_copies_harder $_rename_limit/;
3690 use strict;
3691 use warnings;
3692 use Carp qw/croak/;
3693 use IO::File;
3695 sub new {
3696         my ($class, $opts) = @_;
3697         foreach (qw/svn_path r ra tree_a tree_b log editor_cb/) {
3698                 die "$_ required!\n" unless (defined $opts->{$_});
3699         }
3701         my $pool = SVN::Pool->new;
3702         my $mods = generate_diff($opts->{tree_a}, $opts->{tree_b});
3703         my $types = check_diff_paths($opts->{ra}, $opts->{svn_path},
3704                                      $opts->{r}, $mods);
3706         # $opts->{ra} functions should not be used after this:
3707         my @ce  = $opts->{ra}->get_commit_editor($opts->{log},
3708                                                 $opts->{editor_cb}, $pool);
3709         my $self = SVN::Delta::Editor->new(@ce, $pool);
3710         bless $self, $class;
3711         foreach (qw/svn_path r tree_a tree_b/) {
3712                 $self->{$_} = $opts->{$_};
3713         }
3714         $self->{url} = $opts->{ra}->{url};
3715         $self->{mods} = $mods;
3716         $self->{types} = $types;
3717         $self->{pool} = $pool;
3718         $self->{bat} = { '' => $self->open_root($self->{r}, $self->{pool}) };
3719         $self->{rm} = { };
3720         $self->{path_prefix} = length $self->{svn_path} ?
3721                                "$self->{svn_path}/" : '';
3722         $self->{config} = $opts->{config};
3723         return $self;
3726 sub generate_diff {
3727         my ($tree_a, $tree_b) = @_;
3728         my @diff_tree = qw(diff-tree -z -r);
3729         if ($_cp_similarity) {
3730                 push @diff_tree, "-C$_cp_similarity";
3731         } else {
3732                 push @diff_tree, '-C';
3733         }
3734         push @diff_tree, '--find-copies-harder' if $_find_copies_harder;
3735         push @diff_tree, "-l$_rename_limit" if defined $_rename_limit;
3736         push @diff_tree, $tree_a, $tree_b;
3737         my ($diff_fh, $ctx) = command_output_pipe(@diff_tree);
3738         local $/ = "\0";
3739         my $state = 'meta';
3740         my @mods;
3741         while (<$diff_fh>) {
3742                 chomp $_; # this gets rid of the trailing "\0"
3743                 if ($state eq 'meta' && /^:(\d{6})\s(\d{6})\s
3744                                         ($::sha1)\s($::sha1)\s
3745                                         ([MTCRAD])\d*$/xo) {
3746                         push @mods, {   mode_a => $1, mode_b => $2,
3747                                         sha1_a => $3, sha1_b => $4,
3748                                         chg => $5 };
3749                         if ($5 =~ /^(?:C|R)$/) {
3750                                 $state = 'file_a';
3751                         } else {
3752                                 $state = 'file_b';
3753                         }
3754                 } elsif ($state eq 'file_a') {
3755                         my $x = $mods[$#mods] or croak "Empty array\n";
3756                         if ($x->{chg} !~ /^(?:C|R)$/) {
3757                                 croak "Error parsing $_, $x->{chg}\n";
3758                         }
3759                         $x->{file_a} = $_;
3760                         $state = 'file_b';
3761                 } elsif ($state eq 'file_b') {
3762                         my $x = $mods[$#mods] or croak "Empty array\n";
3763                         if (exists $x->{file_a} && $x->{chg} !~ /^(?:C|R)$/) {
3764                                 croak "Error parsing $_, $x->{chg}\n";
3765                         }
3766                         if (!exists $x->{file_a} && $x->{chg} =~ /^(?:C|R)$/) {
3767                                 croak "Error parsing $_, $x->{chg}\n";
3768                         }
3769                         $x->{file_b} = $_;
3770                         $state = 'meta';
3771                 } else {
3772                         croak "Error parsing $_\n";
3773                 }
3774         }
3775         command_close_pipe($diff_fh, $ctx);
3776         \@mods;
3779 sub check_diff_paths {
3780         my ($ra, $pfx, $rev, $mods) = @_;
3781         my %types;
3782         $pfx .= '/' if length $pfx;
3784         sub type_diff_paths {
3785                 my ($ra, $types, $path, $rev) = @_;
3786                 my @p = split m#/+#, $path;
3787                 my $c = shift @p;
3788                 unless (defined $types->{$c}) {
3789                         $types->{$c} = $ra->check_path($c, $rev);
3790                 }
3791                 while (@p) {
3792                         $c .= '/' . shift @p;
3793                         next if defined $types->{$c};
3794                         $types->{$c} = $ra->check_path($c, $rev);
3795                 }
3796         }
3798         foreach my $m (@$mods) {
3799                 foreach my $f (qw/file_a file_b/) {
3800                         next unless defined $m->{$f};
3801                         my ($dir) = ($m->{$f} =~ m#^(.*?)/?(?:[^/]+)$#);
3802                         if (length $pfx.$dir && ! defined $types{$dir}) {
3803                                 type_diff_paths($ra, \%types, $pfx.$dir, $rev);
3804                         }
3805                 }
3806         }
3807         \%types;
3810 sub split_path {
3811         return ($_[0] =~ m#^(.*?)/?([^/]+)$#);
3814 sub repo_path {
3815         my ($self, $path) = @_;
3816         $self->{path_prefix}.(defined $path ? $path : '');
3819 sub url_path {
3820         my ($self, $path) = @_;
3821         if ($self->{url} =~ m#^https?://#) {
3822                 $path =~ s/([^~a-zA-Z0-9_.-])/uc sprintf("%%%02x",ord($1))/eg;
3823         }
3824         $self->{url} . '/' . $self->repo_path($path);
3827 sub rmdirs {
3828         my ($self) = @_;
3829         my $rm = $self->{rm};
3830         delete $rm->{''}; # we never delete the url we're tracking
3831         return unless %$rm;
3833         foreach (keys %$rm) {
3834                 my @d = split m#/#, $_;
3835                 my $c = shift @d;
3836                 $rm->{$c} = 1;
3837                 while (@d) {
3838                         $c .= '/' . shift @d;
3839                         $rm->{$c} = 1;
3840                 }
3841         }
3842         delete $rm->{$self->{svn_path}};
3843         delete $rm->{''}; # we never delete the url we're tracking
3844         return unless %$rm;
3846         my ($fh, $ctx) = command_output_pipe(qw/ls-tree --name-only -r -z/,
3847                                              $self->{tree_b});
3848         local $/ = "\0";
3849         while (<$fh>) {
3850                 chomp;
3851                 my @dn = split m#/#, $_;
3852                 while (pop @dn) {
3853                         delete $rm->{join '/', @dn};
3854                 }
3855                 unless (%$rm) {
3856                         close $fh;
3857                         return;
3858                 }
3859         }
3860         command_close_pipe($fh, $ctx);
3862         my ($r, $p, $bat) = ($self->{r}, $self->{pool}, $self->{bat});
3863         foreach my $d (sort { $b =~ tr#/#/# <=> $a =~ tr#/#/# } keys %$rm) {
3864                 $self->close_directory($bat->{$d}, $p);
3865                 my ($dn) = ($d =~ m#^(.*?)/?(?:[^/]+)$#);
3866                 print "\tD+\t$d/\n" unless $::_q;
3867                 $self->SUPER::delete_entry($d, $r, $bat->{$dn}, $p);
3868                 delete $bat->{$d};
3869         }
3872 sub open_or_add_dir {
3873         my ($self, $full_path, $baton) = @_;
3874         my $t = $self->{types}->{$full_path};
3875         if (!defined $t) {
3876                 die "$full_path not known in r$self->{r} or we have a bug!\n";
3877         }
3878         {
3879                 no warnings 'once';
3880                 # SVN::Node::none and SVN::Node::file are used only once,
3881                 # so we're shutting up Perl's warnings about them.
3882                 if ($t == $SVN::Node::none) {
3883                         return $self->add_directory($full_path, $baton,
3884                             undef, -1, $self->{pool});
3885                 } elsif ($t == $SVN::Node::dir) {
3886                         return $self->open_directory($full_path, $baton,
3887                             $self->{r}, $self->{pool});
3888                 } # no warnings 'once'
3889                 print STDERR "$full_path already exists in repository at ",
3890                     "r$self->{r} and it is not a directory (",
3891                     ($t == $SVN::Node::file ? 'file' : 'unknown'),"/$t)\n";
3892         } # no warnings 'once'
3893         exit 1;
3896 sub ensure_path {
3897         my ($self, $path) = @_;
3898         my $bat = $self->{bat};
3899         my $repo_path = $self->repo_path($path);
3900         return $bat->{''} unless (length $repo_path);
3901         my @p = split m#/+#, $repo_path;
3902         my $c = shift @p;
3903         $bat->{$c} ||= $self->open_or_add_dir($c, $bat->{''});
3904         while (@p) {
3905                 my $c0 = $c;
3906                 $c .= '/' . shift @p;
3907                 $bat->{$c} ||= $self->open_or_add_dir($c, $bat->{$c0});
3908         }
3909         return $bat->{$c};
3912 # Subroutine to convert a globbing pattern to a regular expression.
3913 # From perl cookbook.
3914 sub glob2pat {
3915         my $globstr = shift;
3916         my %patmap = ('*' => '.*', '?' => '.', '[' => '[', ']' => ']');
3917         $globstr =~ s{(.)} { $patmap{$1} || "\Q$1" }ge;
3918         return '^' . $globstr . '$';
3921 sub check_autoprop {
3922         my ($self, $pattern, $properties, $file, $fbat) = @_;
3923         # Convert the globbing pattern to a regular expression.
3924         my $regex = glob2pat($pattern);
3925         # Check if the pattern matches the file name.
3926         if($file =~ m/($regex)/) {
3927                 # Parse the list of properties to set.
3928                 my @props = split(/;/, $properties);
3929                 foreach my $prop (@props) {
3930                         # Parse 'name=value' syntax and set the property.
3931                         if ($prop =~ /([^=]+)=(.*)/) {
3932                                 my ($n,$v) = ($1,$2);
3933                                 for ($n, $v) {
3934                                         s/^\s+//; s/\s+$//;
3935                                 }
3936                                 $self->change_file_prop($fbat, $n, $v);
3937                         }
3938                 }
3939         }
3942 sub apply_autoprops {
3943         my ($self, $file, $fbat) = @_;
3944         my $conf_t = ${$self->{config}}{'config'};
3945         no warnings 'once';
3946         # Check [miscellany]/enable-auto-props in svn configuration.
3947         if (SVN::_Core::svn_config_get_bool(
3948                 $conf_t,
3949                 $SVN::_Core::SVN_CONFIG_SECTION_MISCELLANY,
3950                 $SVN::_Core::SVN_CONFIG_OPTION_ENABLE_AUTO_PROPS,
3951                 0)) {
3952                 # Auto-props are enabled.  Enumerate them to look for matches.
3953                 my $callback = sub {
3954                         $self->check_autoprop($_[0], $_[1], $file, $fbat);
3955                 };
3956                 SVN::_Core::svn_config_enumerate(
3957                         $conf_t,
3958                         $SVN::_Core::SVN_CONFIG_SECTION_AUTO_PROPS,
3959                         $callback);
3960         }
3963 sub A {
3964         my ($self, $m) = @_;
3965         my ($dir, $file) = split_path($m->{file_b});
3966         my $pbat = $self->ensure_path($dir);
3967         my $fbat = $self->add_file($self->repo_path($m->{file_b}), $pbat,
3968                                         undef, -1);
3969         print "\tA\t$m->{file_b}\n" unless $::_q;
3970         $self->apply_autoprops($file, $fbat);
3971         $self->chg_file($fbat, $m);
3972         $self->close_file($fbat,undef,$self->{pool});
3975 sub C {
3976         my ($self, $m) = @_;
3977         my ($dir, $file) = split_path($m->{file_b});
3978         my $pbat = $self->ensure_path($dir);
3979         my $fbat = $self->add_file($self->repo_path($m->{file_b}), $pbat,
3980                                 $self->url_path($m->{file_a}), $self->{r});
3981         print "\tC\t$m->{file_a} => $m->{file_b}\n" unless $::_q;
3982         $self->chg_file($fbat, $m);
3983         $self->close_file($fbat,undef,$self->{pool});
3986 sub delete_entry {
3987         my ($self, $path, $pbat) = @_;
3988         my $rpath = $self->repo_path($path);
3989         my ($dir, $file) = split_path($rpath);
3990         $self->{rm}->{$dir} = 1;
3991         $self->SUPER::delete_entry($rpath, $self->{r}, $pbat, $self->{pool});
3994 sub R {
3995         my ($self, $m) = @_;
3996         my ($dir, $file) = split_path($m->{file_b});
3997         my $pbat = $self->ensure_path($dir);
3998         my $fbat = $self->add_file($self->repo_path($m->{file_b}), $pbat,
3999                                 $self->url_path($m->{file_a}), $self->{r});
4000         print "\tR\t$m->{file_a} => $m->{file_b}\n" unless $::_q;
4001         $self->apply_autoprops($file, $fbat);
4002         $self->chg_file($fbat, $m);
4003         $self->close_file($fbat,undef,$self->{pool});
4005         ($dir, $file) = split_path($m->{file_a});
4006         $pbat = $self->ensure_path($dir);
4007         $self->delete_entry($m->{file_a}, $pbat);
4010 sub M {
4011         my ($self, $m) = @_;
4012         my ($dir, $file) = split_path($m->{file_b});
4013         my $pbat = $self->ensure_path($dir);
4014         my $fbat = $self->open_file($self->repo_path($m->{file_b}),
4015                                 $pbat,$self->{r},$self->{pool});
4016         print "\t$m->{chg}\t$m->{file_b}\n" unless $::_q;
4017         $self->chg_file($fbat, $m);
4018         $self->close_file($fbat,undef,$self->{pool});
4021 sub T { shift->M(@_) }
4023 sub change_file_prop {
4024         my ($self, $fbat, $pname, $pval) = @_;
4025         $self->SUPER::change_file_prop($fbat, $pname, $pval, $self->{pool});
4028 sub _chg_file_get_blob ($$$$) {
4029         my ($self, $fbat, $m, $which) = @_;
4030         my $fh = $::_repository->temp_acquire("git_blob_$which");
4031         if ($m->{"mode_$which"} =~ /^120/) {
4032                 print $fh 'link ' or croak $!;
4033                 $self->change_file_prop($fbat,'svn:special','*');
4034         } elsif ($m->{mode_a} =~ /^120/ && $m->{"mode_$which"} !~ /^120/) {
4035                 $self->change_file_prop($fbat,'svn:special',undef);
4036         }
4037         my $blob = $m->{"sha1_$which"};
4038         return ($fh,) if ($blob =~ /^0{40}$/);
4039         my $size = $::_repository->cat_blob($blob, $fh);
4040         croak "Failed to read object $blob" if ($size < 0);
4041         $fh->flush == 0 or croak $!;
4042         seek $fh, 0, 0 or croak $!;
4044         my $exp = ::md5sum($fh);
4045         seek $fh, 0, 0 or croak $!;
4046         return ($fh, $exp);
4049 sub chg_file {
4050         my ($self, $fbat, $m) = @_;
4051         if ($m->{mode_b} =~ /755$/ && $m->{mode_a} !~ /755$/) {
4052                 $self->change_file_prop($fbat,'svn:executable','*');
4053         } elsif ($m->{mode_b} !~ /755$/ && $m->{mode_a} =~ /755$/) {
4054                 $self->change_file_prop($fbat,'svn:executable',undef);
4055         }
4056         my ($fh_a, $exp_a) = _chg_file_get_blob $self, $fbat, $m, 'a';
4057         my ($fh_b, $exp_b) = _chg_file_get_blob $self, $fbat, $m, 'b';
4058         my $pool = SVN::Pool->new;
4059         my $atd = $self->apply_textdelta($fbat, $exp_a, $pool);
4060         if (-s $fh_a) {
4061                 my $txstream = SVN::TxDelta::new ($fh_a, $fh_b, $pool);
4062                 my $res = SVN::TxDelta::send_txstream($txstream, @$atd, $pool);
4063                 if (defined $res) {
4064                         die "Unexpected result from send_txstream: $res\n",
4065                             "(SVN::Core::VERSION: $SVN::Core::VERSION)\n";
4066                 }
4067         } else {
4068                 my $got = SVN::TxDelta::send_stream($fh_b, @$atd, $pool);
4069                 die "Checksum mismatch\nexpected: $exp_b\ngot: $got\n"
4070                     if ($got ne $exp_b);
4071         }
4072         Git::temp_release($fh_b, 1);
4073         Git::temp_release($fh_a, 1);
4074         $pool->clear;
4077 sub D {
4078         my ($self, $m) = @_;
4079         my ($dir, $file) = split_path($m->{file_b});
4080         my $pbat = $self->ensure_path($dir);
4081         print "\tD\t$m->{file_b}\n" unless $::_q;
4082         $self->delete_entry($m->{file_b}, $pbat);
4085 sub close_edit {
4086         my ($self) = @_;
4087         my ($p,$bat) = ($self->{pool}, $self->{bat});
4088         foreach (sort { $b =~ tr#/#/# <=> $a =~ tr#/#/# } keys %$bat) {
4089                 next if $_ eq '';
4090                 $self->close_directory($bat->{$_}, $p);
4091         }
4092         $self->close_directory($bat->{''}, $p);
4093         $self->SUPER::close_edit($p);
4094         $p->clear;
4097 sub abort_edit {
4098         my ($self) = @_;
4099         $self->SUPER::abort_edit($self->{pool});
4102 sub DESTROY {
4103         my $self = shift;
4104         $self->SUPER::DESTROY(@_);
4105         $self->{pool}->clear;
4108 # this drives the editor
4109 sub apply_diff {
4110         my ($self) = @_;
4111         my $mods = $self->{mods};
4112         my %o = ( D => 1, R => 0, C => -1, A => 3, M => 3, T => 3 );
4113         foreach my $m (sort { $o{$a->{chg}} <=> $o{$b->{chg}} } @$mods) {
4114                 my $f = $m->{chg};
4115                 if (defined $o{$f}) {
4116                         $self->$f($m);
4117                 } else {
4118                         fatal("Invalid change type: $f");
4119                 }
4120         }
4121         $self->rmdirs if $_rmdir;
4122         if (@$mods == 0) {
4123                 $self->abort_edit;
4124         } else {
4125                 $self->close_edit;
4126         }
4127         return scalar @$mods;
4130 package Git::SVN::Ra;
4131 use vars qw/@ISA $config_dir $_log_window_size/;
4132 use strict;
4133 use warnings;
4134 my ($ra_invalid, $can_do_switch, %ignored_err, $RA);
4136 BEGIN {
4137         # enforce temporary pool usage for some simple functions
4138         no strict 'refs';
4139         for my $f (qw/rev_proplist get_latest_revnum get_uuid get_repos_root
4140                       get_file/) {
4141                 my $SUPER = "SUPER::$f";
4142                 *$f = sub {
4143                         my $self = shift;
4144                         my $pool = SVN::Pool->new;
4145                         my @ret = $self->$SUPER(@_,$pool);
4146                         $pool->clear;
4147                         wantarray ? @ret : $ret[0];
4148                 };
4149         }
4152 sub _auth_providers () {
4153         [
4154           SVN::Client::get_simple_provider(),
4155           SVN::Client::get_ssl_server_trust_file_provider(),
4156           SVN::Client::get_simple_prompt_provider(
4157             \&Git::SVN::Prompt::simple, 2),
4158           SVN::Client::get_ssl_client_cert_file_provider(),
4159           SVN::Client::get_ssl_client_cert_prompt_provider(
4160             \&Git::SVN::Prompt::ssl_client_cert, 2),
4161           SVN::Client::get_ssl_client_cert_pw_file_provider(),
4162           SVN::Client::get_ssl_client_cert_pw_prompt_provider(
4163             \&Git::SVN::Prompt::ssl_client_cert_pw, 2),
4164           SVN::Client::get_username_provider(),
4165           SVN::Client::get_ssl_server_trust_prompt_provider(
4166             \&Git::SVN::Prompt::ssl_server_trust),
4167           SVN::Client::get_username_prompt_provider(
4168             \&Git::SVN::Prompt::username, 2)
4169         ]
4172 sub escape_uri_only {
4173         my ($uri) = @_;
4174         my @tmp;
4175         foreach (split m{/}, $uri) {
4176                 s/([^~\w.%+-]|%(?![a-fA-F0-9]{2}))/sprintf("%%%02X",ord($1))/eg;
4177                 push @tmp, $_;
4178         }
4179         join('/', @tmp);
4182 sub escape_url {
4183         my ($url) = @_;
4184         if ($url =~ m#^(https?)://([^/]+)(.*)$#) {
4185                 my ($scheme, $domain, $uri) = ($1, $2, escape_uri_only($3));
4186                 $url = "$scheme://$domain$uri";
4187         }
4188         $url;
4191 sub new {
4192         my ($class, $url) = @_;
4193         $url =~ s!/+$!!;
4194         return $RA if ($RA && $RA->{url} eq $url);
4196         SVN::_Core::svn_config_ensure($config_dir, undef);
4197         my ($baton, $callbacks) = SVN::Core::auth_open_helper(_auth_providers);
4198         my $config = SVN::Core::config_get_config($config_dir);
4199         $RA = undef;
4200         my $dont_store_passwords = 1;
4201         my $conf_t = ${$config}{'config'};
4202         {
4203                 no warnings 'once';
4204                 # The usage of $SVN::_Core::SVN_CONFIG_* variables
4205                 # produces warnings that variables are used only once.
4206                 # I had not found the better way to shut them up, so
4207                 # the warnings of type 'once' are disabled in this block.
4208                 if (SVN::_Core::svn_config_get_bool($conf_t,
4209                     $SVN::_Core::SVN_CONFIG_SECTION_AUTH,
4210                     $SVN::_Core::SVN_CONFIG_OPTION_STORE_PASSWORDS,
4211                     1) == 0) {
4212                         SVN::_Core::svn_auth_set_parameter($baton,
4213                             $SVN::_Core::SVN_AUTH_PARAM_DONT_STORE_PASSWORDS,
4214                             bless (\$dont_store_passwords, "_p_void"));
4215                 }
4216                 if (SVN::_Core::svn_config_get_bool($conf_t,
4217                     $SVN::_Core::SVN_CONFIG_SECTION_AUTH,
4218                     $SVN::_Core::SVN_CONFIG_OPTION_STORE_AUTH_CREDS,
4219                     1) == 0) {
4220                         $Git::SVN::Prompt::_no_auth_cache = 1;
4221                 }
4222         } # no warnings 'once'
4223         my $self = SVN::Ra->new(url => escape_url($url), auth => $baton,
4224                               config => $config,
4225                               pool => SVN::Pool->new,
4226                               auth_provider_callbacks => $callbacks);
4227         $self->{url} = $url;
4228         $self->{svn_path} = $url;
4229         $self->{repos_root} = $self->get_repos_root;
4230         $self->{svn_path} =~ s#^\Q$self->{repos_root}\E(/|$)##;
4231         $self->{cache} = { check_path => { r => 0, data => {} },
4232                            get_dir => { r => 0, data => {} } };
4233         $RA = bless $self, $class;
4236 sub check_path {
4237         my ($self, $path, $r) = @_;
4238         my $cache = $self->{cache}->{check_path};
4239         if ($r == $cache->{r} && exists $cache->{data}->{$path}) {
4240                 return $cache->{data}->{$path};
4241         }
4242         my $pool = SVN::Pool->new;
4243         my $t = $self->SUPER::check_path($path, $r, $pool);
4244         $pool->clear;
4245         if ($r != $cache->{r}) {
4246                 %{$cache->{data}} = ();
4247                 $cache->{r} = $r;
4248         }
4249         $cache->{data}->{$path} = $t;
4252 sub get_dir {
4253         my ($self, $dir, $r) = @_;
4254         my $cache = $self->{cache}->{get_dir};
4255         if ($r == $cache->{r}) {
4256                 if (my $x = $cache->{data}->{$dir}) {
4257                         return wantarray ? @$x : $x->[0];
4258                 }
4259         }
4260         my $pool = SVN::Pool->new;
4261         my ($d, undef, $props) = $self->SUPER::get_dir($dir, $r, $pool);
4262         my %dirents = map { $_ => { kind => $d->{$_}->kind } } keys %$d;
4263         $pool->clear;
4264         if ($r != $cache->{r}) {
4265                 %{$cache->{data}} = ();
4266                 $cache->{r} = $r;
4267         }
4268         $cache->{data}->{$dir} = [ \%dirents, $r, $props ];
4269         wantarray ? (\%dirents, $r, $props) : \%dirents;
4272 sub DESTROY {
4273         # do not call the real DESTROY since we store ourselves in $RA
4276 # get_log(paths, start, end, limit,
4277 #         discover_changed_paths, strict_node_history, receiver)
4278 sub get_log {
4279         my ($self, @args) = @_;
4280         my $pool = SVN::Pool->new;
4282         # the limit parameter was not supported in SVN 1.1.x, so we
4283         # drop it.  Therefore, the receiver callback passed to it
4284         # is made aware of this limitation by being wrapped if
4285         # the limit passed to is being wrapped.
4286         if ($SVN::Core::VERSION le '1.2.0') {
4287                 my $limit = splice(@args, 3, 1);
4288                 if ($limit > 0) {
4289                         my $receiver = pop @args;
4290                         push(@args, sub { &$receiver(@_) if (--$limit >= 0) });
4291                 }
4292         }
4293         my $ret = $self->SUPER::get_log(@args, $pool);
4294         $pool->clear;
4295         $ret;
4298 sub trees_match {
4299         my ($self, $url1, $rev1, $url2, $rev2) = @_;
4300         my $ctx = SVN::Client->new(auth => _auth_providers);
4301         my $out = IO::File->new_tmpfile;
4303         # older SVN (1.1.x) doesn't take $pool as the last parameter for
4304         # $ctx->diff(), so we'll create a default one
4305         my $pool = SVN::Pool->new_default_sub;
4307         $ra_invalid = 1; # this will open a new SVN::Ra connection to $url1
4308         $ctx->diff([], $url1, $rev1, $url2, $rev2, 1, 1, 0, $out, $out);
4309         $out->flush;
4310         my $ret = (($out->stat)[7] == 0);
4311         close $out or croak $!;
4313         $ret;
4316 sub get_commit_editor {
4317         my ($self, $log, $cb, $pool) = @_;
4318         my @lock = $SVN::Core::VERSION ge '1.2.0' ? (undef, 0) : ();
4319         $self->SUPER::get_commit_editor($log, $cb, @lock, $pool);
4322 sub gs_do_update {
4323         my ($self, $rev_a, $rev_b, $gs, $editor) = @_;
4324         my $new = ($rev_a == $rev_b);
4325         my $path = $gs->{path};
4327         if ($new && -e $gs->{index}) {
4328                 unlink $gs->{index} or die
4329                   "Couldn't unlink index: $gs->{index}: $!\n";
4330         }
4331         my $pool = SVN::Pool->new;
4332         $editor->set_path_strip($path);
4333         my (@pc) = split m#/#, $path;
4334         my $reporter = $self->do_update($rev_b, (@pc ? shift @pc : ''),
4335                                         1, $editor, $pool);
4336         my @lock = $SVN::Core::VERSION ge '1.2.0' ? (undef) : ();
4338         # Since we can't rely on svn_ra_reparent being available, we'll
4339         # just have to do some magic with set_path to make it so
4340         # we only want a partial path.
4341         my $sp = '';
4342         my $final = join('/', @pc);
4343         while (@pc) {
4344                 $reporter->set_path($sp, $rev_b, 0, @lock, $pool);
4345                 $sp .= '/' if length $sp;
4346                 $sp .= shift @pc;
4347         }
4348         die "BUG: '$sp' != '$final'\n" if ($sp ne $final);
4350         $reporter->set_path($sp, $rev_a, $new, @lock, $pool);
4352         $reporter->finish_report($pool);
4353         $pool->clear;
4354         $editor->{git_commit_ok};
4357 # this requires SVN 1.4.3 or later (do_switch didn't work before 1.4.3, and
4358 # svn_ra_reparent didn't work before 1.4)
4359 sub gs_do_switch {
4360         my ($self, $rev_a, $rev_b, $gs, $url_b, $editor) = @_;
4361         my $path = $gs->{path};
4362         my $pool = SVN::Pool->new;
4364         my $full_url = $self->{url};
4365         my $old_url = $full_url;
4366         $full_url .= '/' . escape_uri_only($path) if length $path;
4367         my ($ra, $reparented);
4369         if ($old_url =~ m#^svn(\+ssh)?://#) {
4370                 $_[0] = undef;
4371                 $self = undef;
4372                 $RA = undef;
4373                 $ra = Git::SVN::Ra->new($full_url);
4374                 $ra_invalid = 1;
4375         } elsif ($old_url ne $full_url) {
4376                 SVN::_Ra::svn_ra_reparent($self->{session}, $full_url, $pool);
4377                 $self->{url} = $full_url;
4378                 $reparented = 1;
4379         }
4381         $ra ||= $self;
4382         $url_b = escape_url($url_b);
4383         my $reporter = $ra->do_switch($rev_b, '', 1, $url_b, $editor, $pool);
4384         my @lock = $SVN::Core::VERSION ge '1.2.0' ? (undef) : ();
4385         $reporter->set_path('', $rev_a, 0, @lock, $pool);
4386         $reporter->finish_report($pool);
4388         if ($reparented) {
4389                 SVN::_Ra::svn_ra_reparent($self->{session}, $old_url, $pool);
4390                 $self->{url} = $old_url;
4391         }
4393         $pool->clear;
4394         $editor->{git_commit_ok};
4397 sub longest_common_path {
4398         my ($gsv, $globs) = @_;
4399         my %common;
4400         my $common_max = scalar @$gsv;
4402         foreach my $gs (@$gsv) {
4403                 my @tmp = split m#/#, $gs->{path};
4404                 my $p = '';
4405                 foreach (@tmp) {
4406                         $p .= length($p) ? "/$_" : $_;
4407                         $common{$p} ||= 0;
4408                         $common{$p}++;
4409                 }
4410         }
4411         $globs ||= [];
4412         $common_max += scalar @$globs;
4413         foreach my $glob (@$globs) {
4414                 my @tmp = split m#/#, $glob->{path}->{left};
4415                 my $p = '';
4416                 foreach (@tmp) {
4417                         $p .= length($p) ? "/$_" : $_;
4418                         $common{$p} ||= 0;
4419                         $common{$p}++;
4420                 }
4421         }
4423         my $longest_path = '';
4424         foreach (sort {length $b <=> length $a} keys %common) {
4425                 if ($common{$_} == $common_max) {
4426                         $longest_path = $_;
4427                         last;
4428                 }
4429         }
4430         $longest_path;
4433 sub gs_fetch_loop_common {
4434         my ($self, $base, $head, $gsv, $globs) = @_;
4435         return if ($base > $head);
4436         my $inc = $_log_window_size;
4437         my ($min, $max) = ($base, $head < $base + $inc ? $head : $base + $inc);
4438         my $longest_path = longest_common_path($gsv, $globs);
4439         my $ra_url = $self->{url};
4440         while (1) {
4441                 my %revs;
4442                 my $err;
4443                 my $err_handler = $SVN::Error::handler;
4444                 $SVN::Error::handler = sub {
4445                         ($err) = @_;
4446                         skip_unknown_revs($err);
4447                 };
4448                 sub _cb {
4449                         my ($paths, $r, $author, $date, $log) = @_;
4450                         [ dup_changed_paths($paths),
4451                           { author => $author, date => $date, log => $log } ];
4452                 }
4453                 $self->get_log([$longest_path], $min, $max, 0, 1, 1,
4454                                sub { $revs{$_[1]} = _cb(@_) });
4455                 if ($err) {
4456                         print "Checked through r$max\r";
4457                 }
4458                 if ($err && $max >= $head) {
4459                         print STDERR "Path '$longest_path' ",
4460                                      "was probably deleted:\n",
4461                                      $err->expanded_message,
4462                                      "\nWill attempt to follow ",
4463                                      "revisions r$min .. r$max ",
4464                                      "committed before the deletion\n";
4465                         my $hi = $max;
4466                         while (--$hi >= $min) {
4467                                 my $ok;
4468                                 $self->get_log([$longest_path], $min, $hi,
4469                                                0, 1, 1, sub {
4470                                                $ok ||= $_[1];
4471                                                $revs{$_[1]} = _cb(@_) });
4472                                 if ($ok) {
4473                                         print STDERR "r$min .. r$ok OK\n";
4474                                         last;
4475                                 }
4476                         }
4477                 }
4478                 $SVN::Error::handler = $err_handler;
4480                 my %exists = map { $_->{path} => $_ } @$gsv;
4481                 foreach my $r (sort {$a <=> $b} keys %revs) {
4482                         my ($paths, $logged) = @{$revs{$r}};
4484                         foreach my $gs ($self->match_globs(\%exists, $paths,
4485                                                            $globs, $r)) {
4486                                 if ($gs->rev_map_max >= $r) {
4487                                         next;
4488                                 }
4489                                 next unless $gs->match_paths($paths, $r);
4490                                 $gs->{logged_rev_props} = $logged;
4491                                 if (my $last_commit = $gs->last_commit) {
4492                                         $gs->assert_index_clean($last_commit);
4493                                 }
4494                                 my $log_entry = $gs->do_fetch($paths, $r);
4495                                 if ($log_entry) {
4496                                         $gs->do_git_commit($log_entry);
4497                                 }
4498                                 $INDEX_FILES{$gs->{index}} = 1;
4499                         }
4500                         foreach my $g (@$globs) {
4501                                 my $k = "svn-remote.$g->{remote}." .
4502                                         "$g->{t}-maxRev";
4503                                 Git::SVN::tmp_config($k, $r);
4504                         }
4505                         if ($ra_invalid) {
4506                                 $_[0] = undef;
4507                                 $self = undef;
4508                                 $RA = undef;
4509                                 $self = Git::SVN::Ra->new($ra_url);
4510                                 $ra_invalid = undef;
4511                         }
4512                 }
4513                 # pre-fill the .rev_db since it'll eventually get filled in
4514                 # with '0' x40 if something new gets committed
4515                 foreach my $gs (@$gsv) {
4516                         next if $gs->rev_map_max >= $max;
4517                         next if defined $gs->rev_map_get($max);
4518                         $gs->rev_map_set($max, 0 x40);
4519                 }
4520                 foreach my $g (@$globs) {
4521                         my $k = "svn-remote.$g->{remote}.$g->{t}-maxRev";
4522                         Git::SVN::tmp_config($k, $max);
4523                 }
4524                 last if $max >= $head;
4525                 $min = $max + 1;
4526                 $max += $inc;
4527                 $max = $head if ($max > $head);
4528         }
4529         Git::SVN::gc();
4532 sub get_dir_globbed {
4533         my ($self, $left, $depth, $r) = @_;
4535         my @x = eval { $self->get_dir($left, $r) };
4536         return unless scalar @x == 3;
4537         my $dirents = $x[0];
4538         my @finalents;
4539         foreach my $de (keys %$dirents) {
4540                 next if $dirents->{$de}->{kind} != $SVN::Node::dir;
4541                 if ($depth > 1) {
4542                         my @args = ("$left/$de", $depth - 1, $r);
4543                         foreach my $dir ($self->get_dir_globbed(@args)) {
4544                                 push @finalents, "$de/$dir";
4545                         }
4546                 } else {
4547                         push @finalents, $de;
4548                 }
4549         }
4550         @finalents;
4553 sub match_globs {
4554         my ($self, $exists, $paths, $globs, $r) = @_;
4556         sub get_dir_check {
4557                 my ($self, $exists, $g, $r) = @_;
4559                 my @dirs = $self->get_dir_globbed($g->{path}->{left},
4560                                                   $g->{path}->{depth},
4561                                                   $r);
4563                 foreach my $de (@dirs) {
4564                         my $p = $g->{path}->full_path($de);
4565                         next if $exists->{$p};
4566                         next if (length $g->{path}->{right} &&
4567                                  ($self->check_path($p, $r) !=
4568                                   $SVN::Node::dir));
4569                         $exists->{$p} = Git::SVN->init($self->{url}, $p, undef,
4570                                          $g->{ref}->full_path($de), 1);
4571                 }
4572         }
4573         foreach my $g (@$globs) {
4574                 if (my $path = $paths->{"/$g->{path}->{left}"}) {
4575                         if ($path->{action} =~ /^[AR]$/) {
4576                                 get_dir_check($self, $exists, $g, $r);
4577                         }
4578                 }
4579                 foreach (keys %$paths) {
4580                         if (/$g->{path}->{left_regex}/ &&
4581                             !/$g->{path}->{regex}/) {
4582                                 next if $paths->{$_}->{action} !~ /^[AR]$/;
4583                                 get_dir_check($self, $exists, $g, $r);
4584                         }
4585                         next unless /$g->{path}->{regex}/;
4586                         my $p = $1;
4587                         my $pathname = $g->{path}->full_path($p);
4588                         next if $exists->{$pathname};
4589                         next if ($self->check_path($pathname, $r) !=
4590                                  $SVN::Node::dir);
4591                         $exists->{$pathname} = Git::SVN->init(
4592                                               $self->{url}, $pathname, undef,
4593                                               $g->{ref}->full_path($p), 1);
4594                 }
4595                 my $c = '';
4596                 foreach (split m#/#, $g->{path}->{left}) {
4597                         $c .= "/$_";
4598                         next unless ($paths->{$c} &&
4599                                      ($paths->{$c}->{action} =~ /^[AR]$/));
4600                         get_dir_check($self, $exists, $g, $r);
4601                 }
4602         }
4603         values %$exists;
4606 sub minimize_url {
4607         my ($self) = @_;
4608         return $self->{url} if ($self->{url} eq $self->{repos_root});
4609         my $url = $self->{repos_root};
4610         my @components = split(m!/!, $self->{svn_path});
4611         my $c = '';
4612         do {
4613                 $url .= "/$c" if length $c;
4614                 eval { (ref $self)->new($url)->get_latest_revnum };
4615         } while ($@ && ($c = shift @components));
4616         $url;
4619 sub can_do_switch {
4620         my $self = shift;
4621         unless (defined $can_do_switch) {
4622                 my $pool = SVN::Pool->new;
4623                 my $rep = eval {
4624                         $self->do_switch(1, '', 0, $self->{url},
4625                                          SVN::Delta::Editor->new, $pool);
4626                 };
4627                 if ($@) {
4628                         $can_do_switch = 0;
4629                 } else {
4630                         $rep->abort_report($pool);
4631                         $can_do_switch = 1;
4632                 }
4633                 $pool->clear;
4634         }
4635         $can_do_switch;
4638 sub skip_unknown_revs {
4639         my ($err) = @_;
4640         my $errno = $err->apr_err();
4641         # Maybe the branch we're tracking didn't
4642         # exist when the repo started, so it's
4643         # not an error if it doesn't, just continue
4644         #
4645         # Wonderfully consistent library, eh?
4646         # 160013 - svn:// and file://
4647         # 175002 - http(s)://
4648         # 175007 - http(s):// (this repo required authorization, too...)
4649         #   More codes may be discovered later...
4650         if ($errno == 175007 || $errno == 175002 || $errno == 160013) {
4651                 my $err_key = $err->expanded_message;
4652                 # revision numbers change every time, filter them out
4653                 $err_key =~ s/\d+/\0/g;
4654                 $err_key = "$errno\0$err_key";
4655                 unless ($ignored_err{$err_key}) {
4656                         warn "W: Ignoring error from SVN, path probably ",
4657                              "does not exist: ($errno): ",
4658                              $err->expanded_message,"\n";
4659                         warn "W: Do not be alarmed at the above message ",
4660                              "git-svn is just searching aggressively for ",
4661                              "old history.\n",
4662                              "This may take a while on large repositories\n";
4663                         $ignored_err{$err_key} = 1;
4664                 }
4665                 return;
4666         }
4667         die "Error from SVN, ($errno): ", $err->expanded_message,"\n";
4670 # svn_log_changed_path_t objects passed to get_log are likely to be
4671 # overwritten even if only the refs are copied to an external variable,
4672 # so we should dup the structures in their entirety.  Using an externally
4673 # passed pool (instead of our temporary and quickly cleared pool in
4674 # Git::SVN::Ra) does not help matters at all...
4675 sub dup_changed_paths {
4676         my ($paths) = @_;
4677         return undef unless $paths;
4678         my %ret;
4679         foreach my $p (keys %$paths) {
4680                 my $i = $paths->{$p};
4681                 my %s = map { $_ => $i->$_ }
4682                               qw/copyfrom_path copyfrom_rev action/;
4683                 $ret{$p} = \%s;
4684         }
4685         \%ret;
4688 package Git::SVN::Log;
4689 use strict;
4690 use warnings;
4691 use POSIX qw/strftime/;
4692 use Time::Local;
4693 use constant commit_log_separator => ('-' x 72) . "\n";
4694 use vars qw/$TZ $limit $color $pager $non_recursive $verbose $oneline
4695             %rusers $show_commit $incremental/;
4696 my $l_fmt;
4698 sub cmt_showable {
4699         my ($c) = @_;
4700         return 1 if defined $c->{r};
4702         # big commit message got truncated by the 16k pretty buffer in rev-list
4703         if ($c->{l} && $c->{l}->[-1] eq "...\n" &&
4704                                 $c->{a_raw} =~ /\@([a-f\d\-]+)>$/) {
4705                 @{$c->{l}} = ();
4706                 my @log = command(qw/cat-file commit/, $c->{c});
4708                 # shift off the headers
4709                 shift @log while ($log[0] ne '');
4710                 shift @log;
4712                 # TODO: make $c->{l} not have a trailing newline in the future
4713                 @{$c->{l}} = map { "$_\n" } grep !/^git-svn-id: /, @log;
4715                 (undef, $c->{r}, undef) = ::extract_metadata(
4716                                 (grep(/^git-svn-id: /, @log))[-1]);
4717         }
4718         return defined $c->{r};
4721 sub log_use_color {
4722         return $color || Git->repository->get_colorbool('color.diff');
4725 sub git_svn_log_cmd {
4726         my ($r_min, $r_max, @args) = @_;
4727         my $head = 'HEAD';
4728         my (@files, @log_opts);
4729         foreach my $x (@args) {
4730                 if ($x eq '--' || @files) {
4731                         push @files, $x;
4732                 } else {
4733                         if (::verify_ref("$x^0")) {
4734                                 $head = $x;
4735                         } else {
4736                                 push @log_opts, $x;
4737                         }
4738                 }
4739         }
4741         my ($url, $rev, $uuid, $gs) = ::working_head_info($head);
4742         $gs ||= Git::SVN->_new;
4743         my @cmd = (qw/log --abbrev-commit --pretty=raw --default/,
4744                    $gs->refname);
4745         push @cmd, '-r' unless $non_recursive;
4746         push @cmd, qw/--raw --name-status/ if $verbose;
4747         push @cmd, '--color' if log_use_color();
4748         push @cmd, @log_opts;
4749         if (defined $r_max && $r_max == $r_min) {
4750                 push @cmd, '--max-count=1';
4751                 if (my $c = $gs->rev_map_get($r_max)) {
4752                         push @cmd, $c;
4753                 }
4754         } elsif (defined $r_max) {
4755                 if ($r_max < $r_min) {
4756                         ($r_min, $r_max) = ($r_max, $r_min);
4757                 }
4758                 my (undef, $c_max) = $gs->find_rev_before($r_max, 1, $r_min);
4759                 my (undef, $c_min) = $gs->find_rev_after($r_min, 1, $r_max);
4760                 # If there are no commits in the range, both $c_max and $c_min
4761                 # will be undefined.  If there is at least 1 commit in the
4762                 # range, both will be defined.
4763                 return () if !defined $c_min || !defined $c_max;
4764                 if ($c_min eq $c_max) {
4765                         push @cmd, '--max-count=1', $c_min;
4766                 } else {
4767                         push @cmd, '--boundary', "$c_min..$c_max";
4768                 }
4769         }
4770         return (@cmd, @files);
4773 # adapted from pager.c
4774 sub config_pager {
4775         $pager ||= $ENV{GIT_PAGER} || $ENV{PAGER};
4776         if (!defined $pager) {
4777                 $pager = 'less';
4778         } elsif (length $pager == 0 || $pager eq 'cat') {
4779                 $pager = undef;
4780         }
4781         $ENV{GIT_PAGER_IN_USE} = defined($pager);
4784 sub run_pager {
4785         return unless -t *STDOUT && defined $pager;
4786         pipe my ($rfd, $wfd) or return;
4787         defined(my $pid = fork) or ::fatal "Can't fork: $!";
4788         if (!$pid) {
4789                 open STDOUT, '>&', $wfd or
4790                                      ::fatal "Can't redirect to stdout: $!";
4791                 return;
4792         }
4793         open STDIN, '<&', $rfd or ::fatal "Can't redirect stdin: $!";
4794         $ENV{LESS} ||= 'FRSX';
4795         exec $pager or ::fatal "Can't run pager: $! ($pager)";
4798 sub format_svn_date {
4799         # some systmes don't handle or mishandle %z, so be creative.
4800         my $t = shift || time;
4801         my $gm = timelocal(gmtime($t));
4802         my $sign = qw( + + - )[ $t <=> $gm ];
4803         my $gmoff = sprintf("%s%02d%02d", $sign, (gmtime(abs($t - $gm)))[2,1]);
4804         return strftime("%Y-%m-%d %H:%M:%S $gmoff (%a, %d %b %Y)", localtime($t));
4807 sub parse_git_date {
4808         my ($t, $tz) = @_;
4809         # Date::Parse isn't in the standard Perl distro :(
4810         if ($tz =~ s/^\+//) {
4811                 $t += tz_to_s_offset($tz);
4812         } elsif ($tz =~ s/^\-//) {
4813                 $t -= tz_to_s_offset($tz);
4814         }
4815         return $t;
4818 sub set_local_timezone {
4819         if (defined $TZ) {
4820                 $ENV{TZ} = $TZ;
4821         } else {
4822                 delete $ENV{TZ};
4823         }
4826 sub tz_to_s_offset {
4827         my ($tz) = @_;
4828         $tz =~ s/(\d\d)$//;
4829         return ($1 * 60) + ($tz * 3600);
4832 sub get_author_info {
4833         my ($dest, $author, $t, $tz) = @_;
4834         $author =~ s/(?:^\s*|\s*$)//g;
4835         $dest->{a_raw} = $author;
4836         my $au;
4837         if ($::_authors) {
4838                 $au = $rusers{$author} || undef;
4839         }
4840         if (!$au) {
4841                 ($au) = ($author =~ /<([^>]+)\@[^>]+>$/);
4842         }
4843         $dest->{t} = $t;
4844         $dest->{tz} = $tz;
4845         $dest->{a} = $au;
4846         $dest->{t_utc} = parse_git_date($t, $tz);
4849 sub process_commit {
4850         my ($c, $r_min, $r_max, $defer) = @_;
4851         if (defined $r_min && defined $r_max) {
4852                 if ($r_min == $c->{r} && $r_min == $r_max) {
4853                         show_commit($c);
4854                         return 0;
4855                 }
4856                 return 1 if $r_min == $r_max;
4857                 if ($r_min < $r_max) {
4858                         # we need to reverse the print order
4859                         return 0 if (defined $limit && --$limit < 0);
4860                         push @$defer, $c;
4861                         return 1;
4862                 }
4863                 if ($r_min != $r_max) {
4864                         return 1 if ($r_min < $c->{r});
4865                         return 1 if ($r_max > $c->{r});
4866                 }
4867         }
4868         return 0 if (defined $limit && --$limit < 0);
4869         show_commit($c);
4870         return 1;
4873 sub show_commit {
4874         my $c = shift;
4875         if ($oneline) {
4876                 my $x = "\n";
4877                 if (my $l = $c->{l}) {
4878                         while ($l->[0] =~ /^\s*$/) { shift @$l }
4879                         $x = $l->[0];
4880                 }
4881                 $l_fmt ||= 'A' . length($c->{r});
4882                 print 'r',pack($l_fmt, $c->{r}),' | ';
4883                 print "$c->{c} | " if $show_commit;
4884                 print $x;
4885         } else {
4886                 show_commit_normal($c);
4887         }
4890 sub show_commit_changed_paths {
4891         my ($c) = @_;
4892         return unless $c->{changed};
4893         print "Changed paths:\n", @{$c->{changed}};
4896 sub show_commit_normal {
4897         my ($c) = @_;
4898         print commit_log_separator, "r$c->{r} | ";
4899         print "$c->{c} | " if $show_commit;
4900         print "$c->{a} | ", format_svn_date($c->{t_utc}), ' | ';
4901         my $nr_line = 0;
4903         if (my $l = $c->{l}) {
4904                 while ($l->[$#$l] eq "\n" && $#$l > 0
4905                                           && $l->[($#$l - 1)] eq "\n") {
4906                         pop @$l;
4907                 }
4908                 $nr_line = scalar @$l;
4909                 if (!$nr_line) {
4910                         print "1 line\n\n\n";
4911                 } else {
4912                         if ($nr_line == 1) {
4913                                 $nr_line = '1 line';
4914                         } else {
4915                                 $nr_line .= ' lines';
4916                         }
4917                         print $nr_line, "\n";
4918                         show_commit_changed_paths($c);
4919                         print "\n";
4920                         print $_ foreach @$l;
4921                 }
4922         } else {
4923                 print "1 line\n";
4924                 show_commit_changed_paths($c);
4925                 print "\n";
4927         }
4928         foreach my $x (qw/raw stat diff/) {
4929                 if ($c->{$x}) {
4930                         print "\n";
4931                         print $_ foreach @{$c->{$x}}
4932                 }
4933         }
4936 sub cmd_show_log {
4937         my (@args) = @_;
4938         my ($r_min, $r_max);
4939         my $r_last = -1; # prevent dupes
4940         set_local_timezone();
4941         if (defined $::_revision) {
4942                 if ($::_revision =~ /^(\d+):(\d+)$/) {
4943                         ($r_min, $r_max) = ($1, $2);
4944                 } elsif ($::_revision =~ /^\d+$/) {
4945                         $r_min = $r_max = $::_revision;
4946                 } else {
4947                         ::fatal "-r$::_revision is not supported, use ",
4948                                 "standard 'git log' arguments instead";
4949                 }
4950         }
4952         config_pager();
4953         @args = git_svn_log_cmd($r_min, $r_max, @args);
4954         if (!@args) {
4955                 print commit_log_separator unless $incremental || $oneline;
4956                 return;
4957         }
4958         my $log = command_output_pipe(@args);
4959         run_pager();
4960         my (@k, $c, $d, $stat);
4961         my $esc_color = qr/(?:\033\[(?:(?:\d+;)*\d*)?m)*/;
4962         while (<$log>) {
4963                 if (/^${esc_color}commit -?($::sha1_short)/o) {
4964                         my $cmt = $1;
4965                         if ($c && cmt_showable($c) && $c->{r} != $r_last) {
4966                                 $r_last = $c->{r};
4967                                 process_commit($c, $r_min, $r_max, \@k) or
4968                                                                 goto out;
4969                         }
4970                         $d = undef;
4971                         $c = { c => $cmt };
4972                 } elsif (/^${esc_color}author (.+) (\d+) ([\-\+]?\d+)$/o) {
4973                         get_author_info($c, $1, $2, $3);
4974                 } elsif (/^${esc_color}(?:tree|parent|committer) /o) {
4975                         # ignore
4976                 } elsif (/^${esc_color}:\d{6} \d{6} $::sha1_short/o) {
4977                         push @{$c->{raw}}, $_;
4978                 } elsif (/^${esc_color}[ACRMDT]\t/) {
4979                         # we could add $SVN->{svn_path} here, but that requires
4980                         # remote access at the moment (repo_path_split)...
4981                         s#^(${esc_color})([ACRMDT])\t#$1   $2 #o;
4982                         push @{$c->{changed}}, $_;
4983                 } elsif (/^${esc_color}diff /o) {
4984                         $d = 1;
4985                         push @{$c->{diff}}, $_;
4986                 } elsif ($d) {
4987                         push @{$c->{diff}}, $_;
4988                 } elsif (/^\ .+\ \|\s*\d+\ $esc_color[\+\-]*
4989                           $esc_color*[\+\-]*$esc_color$/x) {
4990                         $stat = 1;
4991                         push @{$c->{stat}}, $_;
4992                 } elsif ($stat && /^ \d+ files changed, \d+ insertions/) {
4993                         push @{$c->{stat}}, $_;
4994                         $stat = undef;
4995                 } elsif (/^${esc_color}    (git-svn-id:.+)$/o) {
4996                         ($c->{url}, $c->{r}, undef) = ::extract_metadata($1);
4997                 } elsif (s/^${esc_color}    //o) {
4998                         push @{$c->{l}}, $_;
4999                 }
5000         }
5001         if ($c && defined $c->{r} && $c->{r} != $r_last) {
5002                 $r_last = $c->{r};
5003                 process_commit($c, $r_min, $r_max, \@k);
5004         }
5005         if (@k) {
5006                 ($r_min, $r_max) = ($r_max, $r_min);
5007                 process_commit($_, $r_min, $r_max) foreach reverse @k;
5008         }
5009 out:
5010         close $log;
5011         print commit_log_separator unless $incremental || $oneline;
5014 sub cmd_blame {
5015         my $path = pop;
5017         config_pager();
5018         run_pager();
5020         my ($fh, $ctx, $rev);
5022         if ($_git_format) {
5023                 ($fh, $ctx) = command_output_pipe('blame', @_, $path);
5024                 while (my $line = <$fh>) {
5025                         if ($line =~ /^\^?([[:xdigit:]]+)\s/) {
5026                                 # Uncommitted edits show up as a rev ID of
5027                                 # all zeros, which we can't look up with
5028                                 # cmt_metadata
5029                                 if ($1 !~ /^0+$/) {
5030                                         (undef, $rev, undef) =
5031                                                 ::cmt_metadata($1);
5032                                         $rev = '0' if (!$rev);
5033                                 } else {
5034                                         $rev = '0';
5035                                 }
5036                                 $rev = sprintf('%-10s', $rev);
5037                                 $line =~ s/^\^?[[:xdigit:]]+(\s)/$rev$1/;
5038                         }
5039                         print $line;
5040                 }
5041         } else {
5042                 ($fh, $ctx) = command_output_pipe('blame', '-p', @_, 'HEAD',
5043                                                   '--', $path);
5044                 my ($sha1);
5045                 my %authors;
5046                 my @buffer;
5047                 my %dsha; #distinct sha keys
5049                 while (my $line = <$fh>) {
5050                         push @buffer, $line;
5051                         if ($line =~ /^([[:xdigit:]]{40})\s\d+\s\d+/) {
5052                                 $dsha{$1} = 1;
5053                         }
5054                 }
5056                 my $s2r = ::cmt_sha2rev_batch([keys %dsha]);
5058                 foreach my $line (@buffer) {
5059                         if ($line =~ /^([[:xdigit:]]{40})\s\d+\s\d+/) {
5060                                 $rev = $s2r->{$1};
5061                                 $rev = '0' if (!$rev)
5062                         }
5063                         elsif ($line =~ /^author (.*)/) {
5064                                 $authors{$rev} = $1;
5065                                 $authors{$rev} =~ s/\s/_/g;
5066                         }
5067                         elsif ($line =~ /^\t(.*)$/) {
5068                                 printf("%6s %10s %s\n", $rev, $authors{$rev}, $1);
5069                         }
5070                 }
5071         }
5072         command_close_pipe($fh, $ctx);
5075 package Git::SVN::Migration;
5076 # these version numbers do NOT correspond to actual version numbers
5077 # of git nor git-svn.  They are just relative.
5079 # v0 layout: .git/$id/info/url, refs/heads/$id-HEAD
5081 # v1 layout: .git/$id/info/url, refs/remotes/$id
5083 # v2 layout: .git/svn/$id/info/url, refs/remotes/$id
5085 # v3 layout: .git/svn/$id, refs/remotes/$id
5086 #            - info/url may remain for backwards compatibility
5087 #            - this is what we migrate up to this layout automatically,
5088 #            - this will be used by git svn init on single branches
5089 # v3.1 layout (auto migrated):
5090 #            - .rev_db => .rev_db.$UUID, .rev_db will remain as a symlink
5091 #              for backwards compatibility
5093 # v4 layout: .git/svn/$repo_id/$id, refs/remotes/$repo_id/$id
5094 #            - this is only created for newly multi-init-ed
5095 #              repositories.  Similar in spirit to the
5096 #              --use-separate-remotes option in git-clone (now default)
5097 #            - we do not automatically migrate to this (following
5098 #              the example set by core git)
5100 # v5 layout: .rev_db.$UUID => .rev_map.$UUID
5101 #            - newer, more-efficient format that uses 24-bytes per record
5102 #              with no filler space.
5103 #            - use xxd -c24 < .rev_map.$UUID to view and debug
5104 #            - This is a one-way migration, repositories updated to the
5105 #              new format will not be able to use old git-svn without
5106 #              rebuilding the .rev_db.  Rebuilding the rev_db is not
5107 #              possible if noMetadata or useSvmProps are set; but should
5108 #              be no problem for users that use the (sensible) defaults.
5109 use strict;
5110 use warnings;
5111 use Carp qw/croak/;
5112 use File::Path qw/mkpath/;
5113 use File::Basename qw/dirname basename/;
5114 use vars qw/$_minimize/;
5116 sub migrate_from_v0 {
5117         my $git_dir = $ENV{GIT_DIR};
5118         return undef unless -d $git_dir;
5119         my ($fh, $ctx) = command_output_pipe(qw/rev-parse --symbolic --all/);
5120         my $migrated = 0;
5121         while (<$fh>) {
5122                 chomp;
5123                 my ($id, $orig_ref) = ($_, $_);
5124                 next unless $id =~ s#^refs/heads/(.+)-HEAD$#$1#;
5125                 next unless -f "$git_dir/$id/info/url";
5126                 my $new_ref = "refs/remotes/$id";
5127                 if (::verify_ref("$new_ref^0")) {
5128                         print STDERR "W: $orig_ref is probably an old ",
5129                                      "branch used by an ancient version of ",
5130                                      "git-svn.\n",
5131                                      "However, $new_ref also exists.\n",
5132                                      "We will not be able ",
5133                                      "to use this branch until this ",
5134                                      "ambiguity is resolved.\n";
5135                         next;
5136                 }
5137                 print STDERR "Migrating from v0 layout...\n" if !$migrated;
5138                 print STDERR "Renaming ref: $orig_ref => $new_ref\n";
5139                 command_noisy('update-ref', $new_ref, $orig_ref);
5140                 command_noisy('update-ref', '-d', $orig_ref, $orig_ref);
5141                 $migrated++;
5142         }
5143         command_close_pipe($fh, $ctx);
5144         print STDERR "Done migrating from v0 layout...\n" if $migrated;
5145         $migrated;
5148 sub migrate_from_v1 {
5149         my $git_dir = $ENV{GIT_DIR};
5150         my $migrated = 0;
5151         return $migrated unless -d $git_dir;
5152         my $svn_dir = "$git_dir/svn";
5154         # just in case somebody used 'svn' as their $id at some point...
5155         return $migrated if -d $svn_dir && ! -f "$svn_dir/info/url";
5157         print STDERR "Migrating from a git-svn v1 layout...\n";
5158         mkpath([$svn_dir]);
5159         print STDERR "Data from a previous version of git-svn exists, but\n\t",
5160                      "$svn_dir\n\t(required for this version ",
5161                      "($::VERSION) of git-svn) does not exist.\n";
5162         my ($fh, $ctx) = command_output_pipe(qw/rev-parse --symbolic --all/);
5163         while (<$fh>) {
5164                 my $x = $_;
5165                 next unless $x =~ s#^refs/remotes/##;
5166                 chomp $x;
5167                 next unless -f "$git_dir/$x/info/url";
5168                 my $u = eval { ::file_to_s("$git_dir/$x/info/url") };
5169                 next unless $u;
5170                 my $dn = dirname("$git_dir/svn/$x");
5171                 mkpath([$dn]) unless -d $dn;
5172                 if ($x eq 'svn') { # they used 'svn' as GIT_SVN_ID:
5173                         mkpath(["$git_dir/svn/svn"]);
5174                         print STDERR " - $git_dir/$x/info => ",
5175                                         "$git_dir/svn/$x/info\n";
5176                         rename "$git_dir/$x/info", "$git_dir/svn/$x/info" or
5177                                croak "$!: $x";
5178                         # don't worry too much about these, they probably
5179                         # don't exist with repos this old (save for index,
5180                         # and we can easily regenerate that)
5181                         foreach my $f (qw/unhandled.log index .rev_db/) {
5182                                 rename "$git_dir/$x/$f", "$git_dir/svn/$x/$f";
5183                         }
5184                 } else {
5185                         print STDERR " - $git_dir/$x => $git_dir/svn/$x\n";
5186                         rename "$git_dir/$x", "$git_dir/svn/$x" or
5187                                croak "$!: $x";
5188                 }
5189                 $migrated++;
5190         }
5191         command_close_pipe($fh, $ctx);
5192         print STDERR "Done migrating from a git-svn v1 layout\n";
5193         $migrated;
5196 sub read_old_urls {
5197         my ($l_map, $pfx, $path) = @_;
5198         my @dir;
5199         foreach (<$path/*>) {
5200                 if (-r "$_/info/url") {
5201                         $pfx .= '/' if $pfx && $pfx !~ m!/$!;
5202                         my $ref_id = $pfx . basename $_;
5203                         my $url = ::file_to_s("$_/info/url");
5204                         $l_map->{$ref_id} = $url;
5205                 } elsif (-d $_) {
5206                         push @dir, $_;
5207                 }
5208         }
5209         foreach (@dir) {
5210                 my $x = $_;
5211                 $x =~ s!^\Q$ENV{GIT_DIR}\E/svn/!!o;
5212                 read_old_urls($l_map, $x, $_);
5213         }
5216 sub migrate_from_v2 {
5217         my @cfg = command(qw/config -l/);
5218         return if grep /^svn-remote\..+\.url=/, @cfg;
5219         my %l_map;
5220         read_old_urls(\%l_map, '', "$ENV{GIT_DIR}/svn");
5221         my $migrated = 0;
5223         foreach my $ref_id (sort keys %l_map) {
5224                 eval { Git::SVN->init($l_map{$ref_id}, '', undef, $ref_id) };
5225                 if ($@) {
5226                         Git::SVN->init($l_map{$ref_id}, '', $ref_id, $ref_id);
5227                 }
5228                 $migrated++;
5229         }
5230         $migrated;
5233 sub minimize_connections {
5234         my $r = Git::SVN::read_all_remotes();
5235         my $new_urls = {};
5236         my $root_repos = {};
5237         foreach my $repo_id (keys %$r) {
5238                 my $url = $r->{$repo_id}->{url} or next;
5239                 my $fetch = $r->{$repo_id}->{fetch} or next;
5240                 my $ra = Git::SVN::Ra->new($url);
5242                 # skip existing cases where we already connect to the root
5243                 if (($ra->{url} eq $ra->{repos_root}) ||
5244                     ($ra->{repos_root} eq $repo_id)) {
5245                         $root_repos->{$ra->{url}} = $repo_id;
5246                         next;
5247                 }
5249                 my $root_ra = Git::SVN::Ra->new($ra->{repos_root});
5250                 my $root_path = $ra->{url};
5251                 $root_path =~ s#^\Q$ra->{repos_root}\E(/|$)##;
5252                 foreach my $path (keys %$fetch) {
5253                         my $ref_id = $fetch->{$path};
5254                         my $gs = Git::SVN->new($ref_id, $repo_id, $path);
5256                         # make sure we can read when connecting to
5257                         # a higher level of a repository
5258                         my ($last_rev, undef) = $gs->last_rev_commit;
5259                         if (!defined $last_rev) {
5260                                 $last_rev = eval {
5261                                         $root_ra->get_latest_revnum;
5262                                 };
5263                                 next if $@;
5264                         }
5265                         my $new = $root_path;
5266                         $new .= length $path ? "/$path" : '';
5267                         eval {
5268                                 $root_ra->get_log([$new], $last_rev, $last_rev,
5269                                                   0, 0, 1, sub { });
5270                         };
5271                         next if $@;
5272                         $new_urls->{$ra->{repos_root}}->{$new} =
5273                                 { ref_id => $ref_id,
5274                                   old_repo_id => $repo_id,
5275                                   old_path => $path };
5276                 }
5277         }
5279         my @emptied;
5280         foreach my $url (keys %$new_urls) {
5281                 # see if we can re-use an existing [svn-remote "repo_id"]
5282                 # instead of creating a(n ugly) new section:
5283                 my $repo_id = $root_repos->{$url} || $url;
5285                 my $fetch = $new_urls->{$url};
5286                 foreach my $path (keys %$fetch) {
5287                         my $x = $fetch->{$path};
5288                         Git::SVN->init($url, $path, $repo_id, $x->{ref_id});
5289                         my $pfx = "svn-remote.$x->{old_repo_id}";
5291                         my $old_fetch = quotemeta("$x->{old_path}:".
5292                                                   "refs/remotes/$x->{ref_id}");
5293                         command_noisy(qw/config --unset/,
5294                                       "$pfx.fetch", '^'. $old_fetch . '$');
5295                         delete $r->{$x->{old_repo_id}}->
5296                                {fetch}->{$x->{old_path}};
5297                         if (!keys %{$r->{$x->{old_repo_id}}->{fetch}}) {
5298                                 command_noisy(qw/config --unset/,
5299                                               "$pfx.url");
5300                                 push @emptied, $x->{old_repo_id}
5301                         }
5302                 }
5303         }
5304         if (@emptied) {
5305                 my $file = $ENV{GIT_CONFIG} || "$ENV{GIT_DIR}/config";
5306                 print STDERR <<EOF;
5307 The following [svn-remote] sections in your config file ($file) are empty
5308 and can be safely removed:
5309 EOF
5310                 print STDERR "[svn-remote \"$_\"]\n" foreach @emptied;
5311         }
5314 sub migration_check {
5315         migrate_from_v0();
5316         migrate_from_v1();
5317         migrate_from_v2();
5318         minimize_connections() if $_minimize;
5321 package Git::IndexInfo;
5322 use strict;
5323 use warnings;
5324 use Git qw/command_input_pipe command_close_pipe/;
5326 sub new {
5327         my ($class) = @_;
5328         my ($gui, $ctx) = command_input_pipe(qw/update-index -z --index-info/);
5329         bless { gui => $gui, ctx => $ctx, nr => 0}, $class;
5332 sub remove {
5333         my ($self, $path) = @_;
5334         if (print { $self->{gui} } '0 ', 0 x 40, "\t", $path, "\0") {
5335                 return ++$self->{nr};
5336         }
5337         undef;
5340 sub update {
5341         my ($self, $mode, $hash, $path) = @_;
5342         if (print { $self->{gui} } $mode, ' ', $hash, "\t", $path, "\0") {
5343                 return ++$self->{nr};
5344         }
5345         undef;
5348 sub DESTROY {
5349         my ($self) = @_;
5350         command_close_pipe($self->{gui}, $self->{ctx});
5353 package Git::SVN::GlobSpec;
5354 use strict;
5355 use warnings;
5357 sub new {
5358         my ($class, $glob) = @_;
5359         my $re = $glob;
5360         $re =~ s!/+$!!g; # no need for trailing slashes
5361         $re =~ m!^([^*]*)(\*(?:/\*)*)([^*]*)$!;
5362         my $temp = $re;
5363         my ($left, $right) = ($1, $3);
5364         $re = $2;
5365         my $depth = $re =~ tr/*/*/;
5366         if ($depth != $temp =~ tr/*/*/) {
5367                 die "Only one set of wildcard directories " .
5368                         "(e.g. '*' or '*/*/*') is supported: '$glob'\n";
5369         }
5370         if ($depth == 0) {
5371                 die "One '*' is needed for glob: '$glob'\n";
5372         }
5373         $re =~ s!\*!\[^/\]*!g;
5374         $re = quotemeta($left) . "($re)" . quotemeta($right);
5375         if (length $left && !($left =~ s!/+$!!g)) {
5376                 die "Missing trailing '/' on left side of: '$glob' ($left)\n";
5377         }
5378         if (length $right && !($right =~ s!^/+!!g)) {
5379                 die "Missing leading '/' on right side of: '$glob' ($right)\n";
5380         }
5381         my $left_re = qr/^\/\Q$left\E(\/|$)/;
5382         bless { left => $left, right => $right, left_regex => $left_re,
5383                 regex => qr/$re/, glob => $glob, depth => $depth }, $class;
5386 sub full_path {
5387         my ($self, $path) = @_;
5388         return (length $self->{left} ? "$self->{left}/" : '') .
5389                $path . (length $self->{right} ? "/$self->{right}" : '');
5392 __END__
5394 Data structures:
5397 $remotes = { # returned by read_all_remotes()
5398         'svn' => {
5399                 # svn-remote.svn.url=https://svn.musicpd.org
5400                 url => 'https://svn.musicpd.org',
5401                 # svn-remote.svn.fetch=mpd/trunk:trunk
5402                 fetch => {
5403                         'mpd/trunk' => 'trunk',
5404                 },
5405                 # svn-remote.svn.tags=mpd/tags/*:tags/*
5406                 tags => {
5407                         path => {
5408                                 left => 'mpd/tags',
5409                                 right => '',
5410                                 regex => qr!mpd/tags/([^/]+)$!,
5411                                 glob => 'tags/*',
5412                         },
5413                         ref => {
5414                                 left => 'tags',
5415                                 right => '',
5416                                 regex => qr!tags/([^/]+)$!,
5417                                 glob => 'tags/*',
5418                         },
5419                 }
5420         }
5421 };
5423 $log_entry hashref as returned by libsvn_log_entry()
5425         log => 'whitespace-formatted log entry
5426 ',                                              # trailing newline is preserved
5427         revision => '8',                        # integer
5428         date => '2004-02-24T17:01:44.108345Z',  # commit date
5429         author => 'committer name'
5430 };
5433 # this is generated by generate_diff();
5434 @mods = array of diff-index line hashes, each element represents one line
5435         of diff-index output
5437 diff-index line ($m hash)
5439         mode_a => first column of diff-index output, no leading ':',
5440         mode_b => second column of diff-index output,
5441         sha1_b => sha1sum of the final blob,
5442         chg => change type [MCRADT],
5443         file_a => original file name of a file (iff chg is 'C' or 'R')
5444         file_b => new/current file name of a file (any chg)
5448 # retval of read_url_paths{,_all}();
5449 $l_map = {
5450         # repository root url
5451         'https://svn.musicpd.org' => {
5452                 # repository path               # GIT_SVN_ID
5453                 'mpd/trunk'             =>      'trunk',
5454                 'mpd/tags/0.11.5'       =>      'tags/0.11.5',
5455         },
5458 Notes:
5459         I don't trust the each() function on unless I created %hash myself
5460         because the internal iterator may not have started at base.