Code

mergetools: use the correct tool for Beyond Compare 3 on Windows
[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 5.008;
5 use warnings;
6 use strict;
7 use vars qw/    $AUTHOR $VERSION
8                 $sha1 $sha1_short $_revision $_repository
9                 $_q $_authors $_authors_prog %users/;
10 $AUTHOR = 'Eric Wong <normalperson@yhbt.net>';
11 $VERSION = '@@GIT_VERSION@@';
13 # From which subdir have we been invoked?
14 my $cmd_dir_prefix = eval {
15         command_oneline([qw/rev-parse --show-prefix/], STDERR => 0)
16 } || '';
18 my $git_dir_user_set = 1 if defined $ENV{GIT_DIR};
19 $ENV{GIT_DIR} ||= '.git';
20 $Git::SVN::default_repo_id = 'svn';
21 $Git::SVN::default_ref_id = $ENV{GIT_SVN_ID} || 'git-svn';
22 $Git::SVN::Ra::_log_window_size = 100;
23 $Git::SVN::_minimize_url = 'unset';
25 if (! exists $ENV{SVN_SSH} && exists $ENV{GIT_SSH}) {
26         $ENV{SVN_SSH} = $ENV{GIT_SSH};
27 }
29 if (exists $ENV{SVN_SSH} && $^O eq 'msys') {
30         $ENV{SVN_SSH} =~ s/\\/\\\\/g;
31         $ENV{SVN_SSH} =~ s/(.*)/"$1"/;
32 }
34 $Git::SVN::Log::TZ = $ENV{TZ};
35 $ENV{TZ} = 'UTC';
36 $| = 1; # unbuffer STDOUT
38 sub fatal (@) { print STDERR "@_\n"; exit 1 }
39 sub _req_svn {
40         require SVN::Core; # use()-ing this causes segfaults for me... *shrug*
41         require SVN::Ra;
42         require SVN::Delta;
43         if ($SVN::Core::VERSION lt '1.1.0') {
44                 fatal "Need SVN::Core 1.1.0 or better (got $SVN::Core::VERSION)";
45         }
46 }
47 my $can_compress = eval { require Compress::Zlib; 1};
48 push @Git::SVN::Ra::ISA, 'SVN::Ra';
49 push @SVN::Git::Editor::ISA, 'SVN::Delta::Editor';
50 push @SVN::Git::Fetcher::ISA, 'SVN::Delta::Editor';
51 use Carp qw/croak/;
52 use Digest::MD5;
53 use IO::File qw//;
54 use File::Basename qw/dirname basename/;
55 use File::Path qw/mkpath/;
56 use File::Spec;
57 use File::Find;
58 use Getopt::Long qw/:config gnu_getopt no_ignore_case auto_abbrev/;
59 use IPC::Open3;
60 use Git;
61 use Memoize;  # core since 5.8.0, Jul 2002
63 BEGIN {
64         # import functions from Git into our packages, en masse
65         no strict 'refs';
66         foreach (qw/command command_oneline command_noisy command_output_pipe
67                     command_input_pipe command_close_pipe
68                     command_bidi_pipe command_close_bidi_pipe/) {
69                 for my $package ( qw(SVN::Git::Editor SVN::Git::Fetcher
70                         Git::SVN::Migration Git::SVN::Log Git::SVN),
71                         __PACKAGE__) {
72                         *{"${package}::$_"} = \&{"Git::$_"};
73                 }
74         }
75         Memoize::memoize 'Git::config';
76         Memoize::memoize 'Git::config_bool';
77 }
79 my ($SVN);
81 $sha1 = qr/[a-f\d]{40}/;
82 $sha1_short = qr/[a-f\d]{4,40}/;
83 my ($_stdin, $_help, $_edit,
84         $_message, $_file, $_branch_dest,
85         $_template, $_shared,
86         $_version, $_fetch_all, $_no_rebase, $_fetch_parent,
87         $_merge, $_strategy, $_dry_run, $_local,
88         $_prefix, $_no_checkout, $_url, $_verbose,
89         $_git_format, $_commit_url, $_tag, $_merge_info);
90 $Git::SVN::_follow_parent = 1;
91 $SVN::Git::Fetcher::_placeholder_filename = ".gitignore";
92 $_q ||= 0;
93 my %remote_opts = ( 'username=s' => \$Git::SVN::Prompt::_username,
94                     'config-dir=s' => \$Git::SVN::Ra::config_dir,
95                     'no-auth-cache' => \$Git::SVN::Prompt::_no_auth_cache,
96                     'ignore-paths=s' => \$SVN::Git::Fetcher::_ignore_regex );
97 my %fc_opts = ( 'follow-parent|follow!' => \$Git::SVN::_follow_parent,
98                 'authors-file|A=s' => \$_authors,
99                 'authors-prog=s' => \$_authors_prog,
100                 'repack:i' => \$Git::SVN::_repack,
101                 'noMetadata' => \$Git::SVN::_no_metadata,
102                 'useSvmProps' => \$Git::SVN::_use_svm_props,
103                 'useSvnsyncProps' => \$Git::SVN::_use_svnsync_props,
104                 'log-window-size=i' => \$Git::SVN::Ra::_log_window_size,
105                 'no-checkout' => \$_no_checkout,
106                 'quiet|q+' => \$_q,
107                 'repack-flags|repack-args|repack-opts=s' =>
108                    \$Git::SVN::_repack_flags,
109                 'use-log-author' => \$Git::SVN::_use_log_author,
110                 'add-author-from' => \$Git::SVN::_add_author_from,
111                 'localtime' => \$Git::SVN::_localtime,
112                 %remote_opts );
114 my ($_trunk, @_tags, @_branches, $_stdlayout);
115 my %icv;
116 my %init_opts = ( 'template=s' => \$_template, 'shared:s' => \$_shared,
117                   'trunk|T=s' => \$_trunk, 'tags|t=s@' => \@_tags,
118                   'branches|b=s@' => \@_branches, 'prefix=s' => \$_prefix,
119                   'stdlayout|s' => \$_stdlayout,
120                   'minimize-url|m!' => \$Git::SVN::_minimize_url,
121                   'no-metadata' => sub { $icv{noMetadata} = 1 },
122                   'use-svm-props' => sub { $icv{useSvmProps} = 1 },
123                   'use-svnsync-props' => sub { $icv{useSvnsyncProps} = 1 },
124                   'rewrite-root=s' => sub { $icv{rewriteRoot} = $_[1] },
125                   'rewrite-uuid=s' => sub { $icv{rewriteUUID} = $_[1] },
126                   %remote_opts );
127 my %cmt_opts = ( 'edit|e' => \$_edit,
128                 'rmdir' => \$SVN::Git::Editor::_rmdir,
129                 'find-copies-harder' => \$SVN::Git::Editor::_find_copies_harder,
130                 'l=i' => \$SVN::Git::Editor::_rename_limit,
131                 'copy-similarity|C=i'=> \$SVN::Git::Editor::_cp_similarity
132 );
134 my %cmd = (
135         fetch => [ \&cmd_fetch, "Download new revisions from SVN",
136                         { 'revision|r=s' => \$_revision,
137                           'fetch-all|all' => \$_fetch_all,
138                           'parent|p' => \$_fetch_parent,
139                            %fc_opts } ],
140         clone => [ \&cmd_clone, "Initialize and fetch revisions",
141                         { 'revision|r=s' => \$_revision,
142                           'preserve-empty-dirs' =>
143                                 \$SVN::Git::Fetcher::_preserve_empty_dirs,
144                           'placeholder-filename=s' =>
145                                 \$SVN::Git::Fetcher::_placeholder_filename,
146                            %fc_opts, %init_opts } ],
147         init => [ \&cmd_init, "Initialize a repo for tracking" .
148                           " (requires URL argument)",
149                           \%init_opts ],
150         'multi-init' => [ \&cmd_multi_init,
151                           "Deprecated alias for ".
152                           "'$0 init -T<trunk> -b<branches> -t<tags>'",
153                           \%init_opts ],
154         dcommit => [ \&cmd_dcommit,
155                      'Commit several diffs to merge with upstream',
156                         { 'merge|m|M' => \$_merge,
157                           'strategy|s=s' => \$_strategy,
158                           'verbose|v' => \$_verbose,
159                           'dry-run|n' => \$_dry_run,
160                           'fetch-all|all' => \$_fetch_all,
161                           'commit-url=s' => \$_commit_url,
162                           'revision|r=i' => \$_revision,
163                           'no-rebase' => \$_no_rebase,
164                           'mergeinfo=s' => \$_merge_info,
165                         %cmt_opts, %fc_opts } ],
166         branch => [ \&cmd_branch,
167                     'Create a branch in the SVN repository',
168                     { 'message|m=s' => \$_message,
169                       'destination|d=s' => \$_branch_dest,
170                       'dry-run|n' => \$_dry_run,
171                       'tag|t' => \$_tag,
172                       'username=s' => \$Git::SVN::Prompt::_username,
173                       'commit-url=s' => \$_commit_url } ],
174         tag => [ sub { $_tag = 1; cmd_branch(@_) },
175                  'Create a tag in the SVN repository',
176                  { 'message|m=s' => \$_message,
177                    'destination|d=s' => \$_branch_dest,
178                    'dry-run|n' => \$_dry_run,
179                    'username=s' => \$Git::SVN::Prompt::_username,
180                    'commit-url=s' => \$_commit_url } ],
181         'set-tree' => [ \&cmd_set_tree,
182                         "Set an SVN repository to a git tree-ish",
183                         { 'stdin' => \$_stdin, %cmt_opts, %fc_opts, } ],
184         'create-ignore' => [ \&cmd_create_ignore,
185                              'Create a .gitignore per svn:ignore',
186                              { 'revision|r=i' => \$_revision
187                              } ],
188         'mkdirs' => [ \&cmd_mkdirs ,
189                       "recreate empty directories after a checkout",
190                       { 'revision|r=i' => \$_revision } ],
191         'propget' => [ \&cmd_propget,
192                        'Print the value of a property on a file or directory',
193                        { 'revision|r=i' => \$_revision } ],
194         'proplist' => [ \&cmd_proplist,
195                        'List all properties of a file or directory',
196                        { 'revision|r=i' => \$_revision } ],
197         'show-ignore' => [ \&cmd_show_ignore, "Show svn:ignore listings",
198                         { 'revision|r=i' => \$_revision
199                         } ],
200         'show-externals' => [ \&cmd_show_externals, "Show svn:externals listings",
201                         { 'revision|r=i' => \$_revision
202                         } ],
203         'multi-fetch' => [ \&cmd_multi_fetch,
204                            "Deprecated alias for $0 fetch --all",
205                            { 'revision|r=s' => \$_revision, %fc_opts } ],
206         'migrate' => [ sub { },
207                        # no-op, we automatically run this anyways,
208                        'Migrate configuration/metadata/layout from
209                         previous versions of git-svn',
210                        { 'minimize' => \$Git::SVN::Migration::_minimize,
211                          %remote_opts } ],
212         'log' => [ \&Git::SVN::Log::cmd_show_log, 'Show commit logs',
213                         { 'limit=i' => \$Git::SVN::Log::limit,
214                           'revision|r=s' => \$_revision,
215                           'verbose|v' => \$Git::SVN::Log::verbose,
216                           'incremental' => \$Git::SVN::Log::incremental,
217                           'oneline' => \$Git::SVN::Log::oneline,
218                           'show-commit' => \$Git::SVN::Log::show_commit,
219                           'non-recursive' => \$Git::SVN::Log::non_recursive,
220                           'authors-file|A=s' => \$_authors,
221                           'color' => \$Git::SVN::Log::color,
222                           'pager=s' => \$Git::SVN::Log::pager
223                         } ],
224         'find-rev' => [ \&cmd_find_rev,
225                         "Translate between SVN revision numbers and tree-ish",
226                         {} ],
227         'rebase' => [ \&cmd_rebase, "Fetch and rebase your working directory",
228                         { 'merge|m|M' => \$_merge,
229                           'verbose|v' => \$_verbose,
230                           'strategy|s=s' => \$_strategy,
231                           'local|l' => \$_local,
232                           'fetch-all|all' => \$_fetch_all,
233                           'dry-run|n' => \$_dry_run,
234                           %fc_opts } ],
235         'commit-diff' => [ \&cmd_commit_diff,
236                            'Commit a diff between two trees',
237                         { 'message|m=s' => \$_message,
238                           'file|F=s' => \$_file,
239                           'revision|r=s' => \$_revision,
240                         %cmt_opts } ],
241         'info' => [ \&cmd_info,
242                     "Show info about the latest SVN revision
243                      on the current branch",
244                     { 'url' => \$_url, } ],
245         'blame' => [ \&Git::SVN::Log::cmd_blame,
246                     "Show what revision and author last modified each line of a file",
247                     { 'git-format' => \$_git_format } ],
248         'reset' => [ \&cmd_reset,
249                      "Undo fetches back to the specified SVN revision",
250                      { 'revision|r=s' => \$_revision,
251                        'parent|p' => \$_fetch_parent } ],
252         'gc' => [ \&cmd_gc,
253                   "Compress unhandled.log files in .git/svn and remove " .
254                   "index files in .git/svn",
255                 {} ],
256 );
258 my $cmd;
259 for (my $i = 0; $i < @ARGV; $i++) {
260         if (defined $cmd{$ARGV[$i]}) {
261                 $cmd = $ARGV[$i];
262                 splice @ARGV, $i, 1;
263                 last;
264         } elsif ($ARGV[$i] eq 'help') {
265                 $cmd = $ARGV[$i+1];
266                 usage(0);
267         }
268 };
270 # make sure we're always running at the top-level working directory
271 unless ($cmd && $cmd =~ /(?:clone|init|multi-init)$/) {
272         unless (-d $ENV{GIT_DIR}) {
273                 if ($git_dir_user_set) {
274                         die "GIT_DIR=$ENV{GIT_DIR} explicitly set, ",
275                             "but it is not a directory\n";
276                 }
277                 my $git_dir = delete $ENV{GIT_DIR};
278                 my $cdup = undef;
279                 git_cmd_try {
280                         $cdup = command_oneline(qw/rev-parse --show-cdup/);
281                         $git_dir = '.' unless ($cdup);
282                         chomp $cdup if ($cdup);
283                         $cdup = "." unless ($cdup && length $cdup);
284                 } "Already at toplevel, but $git_dir not found\n";
285                 chdir $cdup or die "Unable to chdir up to '$cdup'\n";
286                 unless (-d $git_dir) {
287                         die "$git_dir still not found after going to ",
288                             "'$cdup'\n";
289                 }
290                 $ENV{GIT_DIR} = $git_dir;
291         }
292         $_repository = Git->repository(Repository => $ENV{GIT_DIR});
295 my %opts = %{$cmd{$cmd}->[2]} if (defined $cmd);
297 read_git_config(\%opts);
298 if ($cmd && ($cmd eq 'log' || $cmd eq 'blame')) {
299         Getopt::Long::Configure('pass_through');
301 my $rv = GetOptions(%opts, 'h|H' => \$_help, 'version|V' => \$_version,
302                     'minimize-connections' => \$Git::SVN::Migration::_minimize,
303                     'id|i=s' => \$Git::SVN::default_ref_id,
304                     'svn-remote|remote|R=s' => sub {
305                        $Git::SVN::no_reuse_existing = 1;
306                        $Git::SVN::default_repo_id = $_[1] });
307 exit 1 if (!$rv && $cmd && $cmd ne 'log');
309 usage(0) if $_help;
310 version() if $_version;
311 usage(1) unless defined $cmd;
312 load_authors() if $_authors;
313 if (defined $_authors_prog) {
314         $_authors_prog = "'" . File::Spec->rel2abs($_authors_prog) . "'";
317 unless ($cmd =~ /^(?:clone|init|multi-init|commit-diff)$/) {
318         Git::SVN::Migration::migration_check();
320 Git::SVN::init_vars();
321 eval {
322         Git::SVN::verify_remotes_sanity();
323         $cmd{$cmd}->[0]->(@ARGV);
324 };
325 fatal $@ if $@;
326 post_fetch_checkout();
327 exit 0;
329 ####################### primary functions ######################
330 sub usage {
331         my $exit = shift || 0;
332         my $fd = $exit ? \*STDERR : \*STDOUT;
333         print $fd <<"";
334 git-svn - bidirectional operations between a single Subversion tree and git
335 Usage: git svn <command> [options] [arguments]\n
337         print $fd "Available commands:\n" unless $cmd;
339         foreach (sort keys %cmd) {
340                 next if $cmd && $cmd ne $_;
341                 next if /^multi-/; # don't show deprecated commands
342                 print $fd '  ',pack('A17',$_),$cmd{$_}->[1],"\n";
343                 foreach (sort keys %{$cmd{$_}->[2]}) {
344                         # mixed-case options are for .git/config only
345                         next if /[A-Z]/ && /^[a-z]+$/i;
346                         # prints out arguments as they should be passed:
347                         my $x = s#[:=]s$## ? '<arg>' : s#[:=]i$## ? '<num>' : '';
348                         print $fd ' ' x 21, join(', ', map { length $_ > 1 ?
349                                                         "--$_" : "-$_" }
350                                                 split /\|/,$_)," $x\n";
351                 }
352         }
353         print $fd <<"";
354 \nGIT_SVN_ID may be set in the environment or via the --id/-i switch to an
355 arbitrary identifier if you're tracking multiple SVN branches/repositories in
356 one git repository and want to keep them separate.  See git-svn(1) for more
357 information.
359         exit $exit;
362 sub version {
363         ::_req_svn();
364         print "git-svn version $VERSION (svn $SVN::Core::VERSION)\n";
365         exit 0;
368 sub do_git_init_db {
369         unless (-d $ENV{GIT_DIR}) {
370                 my @init_db = ('init');
371                 push @init_db, "--template=$_template" if defined $_template;
372                 if (defined $_shared) {
373                         if ($_shared =~ /[a-z]/) {
374                                 push @init_db, "--shared=$_shared";
375                         } else {
376                                 push @init_db, "--shared";
377                         }
378                 }
379                 command_noisy(@init_db);
380                 $_repository = Git->repository(Repository => ".git");
381         }
382         my $set;
383         my $pfx = "svn-remote.$Git::SVN::default_repo_id";
384         foreach my $i (keys %icv) {
385                 die "'$set' and '$i' cannot both be set\n" if $set;
386                 next unless defined $icv{$i};
387                 command_noisy('config', "$pfx.$i", $icv{$i});
388                 $set = $i;
389         }
390         my $ignore_regex = \$SVN::Git::Fetcher::_ignore_regex;
391         command_noisy('config', "$pfx.ignore-paths", $$ignore_regex)
392                 if defined $$ignore_regex;
394         if (defined $SVN::Git::Fetcher::_preserve_empty_dirs) {
395                 my $fname = \$SVN::Git::Fetcher::_placeholder_filename;
396                 command_noisy('config', "$pfx.preserve-empty-dirs", 'true');
397                 command_noisy('config', "$pfx.placeholder-filename", $$fname);
398         }
401 sub init_subdir {
402         my $repo_path = shift or return;
403         mkpath([$repo_path]) unless -d $repo_path;
404         chdir $repo_path or die "Couldn't chdir to $repo_path: $!\n";
405         $ENV{GIT_DIR} = '.git';
406         $_repository = Git->repository(Repository => $ENV{GIT_DIR});
409 sub cmd_clone {
410         my ($url, $path) = @_;
411         if (!defined $path &&
412             (defined $_trunk || @_branches || @_tags ||
413              defined $_stdlayout) &&
414             $url !~ m#^[a-z\+]+://#) {
415                 $path = $url;
416         }
417         $path = basename($url) if !defined $path || !length $path;
418         my $authors_absolute = $_authors ? File::Spec->rel2abs($_authors) : "";
419         cmd_init($url, $path);
420         command_oneline('config', 'svn.authorsfile', $authors_absolute)
421             if $_authors;
422         Git::SVN::fetch_all($Git::SVN::default_repo_id);
425 sub cmd_init {
426         if (defined $_stdlayout) {
427                 $_trunk = 'trunk' if (!defined $_trunk);
428                 @_tags = 'tags' if (! @_tags);
429                 @_branches = 'branches' if (! @_branches);
430         }
431         if (defined $_trunk || @_branches || @_tags) {
432                 return cmd_multi_init(@_);
433         }
434         my $url = shift or die "SVN repository location required ",
435                                "as a command-line argument\n";
436         $url = canonicalize_url($url);
437         init_subdir(@_);
438         do_git_init_db();
440         if ($Git::SVN::_minimize_url eq 'unset') {
441                 $Git::SVN::_minimize_url = 0;
442         }
444         Git::SVN->init($url);
447 sub cmd_fetch {
448         if (grep /^\d+=./, @_) {
449                 die "'<rev>=<commit>' fetch arguments are ",
450                     "no longer supported.\n";
451         }
452         my ($remote) = @_;
453         if (@_ > 1) {
454                 die "Usage: $0 fetch [--all] [--parent] [svn-remote]\n";
455         }
456         $Git::SVN::no_reuse_existing = undef;
457         if ($_fetch_parent) {
458                 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
459                 unless ($gs) {
460                         die "Unable to determine upstream SVN information from ",
461                             "working tree history\n";
462                 }
463                 # just fetch, don't checkout.
464                 $_no_checkout = 'true';
465                 $_fetch_all ? $gs->fetch_all : $gs->fetch;
466         } elsif ($_fetch_all) {
467                 cmd_multi_fetch();
468         } else {
469                 $remote ||= $Git::SVN::default_repo_id;
470                 Git::SVN::fetch_all($remote, Git::SVN::read_all_remotes());
471         }
474 sub cmd_set_tree {
475         my (@commits) = @_;
476         if ($_stdin || !@commits) {
477                 print "Reading from stdin...\n";
478                 @commits = ();
479                 while (<STDIN>) {
480                         if (/\b($sha1_short)\b/o) {
481                                 unshift @commits, $1;
482                         }
483                 }
484         }
485         my @revs;
486         foreach my $c (@commits) {
487                 my @tmp = command('rev-parse',$c);
488                 if (scalar @tmp == 1) {
489                         push @revs, $tmp[0];
490                 } elsif (scalar @tmp > 1) {
491                         push @revs, reverse(command('rev-list',@tmp));
492                 } else {
493                         fatal "Failed to rev-parse $c";
494                 }
495         }
496         my $gs = Git::SVN->new;
497         my ($r_last, $cmt_last) = $gs->last_rev_commit;
498         $gs->fetch;
499         if (defined $gs->{last_rev} && $r_last != $gs->{last_rev}) {
500                 fatal "There are new revisions that were fetched ",
501                       "and need to be merged (or acknowledged) ",
502                       "before committing.\nlast rev: $r_last\n",
503                       " current: $gs->{last_rev}";
504         }
505         $gs->set_tree($_) foreach @revs;
506         print "Done committing ",scalar @revs," revisions to SVN\n";
507         unlink $gs->{index};
510 sub split_merge_info_range {
511         my ($range) = @_;
512         if ($range =~ /(\d+)-(\d+)/) {
513                 return (int($1), int($2));
514         } else {
515                 return (int($range), int($range));
516         }
519 sub combine_ranges {
520         my ($in) = @_;
522         my @fnums = ();
523         my @arr = split(/,/, $in);
524         for my $element (@arr) {
525                 my ($start, $end) = split_merge_info_range($element);
526                 push @fnums, $start;
527         }
529         my @sorted = @arr [ sort {
530                 $fnums[$a] <=> $fnums[$b]
531         } 0..$#arr ];
533         my @return = ();
534         my $last = -1;
535         my $first = -1;
536         for my $element (@sorted) {
537                 my ($start, $end) = split_merge_info_range($element);
539                 if ($last == -1) {
540                         $first = $start;
541                         $last = $end;
542                         next;
543                 }
544                 if ($start <= $last+1) {
545                         if ($end > $last) {
546                                 $last = $end;
547                         }
548                         next;
549                 }
550                 if ($first == $last) {
551                         push @return, "$first";
552                 } else {
553                         push @return, "$first-$last";
554                 }
555                 $first = $start;
556                 $last = $end;
557         }
559         if ($first != -1) {
560                 if ($first == $last) {
561                         push @return, "$first";
562                 } else {
563                         push @return, "$first-$last";
564                 }
565         }
567         return join(',', @return);
570 sub merge_revs_into_hash {
571         my ($hash, $minfo) = @_;
572         my @lines = split(' ', $minfo);
574         for my $line (@lines) {
575                 my ($branchpath, $revs) = split(/:/, $line);
577                 if (exists($hash->{$branchpath})) {
578                         # Merge the two revision sets
579                         my $combined = "$hash->{$branchpath},$revs";
580                         $hash->{$branchpath} = combine_ranges($combined);
581                 } else {
582                         # Just do range combining for consolidation
583                         $hash->{$branchpath} = combine_ranges($revs);
584                 }
585         }
588 sub merge_merge_info {
589         my ($mergeinfo_one, $mergeinfo_two) = @_;
590         my %result_hash = ();
592         merge_revs_into_hash(\%result_hash, $mergeinfo_one);
593         merge_revs_into_hash(\%result_hash, $mergeinfo_two);
595         my $result = '';
596         # Sort below is for consistency's sake
597         for my $branchname (sort keys(%result_hash)) {
598                 my $revlist = $result_hash{$branchname};
599                 $result .= "$branchname:$revlist\n"
600         }
601         return $result;
604 sub populate_merge_info {
605         my ($d, $gs, $uuid, $linear_refs, $rewritten_parent) = @_;
607         my %parentshash;
608         read_commit_parents(\%parentshash, $d);
609         my @parents = @{$parentshash{$d}};
610         if ($#parents > 0) {
611                 # Merge commit
612                 my $all_parents_ok = 1;
613                 my $aggregate_mergeinfo = '';
614                 my $rooturl = $gs->repos_root;
616                 if (defined($rewritten_parent)) {
617                         # Replace first parent with newly-rewritten version
618                         shift @parents;
619                         unshift @parents, $rewritten_parent;
620                 }
622                 foreach my $parent (@parents) {
623                         my ($branchurl, $svnrev, $paruuid) =
624                                 cmt_metadata($parent);
626                         unless (defined($svnrev)) {
627                                 # Should have been caught be preflight check
628                                 fatal "merge commit $d has ancestor $parent, but that change "
629                      ."does not have git-svn metadata!";
630                         }
631                         unless ($branchurl =~ /^$rooturl(.*)/) {
632                                 fatal "commit $parent git-svn metadata changed mid-run!";
633                         }
634                         my $branchpath = $1;
636                         my $ra = Git::SVN::Ra->new($branchurl);
637                         my (undef, undef, $props) =
638                                 $ra->get_dir(canonicalize_path("."), $svnrev);
639                         my $par_mergeinfo = $props->{'svn:mergeinfo'};
640                         unless (defined $par_mergeinfo) {
641                                 $par_mergeinfo = '';
642                         }
643                         # Merge previous mergeinfo values
644                         $aggregate_mergeinfo =
645                                 merge_merge_info($aggregate_mergeinfo,
646                                                                  $par_mergeinfo, 0);
648                         next if $parent eq $parents[0]; # Skip first parent
649                         # Add new changes being placed in tree by merge
650                         my @cmd = (qw/rev-list --reverse/,
651                                            $parent, qw/--not/);
652                         foreach my $par (@parents) {
653                                 unless ($par eq $parent) {
654                                         push @cmd, $par;
655                                 }
656                         }
657                         my @revsin = ();
658                         my ($revlist, $ctx) = command_output_pipe(@cmd);
659                         while (<$revlist>) {
660                                 my $irev = $_;
661                                 chomp $irev;
662                                 my (undef, $csvnrev, undef) =
663                                         cmt_metadata($irev);
664                                 unless (defined $csvnrev) {
665                                         # A child is missing SVN annotations...
666                                         # this might be OK, or might not be.
667                                         warn "W:child $irev is merged into revision "
668                                                  ."$d but does not have git-svn metadata. "
669                                                  ."This means git-svn cannot determine the "
670                                                  ."svn revision numbers to place into the "
671                                                  ."svn:mergeinfo property. You must ensure "
672                                                  ."a branch is entirely committed to "
673                                                  ."SVN before merging it in order for "
674                                                  ."svn:mergeinfo population to function "
675                                                  ."properly";
676                                 }
677                                 push @revsin, $csvnrev;
678                         }
679                         command_close_pipe($revlist, $ctx);
681                         last unless $all_parents_ok;
683                         # We now have a list of all SVN revnos which are
684                         # merged by this particular parent. Integrate them.
685                         next if $#revsin == -1;
686                         my $newmergeinfo = "$branchpath:" . join(',', @revsin);
687                         $aggregate_mergeinfo =
688                                 merge_merge_info($aggregate_mergeinfo,
689                                                                  $newmergeinfo, 1);
690                 }
691                 if ($all_parents_ok and $aggregate_mergeinfo) {
692                         return $aggregate_mergeinfo;
693                 }
694         }
696         return undef;
699 sub cmd_dcommit {
700         my $head = shift;
701         command_noisy(qw/update-index --refresh/);
702         git_cmd_try { command_oneline(qw/diff-index --quiet HEAD/) }
703                 'Cannot dcommit with a dirty index.  Commit your changes first, '
704                 . "or stash them with `git stash'.\n";
705         $head ||= 'HEAD';
707         my $old_head;
708         if ($head ne 'HEAD') {
709                 $old_head = eval {
710                         command_oneline([qw/symbolic-ref -q HEAD/])
711                 };
712                 if ($old_head) {
713                         $old_head =~ s{^refs/heads/}{};
714                 } else {
715                         $old_head = eval { command_oneline(qw/rev-parse HEAD/) };
716                 }
717                 command(['checkout', $head], STDERR => 0);
718         }
720         my @refs;
721         my ($url, $rev, $uuid, $gs) = working_head_info('HEAD', \@refs);
722         unless ($gs) {
723                 die "Unable to determine upstream SVN information from ",
724                     "$head history.\nPerhaps the repository is empty.";
725         }
727         if (defined $_commit_url) {
728                 $url = $_commit_url;
729         } else {
730                 $url = eval { command_oneline('config', '--get',
731                               "svn-remote.$gs->{repo_id}.commiturl") };
732                 if (!$url) {
733                         $url = $gs->full_pushurl
734                 }
735         }
737         my $last_rev = $_revision if defined $_revision;
738         if ($url) {
739                 print "Committing to $url ...\n";
740         }
741         my ($linear_refs, $parents) = linearize_history($gs, \@refs);
742         if ($_no_rebase && scalar(@$linear_refs) > 1) {
743                 warn "Attempting to commit more than one change while ",
744                      "--no-rebase is enabled.\n",
745                      "If these changes depend on each other, re-running ",
746                      "without --no-rebase may be required."
747         }
748         my $expect_url = $url;
750         my $push_merge_info = eval {
751                 command_oneline(qw/config --get svn.pushmergeinfo/)
752                 };
753         if (not defined($push_merge_info)
754                         or $push_merge_info eq "false"
755                         or $push_merge_info eq "no"
756                         or $push_merge_info eq "never") {
757                 $push_merge_info = 0;
758         }
760         unless (defined($_merge_info) || ! $push_merge_info) {
761                 # Preflight check of changes to ensure no issues with mergeinfo
762                 # This includes check for uncommitted-to-SVN parents
763                 # (other than the first parent, which we will handle),
764                 # information from different SVN repos, and paths
765                 # which are not underneath this repository root.
766                 my $rooturl = $gs->repos_root;
767                 foreach my $d (@$linear_refs) {
768                         my %parentshash;
769                         read_commit_parents(\%parentshash, $d);
770                         my @realparents = @{$parentshash{$d}};
771                         if ($#realparents > 0) {
772                                 # Merge commit
773                                 shift @realparents; # Remove/ignore first parent
774                                 foreach my $parent (@realparents) {
775                                         my ($branchurl, $svnrev, $paruuid) = cmt_metadata($parent);
776                                         unless (defined $paruuid) {
777                                                 # A parent is missing SVN annotations...
778                                                 # abort the whole operation.
779                                                 fatal "$parent is merged into revision $d, "
780                                                          ."but does not have git-svn metadata. "
781                                                          ."Either dcommit the branch or use a "
782                                                          ."local cherry-pick, FF merge, or rebase "
783                                                          ."instead of an explicit merge commit.";
784                                         }
786                                         unless ($paruuid eq $uuid) {
787                                                 # Parent has SVN metadata from different repository
788                                                 fatal "merge parent $parent for change $d has "
789                                                          ."git-svn uuid $paruuid, while current change "
790                                                          ."has uuid $uuid!";
791                                         }
793                                         unless ($branchurl =~ /^$rooturl(.*)/) {
794                                                 # This branch is very strange indeed.
795                                                 fatal "merge parent $parent for $d is on branch "
796                                                          ."$branchurl, which is not under the "
797                                                          ."git-svn root $rooturl!";
798                                         }
799                                 }
800                         }
801                 }
802         }
804         my $rewritten_parent;
805         Git::SVN::remove_username($expect_url);
806         if (defined($_merge_info)) {
807                 $_merge_info =~ tr{ }{\n};
808         }
809         while (1) {
810                 my $d = shift @$linear_refs or last;
811                 unless (defined $last_rev) {
812                         (undef, $last_rev, undef) = cmt_metadata("$d~1");
813                         unless (defined $last_rev) {
814                                 fatal "Unable to extract revision information ",
815                                       "from commit $d~1";
816                         }
817                 }
818                 if ($_dry_run) {
819                         print "diff-tree $d~1 $d\n";
820                 } else {
821                         my $cmt_rev;
823                         unless (defined($_merge_info) || ! $push_merge_info) {
824                                 $_merge_info = populate_merge_info($d, $gs,
825                                                              $uuid,
826                                                              $linear_refs,
827                                                              $rewritten_parent);
828                         }
830                         my %ed_opts = ( r => $last_rev,
831                                         log => get_commit_entry($d)->{log},
832                                         ra => Git::SVN::Ra->new($url),
833                                         config => SVN::Core::config_get_config(
834                                                 $Git::SVN::Ra::config_dir
835                                         ),
836                                         tree_a => "$d~1",
837                                         tree_b => $d,
838                                         editor_cb => sub {
839                                                print "Committed r$_[0]\n";
840                                                $cmt_rev = $_[0];
841                                         },
842                                         mergeinfo => $_merge_info,
843                                         svn_path => '');
844                         if (!SVN::Git::Editor->new(\%ed_opts)->apply_diff) {
845                                 print "No changes\n$d~1 == $d\n";
846                         } elsif ($parents->{$d} && @{$parents->{$d}}) {
847                                 $gs->{inject_parents_dcommit}->{$cmt_rev} =
848                                                                $parents->{$d};
849                         }
850                         $_fetch_all ? $gs->fetch_all : $gs->fetch;
851                         $last_rev = $cmt_rev;
852                         next if $_no_rebase;
854                         # we always want to rebase against the current HEAD,
855                         # not any head that was passed to us
856                         my @diff = command('diff-tree', $d,
857                                            $gs->refname, '--');
858                         my @finish;
859                         if (@diff) {
860                                 @finish = rebase_cmd();
861                                 print STDERR "W: $d and ", $gs->refname,
862                                              " differ, using @finish:\n",
863                                              join("\n", @diff), "\n";
864                         } else {
865                                 print "No changes between current HEAD and ",
866                                       $gs->refname,
867                                       "\nResetting to the latest ",
868                                       $gs->refname, "\n";
869                                 @finish = qw/reset --mixed/;
870                         }
871                         command_noisy(@finish, $gs->refname);
873                         $rewritten_parent = command_oneline(qw/rev-parse HEAD/);
875                         if (@diff) {
876                                 @refs = ();
877                                 my ($url_, $rev_, $uuid_, $gs_) =
878                                               working_head_info('HEAD', \@refs);
879                                 my ($linear_refs_, $parents_) =
880                                               linearize_history($gs_, \@refs);
881                                 if (scalar(@$linear_refs) !=
882                                     scalar(@$linear_refs_)) {
883                                         fatal "# of revisions changed ",
884                                           "\nbefore:\n",
885                                           join("\n", @$linear_refs),
886                                           "\n\nafter:\n",
887                                           join("\n", @$linear_refs_), "\n",
888                                           'If you are attempting to commit ',
889                                           "merges, try running:\n\t",
890                                           'git rebase --interactive',
891                                           '--preserve-merges ',
892                                           $gs->refname,
893                                           "\nBefore dcommitting";
894                                 }
895                                 if ($url_ ne $expect_url) {
896                                         if ($url_ eq $gs->metadata_url) {
897                                                 print
898                                                   "Accepting rewritten URL:",
899                                                   " $url_\n";
900                                         } else {
901                                                 fatal
902                                                   "URL mismatch after rebase:",
903                                                   " $url_ != $expect_url";
904                                         }
905                                 }
906                                 if ($uuid_ ne $uuid) {
907                                         fatal "uuid mismatch after rebase: ",
908                                               "$uuid_ != $uuid";
909                                 }
910                                 # remap parents
911                                 my (%p, @l, $i);
912                                 for ($i = 0; $i < scalar @$linear_refs; $i++) {
913                                         my $new = $linear_refs_->[$i] or next;
914                                         $p{$new} =
915                                                 $parents->{$linear_refs->[$i]};
916                                         push @l, $new;
917                                 }
918                                 $parents = \%p;
919                                 $linear_refs = \@l;
920                         }
921                 }
922         }
924         if ($old_head) {
925                 my $new_head = command_oneline(qw/rev-parse HEAD/);
926                 my $new_is_symbolic = eval {
927                         command_oneline(qw/symbolic-ref -q HEAD/);
928                 };
929                 if ($new_is_symbolic) {
930                         print "dcommitted the branch ", $head, "\n";
931                 } else {
932                         print "dcommitted on a detached HEAD because you gave ",
933                               "a revision argument.\n",
934                               "The rewritten commit is: ", $new_head, "\n";
935                 }
936                 command(['checkout', $old_head], STDERR => 0);
937         }
939         unlink $gs->{index};
942 sub cmd_branch {
943         my ($branch_name, $head) = @_;
945         unless (defined $branch_name && length $branch_name) {
946                 die(($_tag ? "tag" : "branch") . " name required\n");
947         }
948         $head ||= 'HEAD';
950         my (undef, $rev, undef, $gs) = working_head_info($head);
951         my $src = $gs->full_pushurl;
953         my $remote = Git::SVN::read_all_remotes()->{$gs->{repo_id}};
954         my $allglobs = $remote->{ $_tag ? 'tags' : 'branches' };
955         my $glob;
956         if ($#{$allglobs} == 0) {
957                 $glob = $allglobs->[0];
958         } else {
959                 unless(defined $_branch_dest) {
960                         die "Multiple ",
961                             $_tag ? "tag" : "branch",
962                             " paths defined for Subversion repository.\n",
963                             "You must specify where you want to create the ",
964                             $_tag ? "tag" : "branch",
965                             " with the --destination argument.\n";
966                 }
967                 foreach my $g (@{$allglobs}) {
968                         # SVN::Git::Editor could probably be moved to Git.pm..
969                         my $re = SVN::Git::Editor::glob2pat($g->{path}->{left});
970                         if ($_branch_dest =~ /$re/) {
971                                 $glob = $g;
972                                 last;
973                         }
974                 }
975                 unless (defined $glob) {
976                         my $dest_re = qr/\b\Q$_branch_dest\E\b/;
977                         foreach my $g (@{$allglobs}) {
978                                 $g->{path}->{left} =~ /$dest_re/ or next;
979                                 if (defined $glob) {
980                                         die "Ambiguous destination: ",
981                                             $_branch_dest, "\nmatches both '",
982                                             $glob->{path}->{left}, "' and '",
983                                             $g->{path}->{left}, "'\n";
984                                 }
985                                 $glob = $g;
986                         }
987                         unless (defined $glob) {
988                                 die "Unknown ",
989                                     $_tag ? "tag" : "branch",
990                                     " destination $_branch_dest\n";
991                         }
992                 }
993         }
994         my ($lft, $rgt) = @{ $glob->{path} }{qw/left right/};
995         my $url;
996         if (defined $_commit_url) {
997                 $url = $_commit_url;
998         } else {
999                 $url = eval { command_oneline('config', '--get',
1000                         "svn-remote.$gs->{repo_id}.commiturl") };
1001                 if (!$url) {
1002                         $url = $remote->{pushurl} || $remote->{url};
1003                 }
1004         }
1005         my $dst = join '/', $url, $lft, $branch_name, ($rgt || ());
1007         if ($dst =~ /^https:/ && $src =~ /^http:/) {
1008                 $src=~s/^http:/https:/;
1009         }
1011         ::_req_svn();
1013         my $ctx = SVN::Client->new(
1014                 auth    => Git::SVN::Ra::_auth_providers(),
1015                 log_msg => sub {
1016                         ${ $_[0] } = defined $_message
1017                                 ? $_message
1018                                 : 'Create ' . ($_tag ? 'tag ' : 'branch ' )
1019                                 . $branch_name;
1020                 },
1021         );
1023         eval {
1024                 $ctx->ls($dst, 'HEAD', 0);
1025         } and die "branch ${branch_name} already exists\n";
1027         print "Copying ${src} at r${rev} to ${dst}...\n";
1028         $ctx->copy($src, $rev, $dst)
1029                 unless $_dry_run;
1031         $gs->fetch_all;
1034 sub cmd_find_rev {
1035         my $revision_or_hash = shift or die "SVN or git revision required ",
1036                                             "as a command-line argument\n";
1037         my $result;
1038         if ($revision_or_hash =~ /^r\d+$/) {
1039                 my $head = shift;
1040                 $head ||= 'HEAD';
1041                 my @refs;
1042                 my (undef, undef, $uuid, $gs) = working_head_info($head, \@refs);
1043                 unless ($gs) {
1044                         die "Unable to determine upstream SVN information from ",
1045                             "$head history\n";
1046                 }
1047                 my $desired_revision = substr($revision_or_hash, 1);
1048                 $result = $gs->rev_map_get($desired_revision, $uuid);
1049         } else {
1050                 my (undef, $rev, undef) = cmt_metadata($revision_or_hash);
1051                 $result = $rev;
1052         }
1053         print "$result\n" if $result;
1056 sub auto_create_empty_directories {
1057         my ($gs) = @_;
1058         my $var = eval { command_oneline('config', '--get', '--bool',
1059                                          "svn-remote.$gs->{repo_id}.automkdirs") };
1060         # By default, create empty directories by consulting the unhandled log,
1061         # but allow setting it to 'false' to skip it.
1062         return !($var && $var eq 'false');
1065 sub cmd_rebase {
1066         command_noisy(qw/update-index --refresh/);
1067         my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
1068         unless ($gs) {
1069                 die "Unable to determine upstream SVN information from ",
1070                     "working tree history\n";
1071         }
1072         if ($_dry_run) {
1073                 print "Remote Branch: " . $gs->refname . "\n";
1074                 print "SVN URL: " . $url . "\n";
1075                 return;
1076         }
1077         if (command(qw/diff-index HEAD --/)) {
1078                 print STDERR "Cannot rebase with uncommited changes:\n";
1079                 command_noisy('status');
1080                 exit 1;
1081         }
1082         unless ($_local) {
1083                 # rebase will checkout for us, so no need to do it explicitly
1084                 $_no_checkout = 'true';
1085                 $_fetch_all ? $gs->fetch_all : $gs->fetch;
1086         }
1087         command_noisy(rebase_cmd(), $gs->refname);
1088         if (auto_create_empty_directories($gs)) {
1089                 $gs->mkemptydirs;
1090         }
1093 sub cmd_show_ignore {
1094         my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
1095         $gs ||= Git::SVN->new;
1096         my $r = (defined $_revision ? $_revision : $gs->ra->get_latest_revnum);
1097         $gs->prop_walk($gs->{path}, $r, sub {
1098                 my ($gs, $path, $props) = @_;
1099                 print STDOUT "\n# $path\n";
1100                 my $s = $props->{'svn:ignore'} or return;
1101                 $s =~ s/[\r\n]+/\n/g;
1102                 $s =~ s/^\n+//;
1103                 chomp $s;
1104                 $s =~ s#^#$path#gm;
1105                 print STDOUT "$s\n";
1106         });
1109 sub cmd_show_externals {
1110         my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
1111         $gs ||= Git::SVN->new;
1112         my $r = (defined $_revision ? $_revision : $gs->ra->get_latest_revnum);
1113         $gs->prop_walk($gs->{path}, $r, sub {
1114                 my ($gs, $path, $props) = @_;
1115                 print STDOUT "\n# $path\n";
1116                 my $s = $props->{'svn:externals'} or return;
1117                 $s =~ s/[\r\n]+/\n/g;
1118                 chomp $s;
1119                 $s =~ s#^#$path#gm;
1120                 print STDOUT "$s\n";
1121         });
1124 sub cmd_create_ignore {
1125         my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
1126         $gs ||= Git::SVN->new;
1127         my $r = (defined $_revision ? $_revision : $gs->ra->get_latest_revnum);
1128         $gs->prop_walk($gs->{path}, $r, sub {
1129                 my ($gs, $path, $props) = @_;
1130                 # $path is of the form /path/to/dir/
1131                 $path = '.' . $path;
1132                 # SVN can have attributes on empty directories,
1133                 # which git won't track
1134                 mkpath([$path]) unless -d $path;
1135                 my $ignore = $path . '.gitignore';
1136                 my $s = $props->{'svn:ignore'} or return;
1137                 open(GITIGNORE, '>', $ignore)
1138                   or fatal("Failed to open `$ignore' for writing: $!");
1139                 $s =~ s/[\r\n]+/\n/g;
1140                 $s =~ s/^\n+//;
1141                 chomp $s;
1142                 # Prefix all patterns so that the ignore doesn't apply
1143                 # to sub-directories.
1144                 $s =~ s#^#/#gm;
1145                 print GITIGNORE "$s\n";
1146                 close(GITIGNORE)
1147                   or fatal("Failed to close `$ignore': $!");
1148                 command_noisy('add', '-f', $ignore);
1149         });
1152 sub cmd_mkdirs {
1153         my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
1154         $gs ||= Git::SVN->new;
1155         $gs->mkemptydirs($_revision);
1158 sub canonicalize_path {
1159         my ($path) = @_;
1160         my $dot_slash_added = 0;
1161         if (substr($path, 0, 1) ne "/") {
1162                 $path = "./" . $path;
1163                 $dot_slash_added = 1;
1164         }
1165         # File::Spec->canonpath doesn't collapse x/../y into y (for a
1166         # good reason), so let's do this manually.
1167         $path =~ s#/+#/#g;
1168         $path =~ s#/\.(?:/|$)#/#g;
1169         $path =~ s#/[^/]+/\.\.##g;
1170         $path =~ s#/$##g;
1171         $path =~ s#^\./## if $dot_slash_added;
1172         $path =~ s#^/##;
1173         $path =~ s#^\.$##;
1174         return $path;
1177 sub canonicalize_url {
1178         my ($url) = @_;
1179         $url =~ s#^([^:]+://[^/]*/)(.*)$#$1 . canonicalize_path($2)#e;
1180         return $url;
1183 # get_svnprops(PATH)
1184 # ------------------
1185 # Helper for cmd_propget and cmd_proplist below.
1186 sub get_svnprops {
1187         my $path = shift;
1188         my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
1189         $gs ||= Git::SVN->new;
1191         # prefix THE PATH by the sub-directory from which the user
1192         # invoked us.
1193         $path = $cmd_dir_prefix . $path;
1194         fatal("No such file or directory: $path") unless -e $path;
1195         my $is_dir = -d $path ? 1 : 0;
1196         $path = $gs->{path} . '/' . $path;
1198         # canonicalize the path (otherwise libsvn will abort or fail to
1199         # find the file)
1200         $path = canonicalize_path($path);
1202         my $r = (defined $_revision ? $_revision : $gs->ra->get_latest_revnum);
1203         my $props;
1204         if ($is_dir) {
1205                 (undef, undef, $props) = $gs->ra->get_dir($path, $r);
1206         }
1207         else {
1208                 (undef, $props) = $gs->ra->get_file($path, $r, undef);
1209         }
1210         return $props;
1213 # cmd_propget (PROP, PATH)
1214 # ------------------------
1215 # Print the SVN property PROP for PATH.
1216 sub cmd_propget {
1217         my ($prop, $path) = @_;
1218         $path = '.' if not defined $path;
1219         usage(1) if not defined $prop;
1220         my $props = get_svnprops($path);
1221         if (not defined $props->{$prop}) {
1222                 fatal("`$path' does not have a `$prop' SVN property.");
1223         }
1224         print $props->{$prop} . "\n";
1227 # cmd_proplist (PATH)
1228 # -------------------
1229 # Print the list of SVN properties for PATH.
1230 sub cmd_proplist {
1231         my $path = shift;
1232         $path = '.' if not defined $path;
1233         my $props = get_svnprops($path);
1234         print "Properties on '$path':\n";
1235         foreach (sort keys %{$props}) {
1236                 print "  $_\n";
1237         }
1240 sub cmd_multi_init {
1241         my $url = shift;
1242         unless (defined $_trunk || @_branches || @_tags) {
1243                 usage(1);
1244         }
1246         $_prefix = '' unless defined $_prefix;
1247         if (defined $url) {
1248                 $url = canonicalize_url($url);
1249                 init_subdir(@_);
1250         }
1251         do_git_init_db();
1252         if (defined $_trunk) {
1253                 $_trunk =~ s#^/+##;
1254                 my $trunk_ref = 'refs/remotes/' . $_prefix . 'trunk';
1255                 # try both old-style and new-style lookups:
1256                 my $gs_trunk = eval { Git::SVN->new($trunk_ref) };
1257                 unless ($gs_trunk) {
1258                         my ($trunk_url, $trunk_path) =
1259                                               complete_svn_url($url, $_trunk);
1260                         $gs_trunk = Git::SVN->init($trunk_url, $trunk_path,
1261                                                    undef, $trunk_ref);
1262                 }
1263         }
1264         return unless @_branches || @_tags;
1265         my $ra = $url ? Git::SVN::Ra->new($url) : undef;
1266         foreach my $path (@_branches) {
1267                 complete_url_ls_init($ra, $path, '--branches/-b', $_prefix);
1268         }
1269         foreach my $path (@_tags) {
1270                 complete_url_ls_init($ra, $path, '--tags/-t', $_prefix.'tags/');
1271         }
1274 sub cmd_multi_fetch {
1275         $Git::SVN::no_reuse_existing = undef;
1276         my $remotes = Git::SVN::read_all_remotes();
1277         foreach my $repo_id (sort keys %$remotes) {
1278                 if ($remotes->{$repo_id}->{url}) {
1279                         Git::SVN::fetch_all($repo_id, $remotes);
1280                 }
1281         }
1284 # this command is special because it requires no metadata
1285 sub cmd_commit_diff {
1286         my ($ta, $tb, $url) = @_;
1287         my $usage = "Usage: $0 commit-diff -r<revision> ".
1288                     "<tree-ish> <tree-ish> [<URL>]";
1289         fatal($usage) if (!defined $ta || !defined $tb);
1290         my $svn_path = '';
1291         if (!defined $url) {
1292                 my $gs = eval { Git::SVN->new };
1293                 if (!$gs) {
1294                         fatal("Needed URL or usable git-svn --id in ",
1295                               "the command-line\n", $usage);
1296                 }
1297                 $url = $gs->{url};
1298                 $svn_path = $gs->{path};
1299         }
1300         unless (defined $_revision) {
1301                 fatal("-r|--revision is a required argument\n", $usage);
1302         }
1303         if (defined $_message && defined $_file) {
1304                 fatal("Both --message/-m and --file/-F specified ",
1305                       "for the commit message.\n",
1306                       "I have no idea what you mean");
1307         }
1308         if (defined $_file) {
1309                 $_message = file_to_s($_file);
1310         } else {
1311                 $_message ||= get_commit_entry($tb)->{log};
1312         }
1313         my $ra ||= Git::SVN::Ra->new($url);
1314         my $r = $_revision;
1315         if ($r eq 'HEAD') {
1316                 $r = $ra->get_latest_revnum;
1317         } elsif ($r !~ /^\d+$/) {
1318                 die "revision argument: $r not understood by git-svn\n";
1319         }
1320         my %ed_opts = ( r => $r,
1321                         log => $_message,
1322                         ra => $ra,
1323                         tree_a => $ta,
1324                         tree_b => $tb,
1325                         editor_cb => sub { print "Committed r$_[0]\n" },
1326                         svn_path => $svn_path );
1327         if (!SVN::Git::Editor->new(\%ed_opts)->apply_diff) {
1328                 print "No changes\n$ta == $tb\n";
1329         }
1332 sub escape_uri_only {
1333         my ($uri) = @_;
1334         my @tmp;
1335         foreach (split m{/}, $uri) {
1336                 s/([^~\w.%+-]|%(?![a-fA-F0-9]{2}))/sprintf("%%%02X",ord($1))/eg;
1337                 push @tmp, $_;
1338         }
1339         join('/', @tmp);
1342 sub escape_url {
1343         my ($url) = @_;
1344         if ($url =~ m#^([^:]+)://([^/]*)(.*)$#) {
1345                 my ($scheme, $domain, $uri) = ($1, $2, escape_uri_only($3));
1346                 $url = "$scheme://$domain$uri";
1347         }
1348         $url;
1351 sub cmd_info {
1352         my $path = canonicalize_path(defined($_[0]) ? $_[0] : ".");
1353         my $fullpath = canonicalize_path($cmd_dir_prefix . $path);
1354         if (exists $_[1]) {
1355                 die "Too many arguments specified\n";
1356         }
1358         my ($file_type, $diff_status) = find_file_type_and_diff_status($path);
1360         if (!$file_type && !$diff_status) {
1361                 print STDERR "svn: '$path' is not under version control\n";
1362                 exit 1;
1363         }
1365         my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
1366         unless ($gs) {
1367                 die "Unable to determine upstream SVN information from ",
1368                     "working tree history\n";
1369         }
1371         # canonicalize_path() will return "" to make libsvn 1.5.x happy,
1372         $path = "." if $path eq "";
1374         my $full_url = $url . ($fullpath eq "" ? "" : "/$fullpath");
1376         if ($_url) {
1377                 print escape_url($full_url), "\n";
1378                 return;
1379         }
1381         my $result = "Path: $path\n";
1382         $result .= "Name: " . basename($path) . "\n" if $file_type ne "dir";
1383         $result .= "URL: " . escape_url($full_url) . "\n";
1385         eval {
1386                 my $repos_root = $gs->repos_root;
1387                 Git::SVN::remove_username($repos_root);
1388                 $result .= "Repository Root: " . escape_url($repos_root) . "\n";
1389         };
1390         if ($@) {
1391                 $result .= "Repository Root: (offline)\n";
1392         }
1393         ::_req_svn();
1394         $result .= "Repository UUID: $uuid\n" unless $diff_status eq "A" &&
1395                 ($SVN::Core::VERSION le '1.5.4' || $file_type ne "dir");
1396         $result .= "Revision: " . ($diff_status eq "A" ? 0 : $rev) . "\n";
1398         $result .= "Node Kind: " .
1399                    ($file_type eq "dir" ? "directory" : "file") . "\n";
1401         my $schedule = $diff_status eq "A"
1402                        ? "add"
1403                        : ($diff_status eq "D" ? "delete" : "normal");
1404         $result .= "Schedule: $schedule\n";
1406         if ($diff_status eq "A") {
1407                 print $result, "\n";
1408                 return;
1409         }
1411         my ($lc_author, $lc_rev, $lc_date_utc);
1412         my @args = Git::SVN::Log::git_svn_log_cmd($rev, $rev, "--", $fullpath);
1413         my $log = command_output_pipe(@args);
1414         my $esc_color = qr/(?:\033\[(?:(?:\d+;)*\d*)?m)*/;
1415         while (<$log>) {
1416                 if (/^${esc_color}author (.+) <[^>]+> (\d+) ([\-\+]?\d+)$/o) {
1417                         $lc_author = $1;
1418                         $lc_date_utc = Git::SVN::Log::parse_git_date($2, $3);
1419                 } elsif (/^${esc_color}    (git-svn-id:.+)$/o) {
1420                         (undef, $lc_rev, undef) = ::extract_metadata($1);
1421                 }
1422         }
1423         close $log;
1425         Git::SVN::Log::set_local_timezone();
1427         $result .= "Last Changed Author: $lc_author\n";
1428         $result .= "Last Changed Rev: $lc_rev\n";
1429         $result .= "Last Changed Date: " .
1430                    Git::SVN::Log::format_svn_date($lc_date_utc) . "\n";
1432         if ($file_type ne "dir") {
1433                 my $text_last_updated_date =
1434                     ($diff_status eq "D" ? $lc_date_utc : (stat $path)[9]);
1435                 $result .=
1436                     "Text Last Updated: " .
1437                     Git::SVN::Log::format_svn_date($text_last_updated_date) .
1438                     "\n";
1439                 my $checksum;
1440                 if ($diff_status eq "D") {
1441                         my ($fh, $ctx) =
1442                             command_output_pipe(qw(cat-file blob), "HEAD:$path");
1443                         if ($file_type eq "link") {
1444                                 my $file_name = <$fh>;
1445                                 $checksum = md5sum("link $file_name");
1446                         } else {
1447                                 $checksum = md5sum($fh);
1448                         }
1449                         command_close_pipe($fh, $ctx);
1450                 } elsif ($file_type eq "link") {
1451                         my $file_name =
1452                             command(qw(cat-file blob), "HEAD:$path");
1453                         $checksum =
1454                             md5sum("link " . $file_name);
1455                 } else {
1456                         open FILE, "<", $path or die $!;
1457                         $checksum = md5sum(\*FILE);
1458                         close FILE or die $!;
1459                 }
1460                 $result .= "Checksum: " . $checksum . "\n";
1461         }
1463         print $result, "\n";
1466 sub cmd_reset {
1467         my $target = shift || $_revision or die "SVN revision required\n";
1468         $target = $1 if $target =~ /^r(\d+)$/;
1469         $target =~ /^\d+$/ or die "Numeric SVN revision expected\n";
1470         my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
1471         unless ($gs) {
1472                 die "Unable to determine upstream SVN information from ".
1473                     "history\n";
1474         }
1475         my ($r, $c) = $gs->find_rev_before($target, not $_fetch_parent);
1476         die "Cannot find SVN revision $target\n" unless defined($c);
1477         $gs->rev_map_set($r, $c, 'reset', $uuid);
1478         print "r$r = $c ($gs->{ref_id})\n";
1481 sub cmd_gc {
1482         if (!$can_compress) {
1483                 warn "Compress::Zlib could not be found; unhandled.log " .
1484                      "files will not be compressed.\n";
1485         }
1486         find({ wanted => \&gc_directory, no_chdir => 1}, "$ENV{GIT_DIR}/svn");
1489 ########################### utility functions #########################
1491 sub rebase_cmd {
1492         my @cmd = qw/rebase/;
1493         push @cmd, '-v' if $_verbose;
1494         push @cmd, qw/--merge/ if $_merge;
1495         push @cmd, "--strategy=$_strategy" if $_strategy;
1496         @cmd;
1499 sub post_fetch_checkout {
1500         return if $_no_checkout;
1501         my $gs = $Git::SVN::_head or return;
1502         return if verify_ref('refs/heads/master^0');
1504         # look for "trunk" ref if it exists
1505         my $remote = Git::SVN::read_all_remotes()->{$gs->{repo_id}};
1506         my $fetch = $remote->{fetch};
1507         if ($fetch) {
1508                 foreach my $p (keys %$fetch) {
1509                         basename($fetch->{$p}) eq 'trunk' or next;
1510                         $gs = Git::SVN->new($fetch->{$p}, $gs->{repo_id}, $p);
1511                         last;
1512                 }
1513         }
1515         my $valid_head = verify_ref('HEAD^0');
1516         command_noisy(qw(update-ref refs/heads/master), $gs->refname);
1517         return if ($valid_head || !verify_ref('HEAD^0'));
1519         return if $ENV{GIT_DIR} !~ m#^(?:.*/)?\.git$#;
1520         my $index = $ENV{GIT_INDEX_FILE} || "$ENV{GIT_DIR}/index";
1521         return if -f $index;
1523         return if command_oneline(qw/rev-parse --is-inside-work-tree/) eq 'false';
1524         return if command_oneline(qw/rev-parse --is-inside-git-dir/) eq 'true';
1525         command_noisy(qw/read-tree -m -u -v HEAD HEAD/);
1526         print STDERR "Checked out HEAD:\n  ",
1527                      $gs->full_url, " r", $gs->last_rev, "\n";
1528         if (auto_create_empty_directories($gs)) {
1529                 $gs->mkemptydirs($gs->last_rev);
1530         }
1533 sub complete_svn_url {
1534         my ($url, $path) = @_;
1535         $path =~ s#/+$##;
1536         if ($path !~ m#^[a-z\+]+://#) {
1537                 if (!defined $url || $url !~ m#^[a-z\+]+://#) {
1538                         fatal("E: '$path' is not a complete URL ",
1539                               "and a separate URL is not specified");
1540                 }
1541                 return ($url, $path);
1542         }
1543         return ($path, '');
1546 sub complete_url_ls_init {
1547         my ($ra, $repo_path, $switch, $pfx) = @_;
1548         unless ($repo_path) {
1549                 print STDERR "W: $switch not specified\n";
1550                 return;
1551         }
1552         $repo_path =~ s#/+$##;
1553         if ($repo_path =~ m#^[a-z\+]+://#) {
1554                 $ra = Git::SVN::Ra->new($repo_path);
1555                 $repo_path = '';
1556         } else {
1557                 $repo_path =~ s#^/+##;
1558                 unless ($ra) {
1559                         fatal("E: '$repo_path' is not a complete URL ",
1560                               "and a separate URL is not specified");
1561                 }
1562         }
1563         my $url = $ra->{url};
1564         my $gs = Git::SVN->init($url, undef, undef, undef, 1);
1565         my $k = "svn-remote.$gs->{repo_id}.url";
1566         my $orig_url = eval { command_oneline(qw/config --get/, $k) };
1567         if ($orig_url && ($orig_url ne $gs->{url})) {
1568                 die "$k already set: $orig_url\n",
1569                     "wanted to set to: $gs->{url}\n";
1570         }
1571         command_oneline('config', $k, $gs->{url}) unless $orig_url;
1572         my $remote_path = "$gs->{path}/$repo_path";
1573         $remote_path =~ s{%([0-9A-F]{2})}{chr hex($1)}ieg;
1574         $remote_path =~ s#/+#/#g;
1575         $remote_path =~ s#^/##g;
1576         $remote_path .= "/*" if $remote_path !~ /\*/;
1577         my ($n) = ($switch =~ /^--(\w+)/);
1578         if (length $pfx && $pfx !~ m#/$#) {
1579                 die "--prefix='$pfx' must have a trailing slash '/'\n";
1580         }
1581         command_noisy('config',
1582                       '--add',
1583                       "svn-remote.$gs->{repo_id}.$n",
1584                       "$remote_path:refs/remotes/$pfx*" .
1585                         ('/*' x (($remote_path =~ tr/*/*/) - 1)) );
1588 sub verify_ref {
1589         my ($ref) = @_;
1590         eval { command_oneline([ 'rev-parse', '--verify', $ref ],
1591                                { STDERR => 0 }); };
1594 sub get_tree_from_treeish {
1595         my ($treeish) = @_;
1596         # $treeish can be a symbolic ref, too:
1597         my $type = command_oneline(qw/cat-file -t/, $treeish);
1598         my $expected;
1599         while ($type eq 'tag') {
1600                 ($treeish, $type) = command(qw/cat-file tag/, $treeish);
1601         }
1602         if ($type eq 'commit') {
1603                 $expected = (grep /^tree /, command(qw/cat-file commit/,
1604                                                     $treeish))[0];
1605                 ($expected) = ($expected =~ /^tree ($sha1)$/o);
1606                 die "Unable to get tree from $treeish\n" unless $expected;
1607         } elsif ($type eq 'tree') {
1608                 $expected = $treeish;
1609         } else {
1610                 die "$treeish is a $type, expected tree, tag or commit\n";
1611         }
1612         return $expected;
1615 sub get_commit_entry {
1616         my ($treeish) = shift;
1617         my %log_entry = ( log => '', tree => get_tree_from_treeish($treeish) );
1618         my $commit_editmsg = "$ENV{GIT_DIR}/COMMIT_EDITMSG";
1619         my $commit_msg = "$ENV{GIT_DIR}/COMMIT_MSG";
1620         open my $log_fh, '>', $commit_editmsg or croak $!;
1622         my $type = command_oneline(qw/cat-file -t/, $treeish);
1623         if ($type eq 'commit' || $type eq 'tag') {
1624                 my ($msg_fh, $ctx) = command_output_pipe('cat-file',
1625                                                          $type, $treeish);
1626                 my $in_msg = 0;
1627                 my $author;
1628                 my $saw_from = 0;
1629                 my $msgbuf = "";
1630                 while (<$msg_fh>) {
1631                         if (!$in_msg) {
1632                                 $in_msg = 1 if (/^\s*$/);
1633                                 $author = $1 if (/^author (.*>)/);
1634                         } elsif (/^git-svn-id: /) {
1635                                 # skip this for now, we regenerate the
1636                                 # correct one on re-fetch anyways
1637                                 # TODO: set *:merge properties or like...
1638                         } else {
1639                                 if (/^From:/ || /^Signed-off-by:/) {
1640                                         $saw_from = 1;
1641                                 }
1642                                 $msgbuf .= $_;
1643                         }
1644                 }
1645                 $msgbuf =~ s/\s+$//s;
1646                 if ($Git::SVN::_add_author_from && defined($author)
1647                     && !$saw_from) {
1648                         $msgbuf .= "\n\nFrom: $author";
1649                 }
1650                 print $log_fh $msgbuf or croak $!;
1651                 command_close_pipe($msg_fh, $ctx);
1652         }
1653         close $log_fh or croak $!;
1655         if ($_edit || ($type eq 'tree')) {
1656                 chomp(my $editor = command_oneline(qw(var GIT_EDITOR)));
1657                 system('sh', '-c', $editor.' "$@"', $editor, $commit_editmsg);
1658         }
1659         rename $commit_editmsg, $commit_msg or croak $!;
1660         {
1661                 require Encode;
1662                 # SVN requires messages to be UTF-8 when entering the repo
1663                 local $/;
1664                 open $log_fh, '<', $commit_msg or croak $!;
1665                 binmode $log_fh;
1666                 chomp($log_entry{log} = <$log_fh>);
1668                 my $enc = Git::config('i18n.commitencoding') || 'UTF-8';
1669                 my $msg = $log_entry{log};
1671                 eval { $msg = Encode::decode($enc, $msg, 1) };
1672                 if ($@) {
1673                         die "Could not decode as $enc:\n", $msg,
1674                             "\nPerhaps you need to set i18n.commitencoding\n";
1675                 }
1677                 eval { $msg = Encode::encode('UTF-8', $msg, 1) };
1678                 die "Could not encode as UTF-8:\n$msg\n" if $@;
1680                 $log_entry{log} = $msg;
1682                 close $log_fh or croak $!;
1683         }
1684         unlink $commit_msg;
1685         \%log_entry;
1688 sub s_to_file {
1689         my ($str, $file, $mode) = @_;
1690         open my $fd,'>',$file or croak $!;
1691         print $fd $str,"\n" or croak $!;
1692         close $fd or croak $!;
1693         chmod ($mode &~ umask, $file) if (defined $mode);
1696 sub file_to_s {
1697         my $file = shift;
1698         open my $fd,'<',$file or croak "$!: file: $file\n";
1699         local $/;
1700         my $ret = <$fd>;
1701         close $fd or croak $!;
1702         $ret =~ s/\s*$//s;
1703         return $ret;
1706 # '<svn username> = real-name <email address>' mapping based on git-svnimport:
1707 sub load_authors {
1708         open my $authors, '<', $_authors or die "Can't open $_authors $!\n";
1709         my $log = $cmd eq 'log';
1710         while (<$authors>) {
1711                 chomp;
1712                 next unless /^(.+?|\(no author\))\s*=\s*(.+?)\s*<(.+)>\s*$/;
1713                 my ($user, $name, $email) = ($1, $2, $3);
1714                 if ($log) {
1715                         $Git::SVN::Log::rusers{"$name <$email>"} = $user;
1716                 } else {
1717                         $users{$user} = [$name, $email];
1718                 }
1719         }
1720         close $authors or croak $!;
1723 # convert GetOpt::Long specs for use by git-config
1724 sub read_git_config {
1725         my $opts = shift;
1726         my @config_only;
1727         foreach my $o (keys %$opts) {
1728                 # if we have mixedCase and a long option-only, then
1729                 # it's a config-only variable that we don't need for
1730                 # the command-line.
1731                 push @config_only, $o if ($o =~ /[A-Z]/ && $o =~ /^[a-z]+$/i);
1732                 my $v = $opts->{$o};
1733                 my ($key) = ($o =~ /^([a-zA-Z\-]+)/);
1734                 $key =~ s/-//g;
1735                 my $arg = 'git config';
1736                 $arg .= ' --int' if ($o =~ /[:=]i$/);
1737                 $arg .= ' --bool' if ($o !~ /[:=][sfi]$/);
1738                 if (ref $v eq 'ARRAY') {
1739                         chomp(my @tmp = `$arg --get-all svn.$key`);
1740                         @$v = @tmp if @tmp;
1741                 } else {
1742                         chomp(my $tmp = `$arg --get svn.$key`);
1743                         if ($tmp && !($arg =~ / --bool/ && $tmp eq 'false')) {
1744                                 $$v = $tmp;
1745                         }
1746                 }
1747         }
1748         delete @$opts{@config_only} if @config_only;
1751 sub extract_metadata {
1752         my $id = shift or return (undef, undef, undef);
1753         my ($url, $rev, $uuid) = ($id =~ /^\s*git-svn-id:\s+(.*)\@(\d+)
1754                                                         \s([a-f\d\-]+)$/ix);
1755         if (!defined $rev || !$uuid || !$url) {
1756                 # some of the original repositories I made had
1757                 # identifiers like this:
1758                 ($rev, $uuid) = ($id =~/^\s*git-svn-id:\s(\d+)\@([a-f\d\-]+)/i);
1759         }
1760         return ($url, $rev, $uuid);
1763 sub cmt_metadata {
1764         return extract_metadata((grep(/^git-svn-id: /,
1765                 command(qw/cat-file commit/, shift)))[-1]);
1768 sub cmt_sha2rev_batch {
1769         my %s2r;
1770         my ($pid, $in, $out, $ctx) = command_bidi_pipe(qw/cat-file --batch/);
1771         my $list = shift;
1773         foreach my $sha (@{$list}) {
1774                 my $first = 1;
1775                 my $size = 0;
1776                 print $out $sha, "\n";
1778                 while (my $line = <$in>) {
1779                         if ($first && $line =~ /^[[:xdigit:]]{40}\smissing$/) {
1780                                 last;
1781                         } elsif ($first &&
1782                                $line =~ /^[[:xdigit:]]{40}\scommit\s(\d+)$/) {
1783                                 $first = 0;
1784                                 $size = $1;
1785                                 next;
1786                         } elsif ($line =~ /^(git-svn-id: )/) {
1787                                 my (undef, $rev, undef) =
1788                                                       extract_metadata($line);
1789                                 $s2r{$sha} = $rev;
1790                         }
1792                         $size -= length($line);
1793                         last if ($size == 0);
1794                 }
1795         }
1797         command_close_bidi_pipe($pid, $in, $out, $ctx);
1799         return \%s2r;
1802 sub working_head_info {
1803         my ($head, $refs) = @_;
1804         my @args = qw/log --no-color --no-decorate --first-parent
1805                       --pretty=medium/;
1806         my ($fh, $ctx) = command_output_pipe(@args, $head);
1807         my $hash;
1808         my %max;
1809         while (<$fh>) {
1810                 if ( m{^commit ($::sha1)$} ) {
1811                         unshift @$refs, $hash if $hash and $refs;
1812                         $hash = $1;
1813                         next;
1814                 }
1815                 next unless s{^\s*(git-svn-id:)}{$1};
1816                 my ($url, $rev, $uuid) = extract_metadata($_);
1817                 if (defined $url && defined $rev) {
1818                         next if $max{$url} and $max{$url} < $rev;
1819                         if (my $gs = Git::SVN->find_by_url($url)) {
1820                                 my $c = $gs->rev_map_get($rev, $uuid);
1821                                 if ($c && $c eq $hash) {
1822                                         close $fh; # break the pipe
1823                                         return ($url, $rev, $uuid, $gs);
1824                                 } else {
1825                                         $max{$url} ||= $gs->rev_map_max;
1826                                 }
1827                         }
1828                 }
1829         }
1830         command_close_pipe($fh, $ctx);
1831         (undef, undef, undef, undef);
1834 sub read_commit_parents {
1835         my ($parents, $c) = @_;
1836         chomp(my $p = command_oneline(qw/rev-list --parents -1/, $c));
1837         $p =~ s/^($c)\s*// or die "rev-list --parents -1 $c failed!\n";
1838         @{$parents->{$c}} = split(/ /, $p);
1841 sub linearize_history {
1842         my ($gs, $refs) = @_;
1843         my %parents;
1844         foreach my $c (@$refs) {
1845                 read_commit_parents(\%parents, $c);
1846         }
1848         my @linear_refs;
1849         my %skip = ();
1850         my $last_svn_commit = $gs->last_commit;
1851         foreach my $c (reverse @$refs) {
1852                 next if $c eq $last_svn_commit;
1853                 last if $skip{$c};
1855                 unshift @linear_refs, $c;
1856                 $skip{$c} = 1;
1858                 # we only want the first parent to diff against for linear
1859                 # history, we save the rest to inject when we finalize the
1860                 # svn commit
1861                 my $fp_a = verify_ref("$c~1");
1862                 my $fp_b = shift @{$parents{$c}} if $parents{$c};
1863                 if (!$fp_a || !$fp_b) {
1864                         die "Commit $c\n",
1865                             "has no parent commit, and therefore ",
1866                             "nothing to diff against.\n",
1867                             "You should be working from a repository ",
1868                             "originally created by git-svn\n";
1869                 }
1870                 if ($fp_a ne $fp_b) {
1871                         die "$c~1 = $fp_a, however parsing commit $c ",
1872                             "revealed that:\n$c~1 = $fp_b\nBUG!\n";
1873                 }
1875                 foreach my $p (@{$parents{$c}}) {
1876                         $skip{$p} = 1;
1877                 }
1878         }
1879         (\@linear_refs, \%parents);
1882 sub find_file_type_and_diff_status {
1883         my ($path) = @_;
1884         return ('dir', '') if $path eq '';
1886         my $diff_output =
1887             command_oneline(qw(diff --cached --name-status --), $path) || "";
1888         my $diff_status = (split(' ', $diff_output))[0] || "";
1890         my $ls_tree = command_oneline(qw(ls-tree HEAD), $path) || "";
1892         return (undef, undef) if !$diff_status && !$ls_tree;
1894         if ($diff_status eq "A") {
1895                 return ("link", $diff_status) if -l $path;
1896                 return ("dir", $diff_status) if -d $path;
1897                 return ("file", $diff_status);
1898         }
1900         my $mode = (split(' ', $ls_tree))[0] || "";
1902         return ("link", $diff_status) if $mode eq "120000";
1903         return ("dir", $diff_status) if $mode eq "040000";
1904         return ("file", $diff_status);
1907 sub md5sum {
1908         my $arg = shift;
1909         my $ref = ref $arg;
1910         my $md5 = Digest::MD5->new();
1911         if ($ref eq 'GLOB' || $ref eq 'IO::File' || $ref eq 'File::Temp') {
1912                 $md5->addfile($arg) or croak $!;
1913         } elsif ($ref eq 'SCALAR') {
1914                 $md5->add($$arg) or croak $!;
1915         } elsif (!$ref) {
1916                 $md5->add($arg) or croak $!;
1917         } else {
1918                 ::fatal "Can't provide MD5 hash for unknown ref type: '", $ref, "'";
1919         }
1920         return $md5->hexdigest();
1923 sub gc_directory {
1924         if ($can_compress && -f $_ && basename($_) eq "unhandled.log") {
1925                 my $out_filename = $_ . ".gz";
1926                 open my $in_fh, "<", $_ or die "Unable to open $_: $!\n";
1927                 binmode $in_fh;
1928                 my $gz = Compress::Zlib::gzopen($out_filename, "ab") or
1929                                 die "Unable to open $out_filename: $!\n";
1931                 my $res;
1932                 while ($res = sysread($in_fh, my $str, 1024)) {
1933                         $gz->gzwrite($str) or
1934                                 die "Unable to write: ".$gz->gzerror()."!\n";
1935                 }
1936                 unlink $_ or die "unlink $File::Find::name: $!\n";
1937         } elsif (-f $_ && basename($_) eq "index") {
1938                 unlink $_ or die "unlink $_: $!\n";
1939         }
1942 package Git::SVN;
1943 use strict;
1944 use warnings;
1945 use Fcntl qw/:DEFAULT :seek/;
1946 use constant rev_map_fmt => 'NH40';
1947 use vars qw/$default_repo_id $default_ref_id $_no_metadata $_follow_parent
1948             $_repack $_repack_flags $_use_svm_props $_head
1949             $_use_svnsync_props $no_reuse_existing $_minimize_url
1950             $_use_log_author $_add_author_from $_localtime/;
1951 use Carp qw/croak/;
1952 use File::Path qw/mkpath/;
1953 use File::Copy qw/copy/;
1954 use IPC::Open3;
1955 use Memoize;  # core since 5.8.0, Jul 2002
1956 use Memoize::Storable;
1958 my ($_gc_nr, $_gc_period);
1960 # properties that we do not log:
1961 my %SKIP_PROP;
1962 BEGIN {
1963         %SKIP_PROP = map { $_ => 1 } qw/svn:wc:ra_dav:version-url
1964                                         svn:special svn:executable
1965                                         svn:entry:committed-rev
1966                                         svn:entry:last-author
1967                                         svn:entry:uuid
1968                                         svn:entry:committed-date/;
1970         # some options are read globally, but can be overridden locally
1971         # per [svn-remote "..."] section.  Command-line options will *NOT*
1972         # override options set in an [svn-remote "..."] section
1973         no strict 'refs';
1974         for my $option (qw/follow_parent no_metadata use_svm_props
1975                            use_svnsync_props/) {
1976                 my $key = $option;
1977                 $key =~ tr/_//d;
1978                 my $prop = "-$option";
1979                 *$option = sub {
1980                         my ($self) = @_;
1981                         return $self->{$prop} if exists $self->{$prop};
1982                         my $k = "svn-remote.$self->{repo_id}.$key";
1983                         eval { command_oneline(qw/config --get/, $k) };
1984                         if ($@) {
1985                                 $self->{$prop} = ${"Git::SVN::_$option"};
1986                         } else {
1987                                 my $v = command_oneline(qw/config --bool/,$k);
1988                                 $self->{$prop} = $v eq 'false' ? 0 : 1;
1989                         }
1990                         return $self->{$prop};
1991                 }
1992         }
1996 my (%LOCKFILES, %INDEX_FILES);
1997 END {
1998         unlink keys %LOCKFILES if %LOCKFILES;
1999         unlink keys %INDEX_FILES if %INDEX_FILES;
2002 sub resolve_local_globs {
2003         my ($url, $fetch, $glob_spec) = @_;
2004         return unless defined $glob_spec;
2005         my $ref = $glob_spec->{ref};
2006         my $path = $glob_spec->{path};
2007         foreach (command(qw#for-each-ref --format=%(refname) refs/#)) {
2008                 next unless m#^$ref->{regex}$#;
2009                 my $p = $1;
2010                 my $pathname = desanitize_refname($path->full_path($p));
2011                 my $refname = desanitize_refname($ref->full_path($p));
2012                 if (my $existing = $fetch->{$pathname}) {
2013                         if ($existing ne $refname) {
2014                                 die "Refspec conflict:\n",
2015                                     "existing: $existing\n",
2016                                     " globbed: $refname\n";
2017                         }
2018                         my $u = (::cmt_metadata("$refname"))[0];
2019                         $u =~ s!^\Q$url\E(/|$)!! or die
2020                           "$refname: '$url' not found in '$u'\n";
2021                         if ($pathname ne $u) {
2022                                 warn "W: Refspec glob conflict ",
2023                                      "(ref: $refname):\n",
2024                                      "expected path: $pathname\n",
2025                                      "    real path: $u\n",
2026                                      "Continuing ahead with $u\n";
2027                                 next;
2028                         }
2029                 } else {
2030                         $fetch->{$pathname} = $refname;
2031                 }
2032         }
2035 sub parse_revision_argument {
2036         my ($base, $head) = @_;
2037         if (!defined $::_revision || $::_revision eq 'BASE:HEAD') {
2038                 return ($base, $head);
2039         }
2040         return ($1, $2) if ($::_revision =~ /^(\d+):(\d+)$/);
2041         return ($::_revision, $::_revision) if ($::_revision =~ /^\d+$/);
2042         return ($head, $head) if ($::_revision eq 'HEAD');
2043         return ($base, $1) if ($::_revision =~ /^BASE:(\d+)$/);
2044         return ($1, $head) if ($::_revision =~ /^(\d+):HEAD$/);
2045         die "revision argument: $::_revision not understood by git-svn\n";
2048 sub fetch_all {
2049         my ($repo_id, $remotes) = @_;
2050         if (ref $repo_id) {
2051                 my $gs = $repo_id;
2052                 $repo_id = undef;
2053                 $repo_id = $gs->{repo_id};
2054         }
2055         $remotes ||= read_all_remotes();
2056         my $remote = $remotes->{$repo_id} or
2057                      die "[svn-remote \"$repo_id\"] unknown\n";
2058         my $fetch = $remote->{fetch};
2059         my $url = $remote->{url} or die "svn-remote.$repo_id.url not defined\n";
2060         my (@gs, @globs);
2061         my $ra = Git::SVN::Ra->new($url);
2062         my $uuid = $ra->get_uuid;
2063         my $head = $ra->get_latest_revnum;
2065         # ignore errors, $head revision may not even exist anymore
2066         eval { $ra->get_log("", $head, 0, 1, 0, 1, sub { $head = $_[1] }) };
2067         warn "W: $@\n" if $@;
2069         my $base = defined $fetch ? $head : 0;
2071         # read the max revs for wildcard expansion (branches/*, tags/*)
2072         foreach my $t (qw/branches tags/) {
2073                 defined $remote->{$t} or next;
2074                 push @globs, @{$remote->{$t}};
2076                 my $max_rev = eval { tmp_config(qw/--int --get/,
2077                                          "svn-remote.$repo_id.${t}-maxRev") };
2078                 if (defined $max_rev && ($max_rev < $base)) {
2079                         $base = $max_rev;
2080                 } elsif (!defined $max_rev) {
2081                         $base = 0;
2082                 }
2083         }
2085         if ($fetch) {
2086                 foreach my $p (sort keys %$fetch) {
2087                         my $gs = Git::SVN->new($fetch->{$p}, $repo_id, $p);
2088                         my $lr = $gs->rev_map_max;
2089                         if (defined $lr) {
2090                                 $base = $lr if ($lr < $base);
2091                         }
2092                         push @gs, $gs;
2093                 }
2094         }
2096         ($base, $head) = parse_revision_argument($base, $head);
2097         $ra->gs_fetch_loop_common($base, $head, \@gs, \@globs);
2100 sub read_all_remotes {
2101         my $r = {};
2102         my $use_svm_props = eval { command_oneline(qw/config --bool
2103             svn.useSvmProps/) };
2104         $use_svm_props = $use_svm_props eq 'true' if $use_svm_props;
2105         my $svn_refspec = qr{\s*(.*?)\s*:\s*(.+?)\s*};
2106         foreach (grep { s/^svn-remote\.// } command(qw/config -l/)) {
2107                 if (m!^(.+)\.fetch=$svn_refspec$!) {
2108                         my ($remote, $local_ref, $remote_ref) = ($1, $2, $3);
2109                         die("svn-remote.$remote: remote ref '$remote_ref' "
2110                             . "must start with 'refs/'\n")
2111                                 unless $remote_ref =~ m{^refs/};
2112                         $local_ref = uri_decode($local_ref);
2113                         $r->{$remote}->{fetch}->{$local_ref} = $remote_ref;
2114                         $r->{$remote}->{svm} = {} if $use_svm_props;
2115                 } elsif (m!^(.+)\.usesvmprops=\s*(.*)\s*$!) {
2116                         $r->{$1}->{svm} = {};
2117                 } elsif (m!^(.+)\.url=\s*(.*)\s*$!) {
2118                         $r->{$1}->{url} = $2;
2119                 } elsif (m!^(.+)\.pushurl=\s*(.*)\s*$!) {
2120                         $r->{$1}->{pushurl} = $2;
2121                 } elsif (m!^(.+)\.(branches|tags)=$svn_refspec$!) {
2122                         my ($remote, $t, $local_ref, $remote_ref) =
2123                                                              ($1, $2, $3, $4);
2124                         die("svn-remote.$remote: remote ref '$remote_ref' ($t) "
2125                             . "must start with 'refs/'\n")
2126                                 unless $remote_ref =~ m{^refs/};
2127                         $local_ref = uri_decode($local_ref);
2128                         my $rs = {
2129                             t => $t,
2130                             remote => $remote,
2131                             path => Git::SVN::GlobSpec->new($local_ref, 1),
2132                             ref => Git::SVN::GlobSpec->new($remote_ref, 0) };
2133                         if (length($rs->{ref}->{right}) != 0) {
2134                                 die "The '*' glob character must be the last ",
2135                                     "character of '$remote_ref'\n";
2136                         }
2137                         push @{ $r->{$remote}->{$t} }, $rs;
2138                 }
2139         }
2141         map {
2142                 if (defined $r->{$_}->{svm}) {
2143                         my $svm;
2144                         eval {
2145                                 my $section = "svn-remote.$_";
2146                                 $svm = {
2147                                         source => tmp_config('--get',
2148                                             "$section.svm-source"),
2149                                         replace => tmp_config('--get',
2150                                             "$section.svm-replace"),
2151                                 }
2152                         };
2153                         $r->{$_}->{svm} = $svm;
2154                 }
2155         } keys %$r;
2157         $r;
2160 sub init_vars {
2161         $_gc_nr = $_gc_period = 1000;
2162         if (defined $_repack || defined $_repack_flags) {
2163                warn "Repack options are obsolete; they have no effect.\n";
2164         }
2167 sub verify_remotes_sanity {
2168         return unless -d $ENV{GIT_DIR};
2169         my %seen;
2170         foreach (command(qw/config -l/)) {
2171                 if (m!^svn-remote\.(?:.+)\.fetch=.*:refs/remotes/(\S+)\s*$!) {
2172                         if ($seen{$1}) {
2173                                 die "Remote ref refs/remote/$1 is tracked by",
2174                                     "\n  \"$_\"\nand\n  \"$seen{$1}\"\n",
2175                                     "Please resolve this ambiguity in ",
2176                                     "your git configuration file before ",
2177                                     "continuing\n";
2178                         }
2179                         $seen{$1} = $_;
2180                 }
2181         }
2184 sub find_existing_remote {
2185         my ($url, $remotes) = @_;
2186         return undef if $no_reuse_existing;
2187         my $existing;
2188         foreach my $repo_id (keys %$remotes) {
2189                 my $u = $remotes->{$repo_id}->{url} or next;
2190                 next if $u ne $url;
2191                 $existing = $repo_id;
2192                 last;
2193         }
2194         $existing;
2197 sub init_remote_config {
2198         my ($self, $url, $no_write) = @_;
2199         $url =~ s!/+$!!; # strip trailing slash
2200         my $r = read_all_remotes();
2201         my $existing = find_existing_remote($url, $r);
2202         if ($existing) {
2203                 unless ($no_write) {
2204                         print STDERR "Using existing ",
2205                                      "[svn-remote \"$existing\"]\n";
2206                 }
2207                 $self->{repo_id} = $existing;
2208         } elsif ($_minimize_url) {
2209                 my $min_url = Git::SVN::Ra->new($url)->minimize_url;
2210                 $existing = find_existing_remote($min_url, $r);
2211                 if ($existing) {
2212                         unless ($no_write) {
2213                                 print STDERR "Using existing ",
2214                                              "[svn-remote \"$existing\"]\n";
2215                         }
2216                         $self->{repo_id} = $existing;
2217                 }
2218                 if ($min_url ne $url) {
2219                         unless ($no_write) {
2220                                 print STDERR "Using higher level of URL: ",
2221                                              "$url => $min_url\n";
2222                         }
2223                         my $old_path = $self->{path};
2224                         $self->{path} = $url;
2225                         $self->{path} =~ s!^\Q$min_url\E(/|$)!!;
2226                         if (length $old_path) {
2227                                 $self->{path} .= "/$old_path";
2228                         }
2229                         $url = $min_url;
2230                 }
2231         }
2232         my $orig_url;
2233         if (!$existing) {
2234                 # verify that we aren't overwriting anything:
2235                 $orig_url = eval {
2236                         command_oneline('config', '--get',
2237                                         "svn-remote.$self->{repo_id}.url")
2238                 };
2239                 if ($orig_url && ($orig_url ne $url)) {
2240                         die "svn-remote.$self->{repo_id}.url already set: ",
2241                             "$orig_url\nwanted to set to: $url\n";
2242                 }
2243         }
2244         my ($xrepo_id, $xpath) = find_ref($self->refname);
2245         if (!$no_write && defined $xpath) {
2246                 die "svn-remote.$xrepo_id.fetch already set to track ",
2247                     "$xpath:", $self->refname, "\n";
2248         }
2249         unless ($no_write) {
2250                 command_noisy('config',
2251                               "svn-remote.$self->{repo_id}.url", $url);
2252                 $self->{path} =~ s{^/}{};
2253                 $self->{path} =~ s{%([0-9A-F]{2})}{chr hex($1)}ieg;
2254                 command_noisy('config', '--add',
2255                               "svn-remote.$self->{repo_id}.fetch",
2256                               "$self->{path}:".$self->refname);
2257         }
2258         $self->{url} = $url;
2261 sub find_by_url { # repos_root and, path are optional
2262         my ($class, $full_url, $repos_root, $path) = @_;
2264         return undef unless defined $full_url;
2265         remove_username($full_url);
2266         remove_username($repos_root) if defined $repos_root;
2267         my $remotes = read_all_remotes();
2268         if (defined $full_url && defined $repos_root && !defined $path) {
2269                 $path = $full_url;
2270                 $path =~ s#^\Q$repos_root\E(?:/|$)##;
2271         }
2272         foreach my $repo_id (keys %$remotes) {
2273                 my $u = $remotes->{$repo_id}->{url} or next;
2274                 remove_username($u);
2275                 next if defined $repos_root && $repos_root ne $u;
2277                 my $fetch = $remotes->{$repo_id}->{fetch} || {};
2278                 foreach my $t (qw/branches tags/) {
2279                         foreach my $globspec (@{$remotes->{$repo_id}->{$t}}) {
2280                                 resolve_local_globs($u, $fetch, $globspec);
2281                         }
2282                 }
2283                 my $p = $path;
2284                 my $rwr = rewrite_root({repo_id => $repo_id});
2285                 my $svm = $remotes->{$repo_id}->{svm}
2286                         if defined $remotes->{$repo_id}->{svm};
2287                 unless (defined $p) {
2288                         $p = $full_url;
2289                         my $z = $u;
2290                         my $prefix = '';
2291                         if ($rwr) {
2292                                 $z = $rwr;
2293                                 remove_username($z);
2294                         } elsif (defined $svm) {
2295                                 $z = $svm->{source};
2296                                 $prefix = $svm->{replace};
2297                                 $prefix =~ s#^\Q$u\E(?:/|$)##;
2298                                 $prefix =~ s#/$##;
2299                         }
2300                         $p =~ s#^\Q$z\E(?:/|$)#$prefix# or next;
2301                 }
2302                 foreach my $f (keys %$fetch) {
2303                         next if $f ne $p;
2304                         return Git::SVN->new($fetch->{$f}, $repo_id, $f);
2305                 }
2306         }
2307         undef;
2310 sub init {
2311         my ($class, $url, $path, $repo_id, $ref_id, $no_write) = @_;
2312         my $self = _new($class, $repo_id, $ref_id, $path);
2313         if (defined $url) {
2314                 $self->init_remote_config($url, $no_write);
2315         }
2316         $self;
2319 sub find_ref {
2320         my ($ref_id) = @_;
2321         foreach (command(qw/config -l/)) {
2322                 next unless m!^svn-remote\.(.+)\.fetch=
2323                               \s*(.*?)\s*:\s*(.+?)\s*$!x;
2324                 my ($repo_id, $path, $ref) = ($1, $2, $3);
2325                 if ($ref eq $ref_id) {
2326                         $path = '' if ($path =~ m#^\./?#);
2327                         return ($repo_id, $path);
2328                 }
2329         }
2330         (undef, undef, undef);
2333 sub new {
2334         my ($class, $ref_id, $repo_id, $path) = @_;
2335         if (defined $ref_id && !defined $repo_id && !defined $path) {
2336                 ($repo_id, $path) = find_ref($ref_id);
2337                 if (!defined $repo_id) {
2338                         die "Could not find a \"svn-remote.*.fetch\" key ",
2339                             "in the repository configuration matching: ",
2340                             "$ref_id\n";
2341                 }
2342         }
2343         my $self = _new($class, $repo_id, $ref_id, $path);
2344         if (!defined $self->{path} || !length $self->{path}) {
2345                 my $fetch = command_oneline('config', '--get',
2346                                             "svn-remote.$repo_id.fetch",
2347                                             ":$ref_id\$") or
2348                      die "Failed to read \"svn-remote.$repo_id.fetch\" ",
2349                          "\":$ref_id\$\" in config\n";
2350                 ($self->{path}, undef) = split(/\s*:\s*/, $fetch);
2351         }
2352         $self->{path} =~ s{/+}{/}g;
2353         $self->{path} =~ s{\A/}{};
2354         $self->{path} =~ s{/\z}{};
2355         $self->{url} = command_oneline('config', '--get',
2356                                        "svn-remote.$repo_id.url") or
2357                   die "Failed to read \"svn-remote.$repo_id.url\" in config\n";
2358         $self->{pushurl} = eval { command_oneline('config', '--get',
2359                                   "svn-remote.$repo_id.pushurl") };
2360         $self->rebuild;
2361         $self;
2364 sub refname {
2365         my ($refname) = $_[0]->{ref_id} ;
2367         # It cannot end with a slash /, we'll throw up on this because
2368         # SVN can't have directories with a slash in their name, either:
2369         if ($refname =~ m{/$}) {
2370                 die "ref: '$refname' ends with a trailing slash, this is ",
2371                     "not permitted by git nor Subversion\n";
2372         }
2374         # It cannot have ASCII control character space, tilde ~, caret ^,
2375         # colon :, question-mark ?, asterisk *, space, or open bracket [
2376         # anywhere.
2377         #
2378         # Additionally, % must be escaped because it is used for escaping
2379         # and we want our escaped refname to be reversible
2380         $refname =~ s{([ \%~\^:\?\*\[\t])}{uc sprintf('%%%02x',ord($1))}eg;
2382         # no slash-separated component can begin with a dot .
2383         # /.* becomes /%2E*
2384         $refname =~ s{/\.}{/%2E}g;
2386         # It cannot have two consecutive dots .. anywhere
2387         # .. becomes %2E%2E
2388         $refname =~ s{\.\.}{%2E%2E}g;
2390         # trailing dots and .lock are not allowed
2391         # .$ becomes %2E and .lock becomes %2Elock
2392         $refname =~ s{\.(?=$|lock$)}{%2E};
2394         # the sequence @{ is used to access the reflog
2395         # @{ becomes %40{
2396         $refname =~ s{\@\{}{%40\{}g;
2398         return $refname;
2401 sub desanitize_refname {
2402         my ($refname) = @_;
2403         $refname =~ s{%(?:([0-9A-F]{2}))}{chr hex($1)}eg;
2404         return $refname;
2407 sub svm_uuid {
2408         my ($self) = @_;
2409         return $self->{svm}->{uuid} if $self->svm;
2410         $self->ra;
2411         unless ($self->{svm}) {
2412                 die "SVM UUID not cached, and reading remotely failed\n";
2413         }
2414         $self->{svm}->{uuid};
2417 sub svm {
2418         my ($self) = @_;
2419         return $self->{svm} if $self->{svm};
2420         my $svm;
2421         # see if we have it in our config, first:
2422         eval {
2423                 my $section = "svn-remote.$self->{repo_id}";
2424                 $svm = {
2425                   source => tmp_config('--get', "$section.svm-source"),
2426                   uuid => tmp_config('--get', "$section.svm-uuid"),
2427                   replace => tmp_config('--get', "$section.svm-replace"),
2428                 }
2429         };
2430         if ($svm && $svm->{source} && $svm->{uuid} && $svm->{replace}) {
2431                 $self->{svm} = $svm;
2432         }
2433         $self->{svm};
2436 sub _set_svm_vars {
2437         my ($self, $ra) = @_;
2438         return $ra if $self->svm;
2440         my @err = ( "useSvmProps set, but failed to read SVM properties\n",
2441                     "(svm:source, svm:uuid) ",
2442                     "from the following URLs:\n" );
2443         sub read_svm_props {
2444                 my ($self, $ra, $path, $r) = @_;
2445                 my $props = ($ra->get_dir($path, $r))[2];
2446                 my $src = $props->{'svm:source'};
2447                 my $uuid = $props->{'svm:uuid'};
2448                 return undef if (!$src || !$uuid);
2450                 chomp($src, $uuid);
2452                 $uuid =~ m{^[0-9a-f\-]{30,}$}i
2453                     or die "doesn't look right - svm:uuid is '$uuid'\n";
2455                 # the '!' is used to mark the repos_root!/relative/path
2456                 $src =~ s{/?!/?}{/};
2457                 $src =~ s{/+$}{}; # no trailing slashes please
2458                 # username is of no interest
2459                 $src =~ s{(^[a-z\+]*://)[^/@]*@}{$1};
2461                 my $replace = $ra->{url};
2462                 $replace .= "/$path" if length $path;
2464                 my $section = "svn-remote.$self->{repo_id}";
2465                 tmp_config("$section.svm-source", $src);
2466                 tmp_config("$section.svm-replace", $replace);
2467                 tmp_config("$section.svm-uuid", $uuid);
2468                 $self->{svm} = {
2469                         source => $src,
2470                         uuid => $uuid,
2471                         replace => $replace
2472                 };
2473         }
2475         my $r = $ra->get_latest_revnum;
2476         my $path = $self->{path};
2477         my %tried;
2478         while (length $path) {
2479                 unless ($tried{"$self->{url}/$path"}) {
2480                         return $ra if $self->read_svm_props($ra, $path, $r);
2481                         $tried{"$self->{url}/$path"} = 1;
2482                 }
2483                 $path =~ s#/?[^/]+$##;
2484         }
2485         die "Path: '$path' should be ''\n" if $path ne '';
2486         return $ra if $self->read_svm_props($ra, $path, $r);
2487         $tried{"$self->{url}/$path"} = 1;
2489         if ($ra->{repos_root} eq $self->{url}) {
2490                 die @err, (map { "  $_\n" } keys %tried), "\n";
2491         }
2493         # nope, make sure we're connected to the repository root:
2494         my $ok;
2495         my @tried_b;
2496         $path = $ra->{svn_path};
2497         $ra = Git::SVN::Ra->new($ra->{repos_root});
2498         while (length $path) {
2499                 unless ($tried{"$ra->{url}/$path"}) {
2500                         $ok = $self->read_svm_props($ra, $path, $r);
2501                         last if $ok;
2502                         $tried{"$ra->{url}/$path"} = 1;
2503                 }
2504                 $path =~ s#/?[^/]+$##;
2505         }
2506         die "Path: '$path' should be ''\n" if $path ne '';
2507         $ok ||= $self->read_svm_props($ra, $path, $r);
2508         $tried{"$ra->{url}/$path"} = 1;
2509         if (!$ok) {
2510                 die @err, (map { "  $_\n" } keys %tried), "\n";
2511         }
2512         Git::SVN::Ra->new($self->{url});
2515 sub svnsync {
2516         my ($self) = @_;
2517         return $self->{svnsync} if $self->{svnsync};
2519         if ($self->no_metadata) {
2520                 die "Can't have both 'noMetadata' and ",
2521                     "'useSvnsyncProps' options set!\n";
2522         }
2523         if ($self->rewrite_root) {
2524                 die "Can't have both 'useSvnsyncProps' and 'rewriteRoot' ",
2525                     "options set!\n";
2526         }
2527         if ($self->rewrite_uuid) {
2528                 die "Can't have both 'useSvnsyncProps' and 'rewriteUUID' ",
2529                     "options set!\n";
2530         }
2532         my $svnsync;
2533         # see if we have it in our config, first:
2534         eval {
2535                 my $section = "svn-remote.$self->{repo_id}";
2537                 my $url = tmp_config('--get', "$section.svnsync-url");
2538                 ($url) = ($url =~ m{^([a-z\+]+://\S+)$}) or
2539                    die "doesn't look right - svn:sync-from-url is '$url'\n";
2541                 my $uuid = tmp_config('--get', "$section.svnsync-uuid");
2542                 ($uuid) = ($uuid =~ m{^([0-9a-f\-]{30,})$}i) or
2543                    die "doesn't look right - svn:sync-from-uuid is '$uuid'\n";
2545                 $svnsync = { url => $url, uuid => $uuid }
2546         };
2547         if ($svnsync && $svnsync->{url} && $svnsync->{uuid}) {
2548                 return $self->{svnsync} = $svnsync;
2549         }
2551         my $err = "useSvnsyncProps set, but failed to read " .
2552                   "svnsync property: svn:sync-from-";
2553         my $rp = $self->ra->rev_proplist(0);
2555         my $url = $rp->{'svn:sync-from-url'} or die $err . "url\n";
2556         ($url) = ($url =~ m{^([a-z\+]+://\S+)$}) or
2557                    die "doesn't look right - svn:sync-from-url is '$url'\n";
2559         my $uuid = $rp->{'svn:sync-from-uuid'} or die $err . "uuid\n";
2560         ($uuid) = ($uuid =~ m{^([0-9a-f\-]{30,})$}i) or
2561                    die "doesn't look right - svn:sync-from-uuid is '$uuid'\n";
2563         my $section = "svn-remote.$self->{repo_id}";
2564         tmp_config('--add', "$section.svnsync-uuid", $uuid);
2565         tmp_config('--add', "$section.svnsync-url", $url);
2566         return $self->{svnsync} = { url => $url, uuid => $uuid };
2569 # this allows us to memoize our SVN::Ra UUID locally and avoid a
2570 # remote lookup (useful for 'git svn log').
2571 sub ra_uuid {
2572         my ($self) = @_;
2573         unless ($self->{ra_uuid}) {
2574                 my $key = "svn-remote.$self->{repo_id}.uuid";
2575                 my $uuid = eval { tmp_config('--get', $key) };
2576                 if (!$@ && $uuid && $uuid =~ /^([a-f\d\-]{30,})$/i) {
2577                         $self->{ra_uuid} = $uuid;
2578                 } else {
2579                         die "ra_uuid called without URL\n" unless $self->{url};
2580                         $self->{ra_uuid} = $self->ra->get_uuid;
2581                         tmp_config('--add', $key, $self->{ra_uuid});
2582                 }
2583         }
2584         $self->{ra_uuid};
2587 sub _set_repos_root {
2588         my ($self, $repos_root) = @_;
2589         my $k = "svn-remote.$self->{repo_id}.reposRoot";
2590         $repos_root ||= $self->ra->{repos_root};
2591         tmp_config($k, $repos_root);
2592         $repos_root;
2595 sub repos_root {
2596         my ($self) = @_;
2597         my $k = "svn-remote.$self->{repo_id}.reposRoot";
2598         eval { tmp_config('--get', $k) } || $self->_set_repos_root;
2601 sub ra {
2602         my ($self) = shift;
2603         my $ra = Git::SVN::Ra->new($self->{url});
2604         $self->_set_repos_root($ra->{repos_root});
2605         if ($self->use_svm_props && !$self->{svm}) {
2606                 if ($self->no_metadata) {
2607                         die "Can't have both 'noMetadata' and ",
2608                             "'useSvmProps' options set!\n";
2609                 } elsif ($self->use_svnsync_props) {
2610                         die "Can't have both 'useSvnsyncProps' and ",
2611                             "'useSvmProps' options set!\n";
2612                 }
2613                 $ra = $self->_set_svm_vars($ra);
2614                 $self->{-want_revprops} = 1;
2615         }
2616         $ra;
2619 # prop_walk(PATH, REV, SUB)
2620 # -------------------------
2621 # Recursively traverse PATH at revision REV and invoke SUB for each
2622 # directory that contains a SVN property.  SUB will be invoked as
2623 # follows:  &SUB(gs, path, props);  where `gs' is this instance of
2624 # Git::SVN, `path' the path to the directory where the properties
2625 # `props' were found.  The `path' will be relative to point of checkout,
2626 # that is, if url://repo/trunk is the current Git branch, and that
2627 # directory contains a sub-directory `d', SUB will be invoked with `/d/'
2628 # as `path' (note the trailing `/').
2629 sub prop_walk {
2630         my ($self, $path, $rev, $sub) = @_;
2632         $path =~ s#^/##;
2633         my ($dirent, undef, $props) = $self->ra->get_dir($path, $rev);
2634         $path =~ s#^/*#/#g;
2635         my $p = $path;
2636         # Strip the irrelevant part of the path.
2637         $p =~ s#^/+\Q$self->{path}\E(/|$)#/#;
2638         # Ensure the path is terminated by a `/'.
2639         $p =~ s#/*$#/#;
2641         # The properties contain all the internal SVN stuff nobody
2642         # (usually) cares about.
2643         my $interesting_props = 0;
2644         foreach (keys %{$props}) {
2645                 # If it doesn't start with `svn:', it must be a
2646                 # user-defined property.
2647                 ++$interesting_props and next if $_ !~ /^svn:/;
2648                 # FIXME: Fragile, if SVN adds new public properties,
2649                 # this needs to be updated.
2650                 ++$interesting_props if /^svn:(?:ignore|keywords|executable
2651                                                  |eol-style|mime-type
2652                                                  |externals|needs-lock)$/x;
2653         }
2654         &$sub($self, $p, $props) if $interesting_props;
2656         foreach (sort keys %$dirent) {
2657                 next if $dirent->{$_}->{kind} != $SVN::Node::dir;
2658                 $self->prop_walk($self->{path} . $p . $_, $rev, $sub);
2659         }
2662 sub last_rev { ($_[0]->last_rev_commit)[0] }
2663 sub last_commit { ($_[0]->last_rev_commit)[1] }
2665 # returns the newest SVN revision number and newest commit SHA1
2666 sub last_rev_commit {
2667         my ($self) = @_;
2668         if (defined $self->{last_rev} && defined $self->{last_commit}) {
2669                 return ($self->{last_rev}, $self->{last_commit});
2670         }
2671         my $c = ::verify_ref($self->refname.'^0');
2672         if ($c && !$self->use_svm_props && !$self->no_metadata) {
2673                 my $rev = (::cmt_metadata($c))[1];
2674                 if (defined $rev) {
2675                         ($self->{last_rev}, $self->{last_commit}) = ($rev, $c);
2676                         return ($rev, $c);
2677                 }
2678         }
2679         my $map_path = $self->map_path;
2680         unless (-e $map_path) {
2681                 ($self->{last_rev}, $self->{last_commit}) = (undef, undef);
2682                 return (undef, undef);
2683         }
2684         my ($rev, $commit) = $self->rev_map_max(1);
2685         ($self->{last_rev}, $self->{last_commit}) = ($rev, $commit);
2686         return ($rev, $commit);
2689 sub get_fetch_range {
2690         my ($self, $min, $max) = @_;
2691         $max ||= $self->ra->get_latest_revnum;
2692         $min ||= $self->rev_map_max;
2693         (++$min, $max);
2696 sub tmp_config {
2697         my (@args) = @_;
2698         my $old_def_config = "$ENV{GIT_DIR}/svn/config";
2699         my $config = "$ENV{GIT_DIR}/svn/.metadata";
2700         if (! -f $config && -f $old_def_config) {
2701                 rename $old_def_config, $config or
2702                        die "Failed rename $old_def_config => $config: $!\n";
2703         }
2704         my $old_config = $ENV{GIT_CONFIG};
2705         $ENV{GIT_CONFIG} = $config;
2706         $@ = undef;
2707         my @ret = eval {
2708                 unless (-f $config) {
2709                         mkfile($config);
2710                         open my $fh, '>', $config or
2711                             die "Can't open $config: $!\n";
2712                         print $fh "; This file is used internally by ",
2713                                   "git-svn\n" or die
2714                                   "Couldn't write to $config: $!\n";
2715                         print $fh "; You should not have to edit it\n" or
2716                               die "Couldn't write to $config: $!\n";
2717                         close $fh or die "Couldn't close $config: $!\n";
2718                 }
2719                 command('config', @args);
2720         };
2721         my $err = $@;
2722         if (defined $old_config) {
2723                 $ENV{GIT_CONFIG} = $old_config;
2724         } else {
2725                 delete $ENV{GIT_CONFIG};
2726         }
2727         die $err if $err;
2728         wantarray ? @ret : $ret[0];
2731 sub tmp_index_do {
2732         my ($self, $sub) = @_;
2733         my $old_index = $ENV{GIT_INDEX_FILE};
2734         $ENV{GIT_INDEX_FILE} = $self->{index};
2735         $@ = undef;
2736         my @ret = eval {
2737                 my ($dir, $base) = ($self->{index} =~ m#^(.*?)/?([^/]+)$#);
2738                 mkpath([$dir]) unless -d $dir;
2739                 &$sub;
2740         };
2741         my $err = $@;
2742         if (defined $old_index) {
2743                 $ENV{GIT_INDEX_FILE} = $old_index;
2744         } else {
2745                 delete $ENV{GIT_INDEX_FILE};
2746         }
2747         die $err if $err;
2748         wantarray ? @ret : $ret[0];
2751 sub assert_index_clean {
2752         my ($self, $treeish) = @_;
2754         $self->tmp_index_do(sub {
2755                 command_noisy('read-tree', $treeish) unless -e $self->{index};
2756                 my $x = command_oneline('write-tree');
2757                 my ($y) = (command(qw/cat-file commit/, $treeish) =~
2758                            /^tree ($::sha1)/mo);
2759                 return if $y eq $x;
2761                 warn "Index mismatch: $y != $x\nrereading $treeish\n";
2762                 unlink $self->{index} or die "unlink $self->{index}: $!\n";
2763                 command_noisy('read-tree', $treeish);
2764                 $x = command_oneline('write-tree');
2765                 if ($y ne $x) {
2766                         ::fatal "trees ($treeish) $y != $x\n",
2767                                 "Something is seriously wrong...";
2768                 }
2769         });
2772 sub get_commit_parents {
2773         my ($self, $log_entry) = @_;
2774         my (%seen, @ret, @tmp);
2775         # legacy support for 'set-tree'; this is only used by set_tree_cb:
2776         if (my $ip = $self->{inject_parents}) {
2777                 if (my $commit = delete $ip->{$log_entry->{revision}}) {
2778                         push @tmp, $commit;
2779                 }
2780         }
2781         if (my $cur = ::verify_ref($self->refname.'^0')) {
2782                 push @tmp, $cur;
2783         }
2784         if (my $ipd = $self->{inject_parents_dcommit}) {
2785                 if (my $commit = delete $ipd->{$log_entry->{revision}}) {
2786                         push @tmp, @$commit;
2787                 }
2788         }
2789         push @tmp, $_ foreach (@{$log_entry->{parents}}, @tmp);
2790         while (my $p = shift @tmp) {
2791                 next if $seen{$p};
2792                 $seen{$p} = 1;
2793                 push @ret, $p;
2794         }
2795         @ret;
2798 sub rewrite_root {
2799         my ($self) = @_;
2800         return $self->{-rewrite_root} if exists $self->{-rewrite_root};
2801         my $k = "svn-remote.$self->{repo_id}.rewriteRoot";
2802         my $rwr = eval { command_oneline(qw/config --get/, $k) };
2803         if ($rwr) {
2804                 $rwr =~ s#/+$##;
2805                 if ($rwr !~ m#^[a-z\+]+://#) {
2806                         die "$rwr is not a valid URL (key: $k)\n";
2807                 }
2808         }
2809         $self->{-rewrite_root} = $rwr;
2812 sub rewrite_uuid {
2813         my ($self) = @_;
2814         return $self->{-rewrite_uuid} if exists $self->{-rewrite_uuid};
2815         my $k = "svn-remote.$self->{repo_id}.rewriteUUID";
2816         my $rwid = eval { command_oneline(qw/config --get/, $k) };
2817         if ($rwid) {
2818                 $rwid =~ s#/+$##;
2819                 if ($rwid !~ m#^[a-f0-9]{8}-(?:[a-f0-9]{4}-){3}[a-f0-9]{12}$#) {
2820                         die "$rwid is not a valid UUID (key: $k)\n";
2821                 }
2822         }
2823         $self->{-rewrite_uuid} = $rwid;
2826 sub metadata_url {
2827         my ($self) = @_;
2828         ($self->rewrite_root || $self->{url}) .
2829            (length $self->{path} ? '/' . $self->{path} : '');
2832 sub full_url {
2833         my ($self) = @_;
2834         $self->{url} . (length $self->{path} ? '/' . $self->{path} : '');
2837 sub full_pushurl {
2838         my ($self) = @_;
2839         if ($self->{pushurl}) {
2840                 return $self->{pushurl} . (length $self->{path} ? '/' .
2841                        $self->{path} : '');
2842         } else {
2843                 return $self->full_url;
2844         }
2847 sub set_commit_header_env {
2848         my ($log_entry) = @_;
2849         my %env;
2850         foreach my $ned (qw/NAME EMAIL DATE/) {
2851                 foreach my $ac (qw/AUTHOR COMMITTER/) {
2852                         $env{"GIT_${ac}_${ned}"} = $ENV{"GIT_${ac}_${ned}"};
2853                 }
2854         }
2856         $ENV{GIT_AUTHOR_NAME} = $log_entry->{name};
2857         $ENV{GIT_AUTHOR_EMAIL} = $log_entry->{email};
2858         $ENV{GIT_AUTHOR_DATE} = $ENV{GIT_COMMITTER_DATE} = $log_entry->{date};
2860         $ENV{GIT_COMMITTER_NAME} = (defined $log_entry->{commit_name})
2861                                                 ? $log_entry->{commit_name}
2862                                                 : $log_entry->{name};
2863         $ENV{GIT_COMMITTER_EMAIL} = (defined $log_entry->{commit_email})
2864                                                 ? $log_entry->{commit_email}
2865                                                 : $log_entry->{email};
2866         \%env;
2869 sub restore_commit_header_env {
2870         my ($env) = @_;
2871         foreach my $ned (qw/NAME EMAIL DATE/) {
2872                 foreach my $ac (qw/AUTHOR COMMITTER/) {
2873                         my $k = "GIT_${ac}_${ned}";
2874                         if (defined $env->{$k}) {
2875                                 $ENV{$k} = $env->{$k};
2876                         } else {
2877                                 delete $ENV{$k};
2878                         }
2879                 }
2880         }
2883 sub gc {
2884         command_noisy('gc', '--auto');
2885 };
2887 sub do_git_commit {
2888         my ($self, $log_entry) = @_;
2889         my $lr = $self->last_rev;
2890         if (defined $lr && $lr >= $log_entry->{revision}) {
2891                 die "Last fetched revision of ", $self->refname,
2892                     " was r$lr, but we are about to fetch: ",
2893                     "r$log_entry->{revision}!\n";
2894         }
2895         if (my $c = $self->rev_map_get($log_entry->{revision})) {
2896                 croak "$log_entry->{revision} = $c already exists! ",
2897                       "Why are we refetching it?\n";
2898         }
2899         my $old_env = set_commit_header_env($log_entry);
2900         my $tree = $log_entry->{tree};
2901         if (!defined $tree) {
2902                 $tree = $self->tmp_index_do(sub {
2903                                             command_oneline('write-tree') });
2904         }
2905         die "Tree is not a valid sha1: $tree\n" if $tree !~ /^$::sha1$/o;
2907         my @exec = ('git', 'commit-tree', $tree);
2908         foreach ($self->get_commit_parents($log_entry)) {
2909                 push @exec, '-p', $_;
2910         }
2911         defined(my $pid = open3(my $msg_fh, my $out_fh, '>&STDERR', @exec))
2912                                                                    or croak $!;
2913         binmode $msg_fh;
2915         # we always get UTF-8 from SVN, but we may want our commits in
2916         # a different encoding.
2917         if (my $enc = Git::config('i18n.commitencoding')) {
2918                 require Encode;
2919                 Encode::from_to($log_entry->{log}, 'UTF-8', $enc);
2920         }
2921         print $msg_fh $log_entry->{log} or croak $!;
2922         restore_commit_header_env($old_env);
2923         unless ($self->no_metadata) {
2924                 print $msg_fh "\ngit-svn-id: $log_entry->{metadata}\n"
2925                               or croak $!;
2926         }
2927         $msg_fh->flush == 0 or croak $!;
2928         close $msg_fh or croak $!;
2929         chomp(my $commit = do { local $/; <$out_fh> });
2930         close $out_fh or croak $!;
2931         waitpid $pid, 0;
2932         croak $? if $?;
2933         if ($commit !~ /^$::sha1$/o) {
2934                 die "Failed to commit, invalid sha1: $commit\n";
2935         }
2937         $self->rev_map_set($log_entry->{revision}, $commit, 1);
2939         $self->{last_rev} = $log_entry->{revision};
2940         $self->{last_commit} = $commit;
2941         print "r$log_entry->{revision}" unless $::_q > 1;
2942         if (defined $log_entry->{svm_revision}) {
2943                  print " (\@$log_entry->{svm_revision})" unless $::_q > 1;
2944                  $self->rev_map_set($log_entry->{svm_revision}, $commit,
2945                                    0, $self->svm_uuid);
2946         }
2947         print " = $commit ($self->{ref_id})\n" unless $::_q > 1;
2948         if (--$_gc_nr == 0) {
2949                 $_gc_nr = $_gc_period;
2950                 gc();
2951         }
2952         return $commit;
2955 sub match_paths {
2956         my ($self, $paths, $r) = @_;
2957         return 1 if $self->{path} eq '';
2958         if (my $path = $paths->{"/$self->{path}"}) {
2959                 return ($path->{action} eq 'D') ? 0 : 1;
2960         }
2961         $self->{path_regex} ||= qr/^\/\Q$self->{path}\E\//;
2962         if (grep /$self->{path_regex}/, keys %$paths) {
2963                 return 1;
2964         }
2965         my $c = '';
2966         foreach (split m#/#, $self->{path}) {
2967                 $c .= "/$_";
2968                 next unless ($paths->{$c} &&
2969                              ($paths->{$c}->{action} =~ /^[AR]$/));
2970                 if ($self->ra->check_path($self->{path}, $r) ==
2971                     $SVN::Node::dir) {
2972                         return 1;
2973                 }
2974         }
2975         return 0;
2978 sub find_parent_branch {
2979         my ($self, $paths, $rev) = @_;
2980         return undef unless $self->follow_parent;
2981         unless (defined $paths) {
2982                 my $err_handler = $SVN::Error::handler;
2983                 $SVN::Error::handler = \&Git::SVN::Ra::skip_unknown_revs;
2984                 $self->ra->get_log([$self->{path}], $rev, $rev, 0, 1, 1,
2985                                    sub { $paths = $_[0] });
2986                 $SVN::Error::handler = $err_handler;
2987         }
2988         return undef unless defined $paths;
2990         # look for a parent from another branch:
2991         my @b_path_components = split m#/#, $self->{path};
2992         my @a_path_components;
2993         my $i;
2994         while (@b_path_components) {
2995                 $i = $paths->{'/'.join('/', @b_path_components)};
2996                 last if $i && defined $i->{copyfrom_path};
2997                 unshift(@a_path_components, pop(@b_path_components));
2998         }
2999         return undef unless defined $i && defined $i->{copyfrom_path};
3000         my $branch_from = $i->{copyfrom_path};
3001         if (@a_path_components) {
3002                 print STDERR "branch_from: $branch_from => ";
3003                 $branch_from .= '/'.join('/', @a_path_components);
3004                 print STDERR $branch_from, "\n";
3005         }
3006         my $r = $i->{copyfrom_rev};
3007         my $repos_root = $self->ra->{repos_root};
3008         my $url = $self->ra->{url};
3009         my $new_url = $url . $branch_from;
3010         print STDERR  "Found possible branch point: ",
3011                       "$new_url => ", $self->full_url, ", $r\n"
3012                       unless $::_q > 1;
3013         $branch_from =~ s#^/##;
3014         my $gs = $self->other_gs($new_url, $url,
3015                                  $branch_from, $r, $self->{ref_id});
3016         my ($r0, $parent) = $gs->find_rev_before($r, 1);
3017         {
3018                 my ($base, $head);
3019                 if (!defined $r0 || !defined $parent) {
3020                         ($base, $head) = parse_revision_argument(0, $r);
3021                 } else {
3022                         if ($r0 < $r) {
3023                                 $gs->ra->get_log([$gs->{path}], $r0 + 1, $r, 1,
3024                                         0, 1, sub { $base = $_[1] - 1 });
3025                         }
3026                 }
3027                 if (defined $base && $base <= $r) {
3028                         $gs->fetch($base, $r);
3029                 }
3030                 ($r0, $parent) = $gs->find_rev_before($r, 1);
3031         }
3032         if (defined $r0 && defined $parent) {
3033                 print STDERR "Found branch parent: ($self->{ref_id}) $parent\n"
3034                              unless $::_q > 1;
3035                 my $ed;
3036                 if ($self->ra->can_do_switch) {
3037                         $self->assert_index_clean($parent);
3038                         print STDERR "Following parent with do_switch\n"
3039                                      unless $::_q > 1;
3040                         # do_switch works with svn/trunk >= r22312, but that
3041                         # is not included with SVN 1.4.3 (the latest version
3042                         # at the moment), so we can't rely on it
3043                         $self->{last_rev} = $r0;
3044                         $self->{last_commit} = $parent;
3045                         $ed = SVN::Git::Fetcher->new($self, $gs->{path});
3046                         $gs->ra->gs_do_switch($r0, $rev, $gs,
3047                                               $self->full_url, $ed)
3048                           or die "SVN connection failed somewhere...\n";
3049                 } elsif ($self->ra->trees_match($new_url, $r0,
3050                                                 $self->full_url, $rev)) {
3051                         print STDERR "Trees match:\n",
3052                                      "  $new_url\@$r0\n",
3053                                      "  ${\$self->full_url}\@$rev\n",
3054                                      "Following parent with no changes\n"
3055                                      unless $::_q > 1;
3056                         $self->tmp_index_do(sub {
3057                             command_noisy('read-tree', $parent);
3058                         });
3059                         $self->{last_commit} = $parent;
3060                 } else {
3061                         print STDERR "Following parent with do_update\n"
3062                                      unless $::_q > 1;
3063                         $ed = SVN::Git::Fetcher->new($self);
3064                         $self->ra->gs_do_update($rev, $rev, $self, $ed)
3065                           or die "SVN connection failed somewhere...\n";
3066                 }
3067                 print STDERR "Successfully followed parent\n" unless $::_q > 1;
3068                 return $self->make_log_entry($rev, [$parent], $ed);
3069         }
3070         return undef;
3073 sub do_fetch {
3074         my ($self, $paths, $rev) = @_;
3075         my $ed;
3076         my ($last_rev, @parents);
3077         if (my $lc = $self->last_commit) {
3078                 # we can have a branch that was deleted, then re-added
3079                 # under the same name but copied from another path, in
3080                 # which case we'll have multiple parents (we don't
3081                 # want to break the original ref, nor lose copypath info):
3082                 if (my $log_entry = $self->find_parent_branch($paths, $rev)) {
3083                         push @{$log_entry->{parents}}, $lc;
3084                         return $log_entry;
3085                 }
3086                 $ed = SVN::Git::Fetcher->new($self);
3087                 $last_rev = $self->{last_rev};
3088                 $ed->{c} = $lc;
3089                 @parents = ($lc);
3090         } else {
3091                 $last_rev = $rev;
3092                 if (my $log_entry = $self->find_parent_branch($paths, $rev)) {
3093                         return $log_entry;
3094                 }
3095                 $ed = SVN::Git::Fetcher->new($self);
3096         }
3097         unless ($self->ra->gs_do_update($last_rev, $rev, $self, $ed)) {
3098                 die "SVN connection failed somewhere...\n";
3099         }
3100         $self->make_log_entry($rev, \@parents, $ed);
3103 sub mkemptydirs {
3104         my ($self, $r) = @_;
3106         sub scan {
3107                 my ($r, $empty_dirs, $line) = @_;
3108                 if (defined $r && $line =~ /^r(\d+)$/) {
3109                         return 0 if $1 > $r;
3110                 } elsif ($line =~ /^  \+empty_dir: (.+)$/) {
3111                         $empty_dirs->{$1} = 1;
3112                 } elsif ($line =~ /^  \-empty_dir: (.+)$/) {
3113                         my @d = grep {m[^\Q$1\E(/|$)]} (keys %$empty_dirs);
3114                         delete @$empty_dirs{@d};
3115                 }
3116                 1; # continue
3117         };
3119         my %empty_dirs = ();
3120         my $gz_file = "$self->{dir}/unhandled.log.gz";
3121         if (-f $gz_file) {
3122                 if (!$can_compress) {
3123                         warn "Compress::Zlib could not be found; ",
3124                              "empty directories in $gz_file will not be read\n";
3125                 } else {
3126                         my $gz = Compress::Zlib::gzopen($gz_file, "rb") or
3127                                 die "Unable to open $gz_file: $!\n";
3128                         my $line;
3129                         while ($gz->gzreadline($line) > 0) {
3130                                 scan($r, \%empty_dirs, $line) or last;
3131                         }
3132                         $gz->gzclose;
3133                 }
3134         }
3136         if (open my $fh, '<', "$self->{dir}/unhandled.log") {
3137                 binmode $fh or croak "binmode: $!";
3138                 while (<$fh>) {
3139                         scan($r, \%empty_dirs, $_) or last;
3140                 }
3141                 close $fh;
3142         }
3144         my $strip = qr/\A\Q$self->{path}\E(?:\/|$)/;
3145         foreach my $d (sort keys %empty_dirs) {
3146                 $d = uri_decode($d);
3147                 $d =~ s/$strip//;
3148                 next unless length($d);
3149                 next if -d $d;
3150                 if (-e $d) {
3151                         warn "$d exists but is not a directory\n";
3152                 } else {
3153                         print "creating empty directory: $d\n";
3154                         mkpath([$d]);
3155                 }
3156         }
3159 sub get_untracked {
3160         my ($self, $ed) = @_;
3161         my @out;
3162         my $h = $ed->{empty};
3163         foreach (sort keys %$h) {
3164                 my $act = $h->{$_} ? '+empty_dir' : '-empty_dir';
3165                 push @out, "  $act: " . uri_encode($_);
3166                 warn "W: $act: $_\n";
3167         }
3168         foreach my $t (qw/dir_prop file_prop/) {
3169                 $h = $ed->{$t} or next;
3170                 foreach my $path (sort keys %$h) {
3171                         my $ppath = $path eq '' ? '.' : $path;
3172                         foreach my $prop (sort keys %{$h->{$path}}) {
3173                                 next if $SKIP_PROP{$prop};
3174                                 my $v = $h->{$path}->{$prop};
3175                                 my $t_ppath_prop = "$t: " .
3176                                                     uri_encode($ppath) . ' ' .
3177                                                     uri_encode($prop);
3178                                 if (defined $v) {
3179                                         push @out, "  +$t_ppath_prop " .
3180                                                    uri_encode($v);
3181                                 } else {
3182                                         push @out, "  -$t_ppath_prop";
3183                                 }
3184                         }
3185                 }
3186         }
3187         foreach my $t (qw/absent_file absent_directory/) {
3188                 $h = $ed->{$t} or next;
3189                 foreach my $parent (sort keys %$h) {
3190                         foreach my $path (sort @{$h->{$parent}}) {
3191                                 push @out, "  $t: " .
3192                                            uri_encode("$parent/$path");
3193                                 warn "W: $t: $parent/$path ",
3194                                      "Insufficient permissions?\n";
3195                         }
3196                 }
3197         }
3198         \@out;
3201 # parse_svn_date(DATE)
3202 # --------------------
3203 # Given a date (in UTC) from Subversion, return a string in the format
3204 # "<TZ Offset> <local date/time>" that Git will use.
3206 # By default the parsed date will be in UTC; if $Git::SVN::_localtime
3207 # is true we'll convert it to the local timezone instead.
3208 sub parse_svn_date {
3209         my $date = shift || return '+0000 1970-01-01 00:00:00';
3210         my ($Y,$m,$d,$H,$M,$S) = ($date =~ /^(\d{4})\-(\d\d)\-(\d\d)T
3211                                             (\d\d)\:(\d\d)\:(\d\d)\.\d*Z$/x) or
3212                                          croak "Unable to parse date: $date\n";
3213         my $parsed_date;    # Set next.
3215         if ($Git::SVN::_localtime) {
3216                 # Translate the Subversion datetime to an epoch time.
3217                 # Begin by switching ourselves to $date's timezone, UTC.
3218                 my $old_env_TZ = $ENV{TZ};
3219                 $ENV{TZ} = 'UTC';
3221                 my $epoch_in_UTC =
3222                     POSIX::strftime('%s', $S, $M, $H, $d, $m - 1, $Y - 1900);
3224                 # Determine our local timezone (including DST) at the
3225                 # time of $epoch_in_UTC.  $Git::SVN::Log::TZ stored the
3226                 # value of TZ, if any, at the time we were run.
3227                 if (defined $Git::SVN::Log::TZ) {
3228                         $ENV{TZ} = $Git::SVN::Log::TZ;
3229                 } else {
3230                         delete $ENV{TZ};
3231                 }
3233                 my $our_TZ =
3234                     POSIX::strftime('%Z', $S, $M, $H, $d, $m - 1, $Y - 1900);
3236                 # This converts $epoch_in_UTC into our local timezone.
3237                 my ($sec, $min, $hour, $mday, $mon, $year,
3238                     $wday, $yday, $isdst) = localtime($epoch_in_UTC);
3240                 $parsed_date = sprintf('%s %04d-%02d-%02d %02d:%02d:%02d',
3241                                        $our_TZ, $year + 1900, $mon + 1,
3242                                        $mday, $hour, $min, $sec);
3244                 # Reset us to the timezone in effect when we entered
3245                 # this routine.
3246                 if (defined $old_env_TZ) {
3247                         $ENV{TZ} = $old_env_TZ;
3248                 } else {
3249                         delete $ENV{TZ};
3250                 }
3251         } else {
3252                 $parsed_date = "+0000 $Y-$m-$d $H:$M:$S";
3253         }
3255         return $parsed_date;
3258 sub other_gs {
3259         my ($self, $new_url, $url,
3260             $branch_from, $r, $old_ref_id) = @_;
3261         my $gs = Git::SVN->find_by_url($new_url, $url, $branch_from);
3262         unless ($gs) {
3263                 my $ref_id = $old_ref_id;
3264                 $ref_id =~ s/\@\d+-*$//;
3265                 $ref_id .= "\@$r";
3266                 # just grow a tail if we're not unique enough :x
3267                 $ref_id .= '-' while find_ref($ref_id);
3268                 my ($u, $p, $repo_id) = ($new_url, '', $ref_id);
3269                 if ($u =~ s#^\Q$url\E(/|$)##) {
3270                         $p = $u;
3271                         $u = $url;
3272                         $repo_id = $self->{repo_id};
3273                 }
3274                 while (1) {
3275                         # It is possible to tag two different subdirectories at
3276                         # the same revision.  If the url for an existing ref
3277                         # does not match, we must either find a ref with a
3278                         # matching url or create a new ref by growing a tail.
3279                         $gs = Git::SVN->init($u, $p, $repo_id, $ref_id, 1);
3280                         my (undef, $max_commit) = $gs->rev_map_max(1);
3281                         last if (!$max_commit);
3282                         my ($url) = ::cmt_metadata($max_commit);
3283                         last if ($url eq $gs->metadata_url);
3284                         $ref_id .= '-';
3285                 }
3286                 print STDERR "Initializing parent: $ref_id\n" unless $::_q > 1;
3287         }
3288         $gs
3291 sub call_authors_prog {
3292         my ($orig_author) = @_;
3293         $orig_author = command_oneline('rev-parse', '--sq-quote', $orig_author);
3294         my $author = `$::_authors_prog $orig_author`;
3295         if ($? != 0) {
3296                 die "$::_authors_prog failed with exit code $?\n"
3297         }
3298         if ($author =~ /^\s*(.+?)\s*<(.*)>\s*$/) {
3299                 my ($name, $email) = ($1, $2);
3300                 $email = undef if length $2 == 0;
3301                 return [$name, $email];
3302         } else {
3303                 die "Author: $orig_author: $::_authors_prog returned "
3304                         . "invalid author format: $author\n";
3305         }
3308 sub check_author {
3309         my ($author) = @_;
3310         if (!defined $author || length $author == 0) {
3311                 $author = '(no author)';
3312         }
3313         if (!defined $::users{$author}) {
3314                 if (defined $::_authors_prog) {
3315                         $::users{$author} = call_authors_prog($author);
3316                 } elsif (defined $::_authors) {
3317                         die "Author: $author not defined in $::_authors file\n";
3318                 }
3319         }
3320         $author;
3323 sub find_extra_svk_parents {
3324         my ($self, $ed, $tickets, $parents) = @_;
3325         # aha!  svk:merge property changed...
3326         my @tickets = split "\n", $tickets;
3327         my @known_parents;
3328         for my $ticket ( @tickets ) {
3329                 my ($uuid, $path, $rev) = split /:/, $ticket;
3330                 if ( $uuid eq $self->ra_uuid ) {
3331                         my $url = $self->{url};
3332                         my $repos_root = $url;
3333                         my $branch_from = $path;
3334                         $branch_from =~ s{^/}{};
3335                         my $gs = $self->other_gs($repos_root."/".$branch_from,
3336                                                  $url,
3337                                                  $branch_from,
3338                                                  $rev,
3339                                                  $self->{ref_id});
3340                         if ( my $commit = $gs->rev_map_get($rev, $uuid) ) {
3341                                 # wahey!  we found it, but it might be
3342                                 # an old one (!)
3343                                 push @known_parents, [ $rev, $commit ];
3344                         }
3345                 }
3346         }
3347         # Ordering matters; highest-numbered commit merge tickets
3348         # first, as they may account for later merge ticket additions
3349         # or changes.
3350         @known_parents = map {$_->[1]} sort {$b->[0] <=> $a->[0]} @known_parents;
3351         for my $parent ( @known_parents ) {
3352                 my @cmd = ('rev-list', $parent, map { "^$_" } @$parents );
3353                 my ($msg_fh, $ctx) = command_output_pipe(@cmd);
3354                 my $new;
3355                 while ( <$msg_fh> ) {
3356                         $new=1;last;
3357                 }
3358                 command_close_pipe($msg_fh, $ctx);
3359                 if ( $new ) {
3360                         print STDERR
3361                             "Found merge parent (svk:merge ticket): $parent\n";
3362                         push @$parents, $parent;
3363                 }
3364         }
3367 sub lookup_svn_merge {
3368         my $uuid = shift;
3369         my $url = shift;
3370         my $merge = shift;
3372         my ($source, $revs) = split ":", $merge;
3373         my $path = $source;
3374         $path =~ s{^/}{};
3375         my $gs = Git::SVN->find_by_url($url.$source, $url, $path);
3376         if ( !$gs ) {
3377                 warn "Couldn't find revmap for $url$source\n";
3378                 return;
3379         }
3380         my @ranges = split ",", $revs;
3381         my ($tip, $tip_commit);
3382         my @merged_commit_ranges;
3383         # find the tip
3384         for my $range ( @ranges ) {
3385                 my ($bottom, $top) = split "-", $range;
3386                 $top ||= $bottom;
3387                 my $bottom_commit = $gs->find_rev_after( $bottom, 1, $top );
3388                 my $top_commit = $gs->find_rev_before( $top, 1, $bottom );
3390                 unless ($top_commit and $bottom_commit) {
3391                         warn "W:unknown path/rev in svn:mergeinfo "
3392                                 ."dirprop: $source:$range\n";
3393                         next;
3394                 }
3396                 if (scalar(command('rev-parse', "$bottom_commit^@"))) {
3397                         push @merged_commit_ranges,
3398                              "$bottom_commit^..$top_commit";
3399                 } else {
3400                         push @merged_commit_ranges, "$top_commit";
3401                 }
3403                 if ( !defined $tip or $top > $tip ) {
3404                         $tip = $top;
3405                         $tip_commit = $top_commit;
3406                 }
3407         }
3408         return ($tip_commit, @merged_commit_ranges);
3411 sub _rev_list {
3412         my ($msg_fh, $ctx) = command_output_pipe(
3413                 "rev-list", @_,
3414                );
3415         my @rv;
3416         while ( <$msg_fh> ) {
3417                 chomp;
3418                 push @rv, $_;
3419         }
3420         command_close_pipe($msg_fh, $ctx);
3421         @rv;
3424 sub check_cherry_pick {
3425         my $base = shift;
3426         my $tip = shift;
3427         my $parents = shift;
3428         my @ranges = @_;
3429         my %commits = map { $_ => 1 }
3430                 _rev_list("--no-merges", $tip, "--not", $base, @$parents, "--");
3431         for my $range ( @ranges ) {
3432                 delete @commits{_rev_list($range, "--")};
3433         }
3434         for my $commit (keys %commits) {
3435                 if (has_no_changes($commit)) {
3436                         delete $commits{$commit};
3437                 }
3438         }
3439         return (keys %commits);
3442 sub has_no_changes {
3443         my $commit = shift;
3445         my @revs = split / /, command_oneline(
3446                 qw(rev-list --parents -1 -m), $commit);
3448         # Commits with no parents, e.g. the start of a partial branch,
3449         # have changes by definition.
3450         return 1 if (@revs < 2);
3452         # Commits with multiple parents, e.g a merge, have no changes
3453         # by definition.
3454         return 0 if (@revs > 2);
3456         return (command_oneline("rev-parse", "$commit^{tree}") eq
3457                 command_oneline("rev-parse", "$commit~1^{tree}"));
3460 # The GIT_DIR environment variable is not always set until after the command
3461 # line arguments are processed, so we can't memoize in a BEGIN block.
3463         my $memoized = 0;
3465         sub memoize_svn_mergeinfo_functions {
3466                 return if $memoized;
3467                 $memoized = 1;
3469                 my $cache_path = "$ENV{GIT_DIR}/svn/.caches/";
3470                 mkpath([$cache_path]) unless -d $cache_path;
3472                 tie my %lookup_svn_merge_cache => 'Memoize::Storable',
3473                     "$cache_path/lookup_svn_merge.db", 'nstore';
3474                 memoize 'lookup_svn_merge',
3475                         SCALAR_CACHE => 'FAULT',
3476                         LIST_CACHE => ['HASH' => \%lookup_svn_merge_cache],
3477                 ;
3479                 tie my %check_cherry_pick_cache => 'Memoize::Storable',
3480                     "$cache_path/check_cherry_pick.db", 'nstore';
3481                 memoize 'check_cherry_pick',
3482                         SCALAR_CACHE => 'FAULT',
3483                         LIST_CACHE => ['HASH' => \%check_cherry_pick_cache],
3484                 ;
3486                 tie my %has_no_changes_cache => 'Memoize::Storable',
3487                     "$cache_path/has_no_changes.db", 'nstore';
3488                 memoize 'has_no_changes',
3489                         SCALAR_CACHE => ['HASH' => \%has_no_changes_cache],
3490                         LIST_CACHE => 'FAULT',
3491                 ;
3492         }
3494         sub unmemoize_svn_mergeinfo_functions {
3495                 return if not $memoized;
3496                 $memoized = 0;
3498                 Memoize::unmemoize 'lookup_svn_merge';
3499                 Memoize::unmemoize 'check_cherry_pick';
3500                 Memoize::unmemoize 'has_no_changes';
3501         }
3503         Memoize::memoize 'Git::SVN::repos_root';
3506 END {
3507         # Force cache writeout explicitly instead of waiting for
3508         # global destruction to avoid segfault in Storable:
3509         # http://rt.cpan.org/Public/Bug/Display.html?id=36087
3510         unmemoize_svn_mergeinfo_functions();
3513 sub parents_exclude {
3514         my $parents = shift;
3515         my @commits = @_;
3516         return unless @commits;
3518         my @excluded;
3519         my $excluded;
3520         do {
3521                 my @cmd = ('rev-list', "-1", @commits, "--not", @$parents );
3522                 $excluded = command_oneline(@cmd);
3523                 if ( $excluded ) {
3524                         my @new;
3525                         my $found;
3526                         for my $commit ( @commits ) {
3527                                 if ( $commit eq $excluded ) {
3528                                         push @excluded, $commit;
3529                                         $found++;
3530                                         last;
3531                                 }
3532                                 else {
3533                                         push @new, $commit;
3534                                 }
3535                         }
3536                         die "saw commit '$excluded' in rev-list output, "
3537                                 ."but we didn't ask for that commit (wanted: @commits --not @$parents)"
3538                                         unless $found;
3539                         @commits = @new;
3540                 }
3541         }
3542                 while ($excluded and @commits);
3544         return @excluded;
3548 # note: this function should only be called if the various dirprops
3549 # have actually changed
3550 sub find_extra_svn_parents {
3551         my ($self, $ed, $mergeinfo, $parents) = @_;
3552         # aha!  svk:merge property changed...
3554         memoize_svn_mergeinfo_functions();
3556         # We first search for merged tips which are not in our
3557         # history.  Then, we figure out which git revisions are in
3558         # that tip, but not this revision.  If all of those revisions
3559         # are now marked as merge, we can add the tip as a parent.
3560         my @merges = split "\n", $mergeinfo;
3561         my @merge_tips;
3562         my $url = $self->{url};
3563         my $uuid = $self->ra_uuid;
3564         my %ranges;
3565         for my $merge ( @merges ) {
3566                 my ($tip_commit, @ranges) =
3567                         lookup_svn_merge( $uuid, $url, $merge );
3568                 unless (!$tip_commit or
3569                                 grep { $_ eq $tip_commit } @$parents ) {
3570                         push @merge_tips, $tip_commit;
3571                         $ranges{$tip_commit} = \@ranges;
3572                 } else {
3573                         push @merge_tips, undef;
3574                 }
3575         }
3577         my %excluded = map { $_ => 1 }
3578                 parents_exclude($parents, grep { defined } @merge_tips);
3580         # check merge tips for new parents
3581         my @new_parents;
3582         for my $merge_tip ( @merge_tips ) {
3583                 my $spec = shift @merges;
3584                 next unless $merge_tip and $excluded{$merge_tip};
3586                 my $ranges = $ranges{$merge_tip};
3588                 # check out 'new' tips
3589                 my $merge_base;
3590                 eval {
3591                         $merge_base = command_oneline(
3592                                 "merge-base",
3593                                 @$parents, $merge_tip,
3594                         );
3595                 };
3596                 if ($@) {
3597                         die "An error occurred during merge-base"
3598                                 unless $@->isa("Git::Error::Command");
3600                         warn "W: Cannot find common ancestor between ".
3601                              "@$parents and $merge_tip. Ignoring merge info.\n";
3602                         next;
3603                 }
3605                 # double check that there are no missing non-merge commits
3606                 my (@incomplete) = check_cherry_pick(
3607                         $merge_base, $merge_tip,
3608                         $parents,
3609                         @$ranges,
3610                        );
3612                 if ( @incomplete ) {
3613                         warn "W:svn cherry-pick ignored ($spec) - missing "
3614                                 .@incomplete." commit(s) (eg $incomplete[0])\n";
3615                 } else {
3616                         warn
3617                                 "Found merge parent (svn:mergeinfo prop): ",
3618                                         $merge_tip, "\n";
3619                         push @new_parents, $merge_tip;
3620                 }
3621         }
3623         # cater for merges which merge commits from multiple branches
3624         if ( @new_parents > 1 ) {
3625                 for ( my $i = 0; $i <= $#new_parents; $i++ ) {
3626                         for ( my $j = 0; $j <= $#new_parents; $j++ ) {
3627                                 next if $i == $j;
3628                                 next unless $new_parents[$i];
3629                                 next unless $new_parents[$j];
3630                                 my $revs = command_oneline(
3631                                         "rev-list", "-1",
3632                                         "$new_parents[$i]..$new_parents[$j]",
3633                                        );
3634                                 if ( !$revs ) {
3635                                         undef($new_parents[$j]);
3636                                 }
3637                         }
3638                 }
3639         }
3640         push @$parents, grep { defined } @new_parents;
3643 sub make_log_entry {
3644         my ($self, $rev, $parents, $ed) = @_;
3645         my $untracked = $self->get_untracked($ed);
3647         my @parents = @$parents;
3648         my $ps = $ed->{path_strip} || "";
3649         for my $path ( grep { m/$ps/ } %{$ed->{dir_prop}} ) {
3650                 my $props = $ed->{dir_prop}{$path};
3651                 if ( $props->{"svk:merge"} ) {
3652                         $self->find_extra_svk_parents
3653                                 ($ed, $props->{"svk:merge"}, \@parents);
3654                 }
3655                 if ( $props->{"svn:mergeinfo"} ) {
3656                         $self->find_extra_svn_parents
3657                                 ($ed,
3658                                  $props->{"svn:mergeinfo"},
3659                                  \@parents);
3660                 }
3661         }
3663         open my $un, '>>', "$self->{dir}/unhandled.log" or croak $!;
3664         print $un "r$rev\n" or croak $!;
3665         print $un $_, "\n" foreach @$untracked;
3666         my %log_entry = ( parents => \@parents, revision => $rev,
3667                           log => '');
3669         my $headrev;
3670         my $logged = delete $self->{logged_rev_props};
3671         if (!$logged || $self->{-want_revprops}) {
3672                 my $rp = $self->ra->rev_proplist($rev);
3673                 foreach (sort keys %$rp) {
3674                         my $v = $rp->{$_};
3675                         if (/^svn:(author|date|log)$/) {
3676                                 $log_entry{$1} = $v;
3677                         } elsif ($_ eq 'svm:headrev') {
3678                                 $headrev = $v;
3679                         } else {
3680                                 print $un "  rev_prop: ", uri_encode($_), ' ',
3681                                           uri_encode($v), "\n";
3682                         }
3683                 }
3684         } else {
3685                 map { $log_entry{$_} = $logged->{$_} } keys %$logged;
3686         }
3687         close $un or croak $!;
3689         $log_entry{date} = parse_svn_date($log_entry{date});
3690         $log_entry{log} .= "\n";
3691         my $author = $log_entry{author} = check_author($log_entry{author});
3692         my ($name, $email) = defined $::users{$author} ? @{$::users{$author}}
3693                                                        : ($author, undef);
3695         my ($commit_name, $commit_email) = ($name, $email);
3696         if ($_use_log_author) {
3697                 my $name_field;
3698                 if ($log_entry{log} =~ /From:\s+(.*\S)\s*\n/i) {
3699                         $name_field = $1;
3700                 } elsif ($log_entry{log} =~ /Signed-off-by:\s+(.*\S)\s*\n/i) {
3701                         $name_field = $1;
3702                 }
3703                 if (!defined $name_field) {
3704                         if (!defined $email) {
3705                                 $email = $name;
3706                         }
3707                 } elsif ($name_field =~ /(.*?)\s+<(.*)>/) {
3708                         ($name, $email) = ($1, $2);
3709                 } elsif ($name_field =~ /(.*)@/) {
3710                         ($name, $email) = ($1, $name_field);
3711                 } else {
3712                         ($name, $email) = ($name_field, $name_field);
3713                 }
3714         }
3715         if (defined $headrev && $self->use_svm_props) {
3716                 if ($self->rewrite_root) {
3717                         die "Can't have both 'useSvmProps' and 'rewriteRoot' ",
3718                             "options set!\n";
3719                 }
3720                 if ($self->rewrite_uuid) {
3721                         die "Can't have both 'useSvmProps' and 'rewriteUUID' ",
3722                             "options set!\n";
3723                 }
3724                 my ($uuid, $r) = $headrev =~ m{^([a-f\d\-]{30,}):(\d+)$}i;
3725                 # we don't want "SVM: initializing mirror for junk" ...
3726                 return undef if $r == 0;
3727                 my $svm = $self->svm;
3728                 if ($uuid ne $svm->{uuid}) {
3729                         die "UUID mismatch on SVM path:\n",
3730                             "expected: $svm->{uuid}\n",
3731                             "     got: $uuid\n";
3732                 }
3733                 my $full_url = $self->full_url;
3734                 $full_url =~ s#^\Q$svm->{replace}\E(/|$)#$svm->{source}$1# or
3735                              die "Failed to replace '$svm->{replace}' with ",
3736                                  "'$svm->{source}' in $full_url\n";
3737                 # throw away username for storing in records
3738                 remove_username($full_url);
3739                 $log_entry{metadata} = "$full_url\@$r $uuid";
3740                 $log_entry{svm_revision} = $r;
3741                 $email ||= "$author\@$uuid";
3742                 $commit_email ||= "$author\@$uuid";
3743         } elsif ($self->use_svnsync_props) {
3744                 my $full_url = $self->svnsync->{url};
3745                 $full_url .= "/$self->{path}" if length $self->{path};
3746                 remove_username($full_url);
3747                 my $uuid = $self->svnsync->{uuid};
3748                 $log_entry{metadata} = "$full_url\@$rev $uuid";
3749                 $email ||= "$author\@$uuid";
3750                 $commit_email ||= "$author\@$uuid";
3751         } else {
3752                 my $url = $self->metadata_url;
3753                 remove_username($url);
3754                 my $uuid = $self->rewrite_uuid || $self->ra->get_uuid;
3755                 $log_entry{metadata} = "$url\@$rev " . $uuid;
3756                 $email ||= "$author\@" . $uuid;
3757                 $commit_email ||= "$author\@" . $uuid;
3758         }
3759         $log_entry{name} = $name;
3760         $log_entry{email} = $email;
3761         $log_entry{commit_name} = $commit_name;
3762         $log_entry{commit_email} = $commit_email;
3763         \%log_entry;
3766 sub fetch {
3767         my ($self, $min_rev, $max_rev, @parents) = @_;
3768         my ($last_rev, $last_commit) = $self->last_rev_commit;
3769         my ($base, $head) = $self->get_fetch_range($min_rev, $max_rev);
3770         $self->ra->gs_fetch_loop_common($base, $head, [$self]);
3773 sub set_tree_cb {
3774         my ($self, $log_entry, $tree, $rev, $date, $author) = @_;
3775         $self->{inject_parents} = { $rev => $tree };
3776         $self->fetch(undef, undef);
3779 sub set_tree {
3780         my ($self, $tree) = (shift, shift);
3781         my $log_entry = ::get_commit_entry($tree);
3782         unless ($self->{last_rev}) {
3783                 ::fatal("Must have an existing revision to commit");
3784         }
3785         my %ed_opts = ( r => $self->{last_rev},
3786                         log => $log_entry->{log},
3787                         ra => $self->ra,
3788                         tree_a => $self->{last_commit},
3789                         tree_b => $tree,
3790                         editor_cb => sub {
3791                                $self->set_tree_cb($log_entry, $tree, @_) },
3792                         svn_path => $self->{path} );
3793         if (!SVN::Git::Editor->new(\%ed_opts)->apply_diff) {
3794                 print "No changes\nr$self->{last_rev} = $tree\n";
3795         }
3798 sub rebuild_from_rev_db {
3799         my ($self, $path) = @_;
3800         my $r = -1;
3801         open my $fh, '<', $path or croak "open: $!";
3802         binmode $fh or croak "binmode: $!";
3803         while (<$fh>) {
3804                 length($_) == 41 or croak "inconsistent size in ($_) != 41";
3805                 chomp($_);
3806                 ++$r;
3807                 next if $_ eq ('0' x 40);
3808                 $self->rev_map_set($r, $_);
3809                 print "r$r = $_\n";
3810         }
3811         close $fh or croak "close: $!";
3812         unlink $path or croak "unlink: $!";
3815 sub rebuild {
3816         my ($self) = @_;
3817         my $map_path = $self->map_path;
3818         my $partial = (-e $map_path && ! -z $map_path);
3819         return unless ::verify_ref($self->refname.'^0');
3820         if (!$partial && ($self->use_svm_props || $self->no_metadata)) {
3821                 my $rev_db = $self->rev_db_path;
3822                 $self->rebuild_from_rev_db($rev_db);
3823                 if ($self->use_svm_props) {
3824                         my $svm_rev_db = $self->rev_db_path($self->svm_uuid);
3825                         $self->rebuild_from_rev_db($svm_rev_db);
3826                 }
3827                 $self->unlink_rev_db_symlink;
3828                 return;
3829         }
3830         print "Rebuilding $map_path ...\n" if (!$partial);
3831         my ($base_rev, $head) = ($partial ? $self->rev_map_max_norebuild(1) :
3832                 (undef, undef));
3833         my ($log, $ctx) =
3834             command_output_pipe(qw/rev-list --pretty=raw --no-color --reverse/,
3835                                 ($head ? "$head.." : "") . $self->refname,
3836                                 '--');
3837         my $metadata_url = $self->metadata_url;
3838         remove_username($metadata_url);
3839         my $svn_uuid = $self->rewrite_uuid || $self->ra_uuid;
3840         my $c;
3841         while (<$log>) {
3842                 if ( m{^commit ($::sha1)$} ) {
3843                         $c = $1;
3844                         next;
3845                 }
3846                 next unless s{^\s*(git-svn-id:)}{$1};
3847                 my ($url, $rev, $uuid) = ::extract_metadata($_);
3848                 remove_username($url);
3850                 # ignore merges (from set-tree)
3851                 next if (!defined $rev || !$uuid);
3853                 # if we merged or otherwise started elsewhere, this is
3854                 # how we break out of it
3855                 if (($uuid ne $svn_uuid) ||
3856                     ($metadata_url && $url && ($url ne $metadata_url))) {
3857                         next;
3858                 }
3859                 if ($partial && $head) {
3860                         print "Partial-rebuilding $map_path ...\n";
3861                         print "Currently at $base_rev = $head\n";
3862                         $head = undef;
3863                 }
3865                 $self->rev_map_set($rev, $c);
3866                 print "r$rev = $c\n";
3867         }
3868         command_close_pipe($log, $ctx);
3869         print "Done rebuilding $map_path\n" if (!$partial || !$head);
3870         my $rev_db_path = $self->rev_db_path;
3871         if (-f $self->rev_db_path) {
3872                 unlink $self->rev_db_path or croak "unlink: $!";
3873         }
3874         $self->unlink_rev_db_symlink;
3877 # rev_map:
3878 # Tie::File seems to be prone to offset errors if revisions get sparse,
3879 # it's not that fast, either.  Tie::File is also not in Perl 5.6.  So
3880 # one of my favorite modules is out :<  Next up would be one of the DBM
3881 # modules, but I'm not sure which is most portable...
3883 # This is the replacement for the rev_db format, which was too big
3884 # and inefficient for large repositories with a lot of sparse history
3885 # (mainly tags)
3887 # The format is this:
3888 #   - 24 bytes for every record,
3889 #     * 4 bytes for the integer representing an SVN revision number
3890 #     * 20 bytes representing the sha1 of a git commit
3891 #   - No empty padding records like the old format
3892 #     (except the last record, which can be overwritten)
3893 #   - new records are written append-only since SVN revision numbers
3894 #     increase monotonically
3895 #   - lookups on SVN revision number are done via a binary search
3896 #   - Piping the file to xxd -c24 is a good way of dumping it for
3897 #     viewing or editing (piped back through xxd -r), should the need
3898 #     ever arise.
3899 #   - The last record can be padding revision with an all-zero sha1
3900 #     This is used to optimize fetch performance when using multiple
3901 #     "fetch" directives in .git/config
3903 # These files are disposable unless noMetadata or useSvmProps is set
3905 sub _rev_map_set {
3906         my ($fh, $rev, $commit) = @_;
3908         binmode $fh or croak "binmode: $!";
3909         my $size = (stat($fh))[7];
3910         ($size % 24) == 0 or croak "inconsistent size: $size";
3912         my $wr_offset = 0;
3913         if ($size > 0) {
3914                 sysseek($fh, -24, SEEK_END) or croak "seek: $!";
3915                 my $read = sysread($fh, my $buf, 24) or croak "read: $!";
3916                 $read == 24 or croak "read only $read bytes (!= 24)";
3917                 my ($last_rev, $last_commit) = unpack(rev_map_fmt, $buf);
3918                 if ($last_commit eq ('0' x40)) {
3919                         if ($size >= 48) {
3920                                 sysseek($fh, -48, SEEK_END) or croak "seek: $!";
3921                                 $read = sysread($fh, $buf, 24) or
3922                                     croak "read: $!";
3923                                 $read == 24 or
3924                                     croak "read only $read bytes (!= 24)";
3925                                 ($last_rev, $last_commit) =
3926                                     unpack(rev_map_fmt, $buf);
3927                                 if ($last_commit eq ('0' x40)) {
3928                                         croak "inconsistent .rev_map\n";
3929                                 }
3930                         }
3931                         if ($last_rev >= $rev) {
3932                                 croak "last_rev is higher!: $last_rev >= $rev";
3933                         }
3934                         $wr_offset = -24;
3935                 }
3936         }
3937         sysseek($fh, $wr_offset, SEEK_END) or croak "seek: $!";
3938         syswrite($fh, pack(rev_map_fmt, $rev, $commit), 24) == 24 or
3939           croak "write: $!";
3942 sub _rev_map_reset {
3943         my ($fh, $rev, $commit) = @_;
3944         my $c = _rev_map_get($fh, $rev);
3945         $c eq $commit or die "_rev_map_reset(@_) commit $c does not match!\n";
3946         my $offset = sysseek($fh, 0, SEEK_CUR) or croak "seek: $!";
3947         truncate $fh, $offset or croak "truncate: $!";
3950 sub mkfile {
3951         my ($path) = @_;
3952         unless (-e $path) {
3953                 my ($dir, $base) = ($path =~ m#^(.*?)/?([^/]+)$#);
3954                 mkpath([$dir]) unless -d $dir;
3955                 open my $fh, '>>', $path or die "Couldn't create $path: $!\n";
3956                 close $fh or die "Couldn't close (create) $path: $!\n";
3957         }
3960 sub rev_map_set {
3961         my ($self, $rev, $commit, $update_ref, $uuid) = @_;
3962         defined $commit or die "missing arg3\n";
3963         length $commit == 40 or die "arg3 must be a full SHA1 hexsum\n";
3964         my $db = $self->map_path($uuid);
3965         my $db_lock = "$db.lock";
3966         my $sig;
3967         $update_ref ||= 0;
3968         if ($update_ref) {
3969                 $SIG{INT} = $SIG{HUP} = $SIG{TERM} = $SIG{ALRM} = $SIG{PIPE} =
3970                             $SIG{USR1} = $SIG{USR2} = sub { $sig = $_[0] };
3971         }
3972         mkfile($db);
3974         $LOCKFILES{$db_lock} = 1;
3975         my $sync;
3976         # both of these options make our .rev_db file very, very important
3977         # and we can't afford to lose it because rebuild() won't work
3978         if ($self->use_svm_props || $self->no_metadata) {
3979                 $sync = 1;
3980                 copy($db, $db_lock) or die "rev_map_set(@_): ",
3981                                            "Failed to copy: ",
3982                                            "$db => $db_lock ($!)\n";
3983         } else {
3984                 rename $db, $db_lock or die "rev_map_set(@_): ",
3985                                             "Failed to rename: ",
3986                                             "$db => $db_lock ($!)\n";
3987         }
3989         sysopen(my $fh, $db_lock, O_RDWR | O_CREAT)
3990              or croak "Couldn't open $db_lock: $!\n";
3991         $update_ref eq 'reset' ? _rev_map_reset($fh, $rev, $commit) :
3992                                  _rev_map_set($fh, $rev, $commit);
3993         if ($sync) {
3994                 $fh->flush or die "Couldn't flush $db_lock: $!\n";
3995                 $fh->sync or die "Couldn't sync $db_lock: $!\n";
3996         }
3997         close $fh or croak $!;
3998         if ($update_ref) {
3999                 $_head = $self;
4000                 my $note = "";
4001                 $note = " ($update_ref)" if ($update_ref !~ /^\d*$/);
4002                 command_noisy('update-ref', '-m', "r$rev$note",
4003                               $self->refname, $commit);
4004         }
4005         rename $db_lock, $db or die "rev_map_set(@_): ", "Failed to rename: ",
4006                                     "$db_lock => $db ($!)\n";
4007         delete $LOCKFILES{$db_lock};
4008         if ($update_ref) {
4009                 $SIG{INT} = $SIG{HUP} = $SIG{TERM} = $SIG{ALRM} = $SIG{PIPE} =
4010                             $SIG{USR1} = $SIG{USR2} = 'DEFAULT';
4011                 kill $sig, $$ if defined $sig;
4012         }
4015 # If want_commit, this will return an array of (rev, commit) where
4016 # commit _must_ be a valid commit in the archive.
4017 # Otherwise, it'll return the max revision (whether or not the
4018 # commit is valid or just a 0x40 placeholder).
4019 sub rev_map_max {
4020         my ($self, $want_commit) = @_;
4021         $self->rebuild;
4022         my ($r, $c) = $self->rev_map_max_norebuild($want_commit);
4023         $want_commit ? ($r, $c) : $r;
4026 sub rev_map_max_norebuild {
4027         my ($self, $want_commit) = @_;
4028         my $map_path = $self->map_path;
4029         stat $map_path or return $want_commit ? (0, undef) : 0;
4030         sysopen(my $fh, $map_path, O_RDONLY) or croak "open: $!";
4031         binmode $fh or croak "binmode: $!";
4032         my $size = (stat($fh))[7];
4033         ($size % 24) == 0 or croak "inconsistent size: $size";
4035         if ($size == 0) {
4036                 close $fh or croak "close: $!";
4037                 return $want_commit ? (0, undef) : 0;
4038         }
4040         sysseek($fh, -24, SEEK_END) or croak "seek: $!";
4041         sysread($fh, my $buf, 24) == 24 or croak "read: $!";
4042         my ($r, $c) = unpack(rev_map_fmt, $buf);
4043         if ($want_commit && $c eq ('0' x40)) {
4044                 if ($size < 48) {
4045                         return $want_commit ? (0, undef) : 0;
4046                 }
4047                 sysseek($fh, -48, SEEK_END) or croak "seek: $!";
4048                 sysread($fh, $buf, 24) == 24 or croak "read: $!";
4049                 ($r, $c) = unpack(rev_map_fmt, $buf);
4050                 if ($c eq ('0'x40)) {
4051                         croak "Penultimate record is all-zeroes in $map_path";
4052                 }
4053         }
4054         close $fh or croak "close: $!";
4055         $want_commit ? ($r, $c) : $r;
4058 sub rev_map_get {
4059         my ($self, $rev, $uuid) = @_;
4060         my $map_path = $self->map_path($uuid);
4061         return undef unless -e $map_path;
4063         sysopen(my $fh, $map_path, O_RDONLY) or croak "open: $!";
4064         my $c = _rev_map_get($fh, $rev);
4065         close($fh) or croak "close: $!";
4066         $c
4069 sub _rev_map_get {
4070         my ($fh, $rev) = @_;
4072         binmode $fh or croak "binmode: $!";
4073         my $size = (stat($fh))[7];
4074         ($size % 24) == 0 or croak "inconsistent size: $size";
4076         if ($size == 0) {
4077                 return undef;
4078         }
4080         my ($l, $u) = (0, $size - 24);
4081         my ($r, $c, $buf);
4083         while ($l <= $u) {
4084                 my $i = int(($l/24 + $u/24) / 2) * 24;
4085                 sysseek($fh, $i, SEEK_SET) or croak "seek: $!";
4086                 sysread($fh, my $buf, 24) == 24 or croak "read: $!";
4087                 my ($r, $c) = unpack(rev_map_fmt, $buf);
4089                 if ($r < $rev) {
4090                         $l = $i + 24;
4091                 } elsif ($r > $rev) {
4092                         $u = $i - 24;
4093                 } else { # $r == $rev
4094                         return $c eq ('0' x 40) ? undef : $c;
4095                 }
4096         }
4097         undef;
4100 # Finds the first svn revision that exists on (if $eq_ok is true) or
4101 # before $rev for the current branch.  It will not search any lower
4102 # than $min_rev.  Returns the git commit hash and svn revision number
4103 # if found, else (undef, undef).
4104 sub find_rev_before {
4105         my ($self, $rev, $eq_ok, $min_rev) = @_;
4106         --$rev unless $eq_ok;
4107         $min_rev ||= 1;
4108         my $max_rev = $self->rev_map_max;
4109         $rev = $max_rev if ($rev > $max_rev);
4110         while ($rev >= $min_rev) {
4111                 if (my $c = $self->rev_map_get($rev)) {
4112                         return ($rev, $c);
4113                 }
4114                 --$rev;
4115         }
4116         return (undef, undef);
4119 # Finds the first svn revision that exists on (if $eq_ok is true) or
4120 # after $rev for the current branch.  It will not search any higher
4121 # than $max_rev.  Returns the git commit hash and svn revision number
4122 # if found, else (undef, undef).
4123 sub find_rev_after {
4124         my ($self, $rev, $eq_ok, $max_rev) = @_;
4125         ++$rev unless $eq_ok;
4126         $max_rev ||= $self->rev_map_max;
4127         while ($rev <= $max_rev) {
4128                 if (my $c = $self->rev_map_get($rev)) {
4129                         return ($rev, $c);
4130                 }
4131                 ++$rev;
4132         }
4133         return (undef, undef);
4136 sub _new {
4137         my ($class, $repo_id, $ref_id, $path) = @_;
4138         unless (defined $repo_id && length $repo_id) {
4139                 $repo_id = $Git::SVN::default_repo_id;
4140         }
4141         unless (defined $ref_id && length $ref_id) {
4142                 $_prefix = '' unless defined($_prefix);
4143                 $_[2] = $ref_id =
4144                              "refs/remotes/$_prefix$Git::SVN::default_ref_id";
4145         }
4146         $_[1] = $repo_id;
4147         my $dir = "$ENV{GIT_DIR}/svn/$ref_id";
4149         # Older repos imported by us used $GIT_DIR/svn/foo instead of
4150         # $GIT_DIR/svn/refs/remotes/foo when tracking refs/remotes/foo
4151         if ($ref_id =~ m{^refs/remotes/(.*)}) {
4152                 my $old_dir = "$ENV{GIT_DIR}/svn/$1";
4153                 if (-d $old_dir && ! -d $dir) {
4154                         $dir = $old_dir;
4155                 }
4156         }
4158         $_[3] = $path = '' unless (defined $path);
4159         mkpath([$dir]);
4160         bless {
4161                 ref_id => $ref_id, dir => $dir, index => "$dir/index",
4162                 path => $path, config => "$ENV{GIT_DIR}/svn/config",
4163                 map_root => "$dir/.rev_map", repo_id => $repo_id }, $class;
4166 # for read-only access of old .rev_db formats
4167 sub unlink_rev_db_symlink {
4168         my ($self) = @_;
4169         my $link = $self->rev_db_path;
4170         $link =~ s/\.[\w-]+$// or croak "missing UUID at the end of $link";
4171         if (-l $link) {
4172                 unlink $link or croak "unlink: $link failed!";
4173         }
4176 sub rev_db_path {
4177         my ($self, $uuid) = @_;
4178         my $db_path = $self->map_path($uuid);
4179         $db_path =~ s{/\.rev_map\.}{/\.rev_db\.}
4180             or croak "map_path: $db_path does not contain '/.rev_map.' !";
4181         $db_path;
4184 # the new replacement for .rev_db
4185 sub map_path {
4186         my ($self, $uuid) = @_;
4187         $uuid ||= $self->ra_uuid;
4188         "$self->{map_root}.$uuid";
4191 sub uri_encode {
4192         my ($f) = @_;
4193         $f =~ s#([^a-zA-Z0-9\*!\:_\./\-])#uc sprintf("%%%02x",ord($1))#eg;
4194         $f
4197 sub uri_decode {
4198         my ($f) = @_;
4199         $f =~ s#%([0-9a-fA-F]{2})#chr(hex($1))#eg;
4200         $f
4203 sub remove_username {
4204         $_[0] =~ s{^([^:]*://)[^@]+@}{$1};
4207 package Git::SVN::Prompt;
4208 use strict;
4209 use warnings;
4210 require SVN::Core;
4211 use vars qw/$_no_auth_cache $_username/;
4213 sub simple {
4214         my ($cred, $realm, $default_username, $may_save, $pool) = @_;
4215         $may_save = undef if $_no_auth_cache;
4216         $default_username = $_username if defined $_username;
4217         if (defined $default_username && length $default_username) {
4218                 if (defined $realm && length $realm) {
4219                         print STDERR "Authentication realm: $realm\n";
4220                         STDERR->flush;
4221                 }
4222                 $cred->username($default_username);
4223         } else {
4224                 username($cred, $realm, $may_save, $pool);
4225         }
4226         $cred->password(_read_password("Password for '" .
4227                                        $cred->username . "': ", $realm));
4228         $cred->may_save($may_save);
4229         $SVN::_Core::SVN_NO_ERROR;
4232 sub ssl_server_trust {
4233         my ($cred, $realm, $failures, $cert_info, $may_save, $pool) = @_;
4234         $may_save = undef if $_no_auth_cache;
4235         print STDERR "Error validating server certificate for '$realm':\n";
4236         {
4237                 no warnings 'once';
4238                 # All variables SVN::Auth::SSL::* are used only once,
4239                 # so we're shutting up Perl warnings about this.
4240                 if ($failures & $SVN::Auth::SSL::UNKNOWNCA) {
4241                         print STDERR " - The certificate is not issued ",
4242                             "by a trusted authority. Use the\n",
4243                             "   fingerprint to validate ",
4244                             "the certificate manually!\n";
4245                 }
4246                 if ($failures & $SVN::Auth::SSL::CNMISMATCH) {
4247                         print STDERR " - The certificate hostname ",
4248                             "does not match.\n";
4249                 }
4250                 if ($failures & $SVN::Auth::SSL::NOTYETVALID) {
4251                         print STDERR " - The certificate is not yet valid.\n";
4252                 }
4253                 if ($failures & $SVN::Auth::SSL::EXPIRED) {
4254                         print STDERR " - The certificate has expired.\n";
4255                 }
4256                 if ($failures & $SVN::Auth::SSL::OTHER) {
4257                         print STDERR " - The certificate has ",
4258                             "an unknown error.\n";
4259                 }
4260         } # no warnings 'once'
4261         printf STDERR
4262                 "Certificate information:\n".
4263                 " - Hostname: %s\n".
4264                 " - Valid: from %s until %s\n".
4265                 " - Issuer: %s\n".
4266                 " - Fingerprint: %s\n",
4267                 map $cert_info->$_, qw(hostname valid_from valid_until
4268                                        issuer_dname fingerprint);
4269         my $choice;
4270 prompt:
4271         print STDERR $may_save ?
4272               "(R)eject, accept (t)emporarily or accept (p)ermanently? " :
4273               "(R)eject or accept (t)emporarily? ";
4274         STDERR->flush;
4275         $choice = lc(substr(<STDIN> || 'R', 0, 1));
4276         if ($choice =~ /^t$/i) {
4277                 $cred->may_save(undef);
4278         } elsif ($choice =~ /^r$/i) {
4279                 return -1;
4280         } elsif ($may_save && $choice =~ /^p$/i) {
4281                 $cred->may_save($may_save);
4282         } else {
4283                 goto prompt;
4284         }
4285         $cred->accepted_failures($failures);
4286         $SVN::_Core::SVN_NO_ERROR;
4289 sub ssl_client_cert {
4290         my ($cred, $realm, $may_save, $pool) = @_;
4291         $may_save = undef if $_no_auth_cache;
4292         print STDERR "Client certificate filename: ";
4293         STDERR->flush;
4294         chomp(my $filename = <STDIN>);
4295         $cred->cert_file($filename);
4296         $cred->may_save($may_save);
4297         $SVN::_Core::SVN_NO_ERROR;
4300 sub ssl_client_cert_pw {
4301         my ($cred, $realm, $may_save, $pool) = @_;
4302         $may_save = undef if $_no_auth_cache;
4303         $cred->password(_read_password("Password: ", $realm));
4304         $cred->may_save($may_save);
4305         $SVN::_Core::SVN_NO_ERROR;
4308 sub username {
4309         my ($cred, $realm, $may_save, $pool) = @_;
4310         $may_save = undef if $_no_auth_cache;
4311         if (defined $realm && length $realm) {
4312                 print STDERR "Authentication realm: $realm\n";
4313         }
4314         my $username;
4315         if (defined $_username) {
4316                 $username = $_username;
4317         } else {
4318                 print STDERR "Username: ";
4319                 STDERR->flush;
4320                 chomp($username = <STDIN>);
4321         }
4322         $cred->username($username);
4323         $cred->may_save($may_save);
4324         $SVN::_Core::SVN_NO_ERROR;
4327 sub _read_password {
4328         my ($prompt, $realm) = @_;
4329         my $password = '';
4330         if (exists $ENV{GIT_ASKPASS}) {
4331                 open(PH, "-|", $ENV{GIT_ASKPASS}, $prompt);
4332                 $password = <PH>;
4333                 $password =~ s/[\012\015]//; # \n\r
4334                 close(PH);
4335         } else {
4336                 print STDERR $prompt;
4337                 STDERR->flush;
4338                 require Term::ReadKey;
4339                 Term::ReadKey::ReadMode('noecho');
4340                 while (defined(my $key = Term::ReadKey::ReadKey(0))) {
4341                         last if $key =~ /[\012\015]/; # \n\r
4342                         $password .= $key;
4343                 }
4344                 Term::ReadKey::ReadMode('restore');
4345                 print STDERR "\n";
4346                 STDERR->flush;
4347         }
4348         $password;
4351 package SVN::Git::Fetcher;
4352 use vars qw/@ISA $_ignore_regex $_preserve_empty_dirs $_placeholder_filename
4353             @deleted_gpath %added_placeholder $repo_id/;
4354 use strict;
4355 use warnings;
4356 use Carp qw/croak/;
4357 use File::Basename qw/dirname/;
4358 use IO::File qw//;
4360 # file baton members: path, mode_a, mode_b, pool, fh, blob, base
4361 sub new {
4362         my ($class, $git_svn, $switch_path) = @_;
4363         my $self = SVN::Delta::Editor->new;
4364         bless $self, $class;
4365         if (exists $git_svn->{last_commit}) {
4366                 $self->{c} = $git_svn->{last_commit};
4367                 $self->{empty_symlinks} =
4368                                   _mark_empty_symlinks($git_svn, $switch_path);
4369         }
4371         # some options are read globally, but can be overridden locally
4372         # per [svn-remote "..."] section.  Command-line options will *NOT*
4373         # override options set in an [svn-remote "..."] section
4374         $repo_id = $git_svn->{repo_id};
4375         my $k = "svn-remote.$repo_id.ignore-paths";
4376         my $v = eval { command_oneline('config', '--get', $k) };
4377         $self->{ignore_regex} = $v;
4379         $k = "svn-remote.$repo_id.preserve-empty-dirs";
4380         $v = eval { command_oneline('config', '--get', '--bool', $k) };
4381         if ($v && $v eq 'true') {
4382                 $_preserve_empty_dirs = 1;
4383                 $k = "svn-remote.$repo_id.placeholder-filename";
4384                 $v = eval { command_oneline('config', '--get', $k) };
4385                 $_placeholder_filename = $v;
4386         }
4388         # Load the list of placeholder files added during previous invocations.
4389         $k = "svn-remote.$repo_id.added-placeholder";
4390         $v = eval { command_oneline('config', '--get-all', $k) };
4391         if ($_preserve_empty_dirs && $v) {
4392                 # command() prints errors to stderr, so we only call it if
4393                 # command_oneline() succeeded.
4394                 my @v = command('config', '--get-all', $k);
4395                 $added_placeholder{ dirname($_) } = $_ foreach @v;
4396         }
4398         $self->{empty} = {};
4399         $self->{dir_prop} = {};
4400         $self->{file_prop} = {};
4401         $self->{absent_dir} = {};
4402         $self->{absent_file} = {};
4403         $self->{gii} = $git_svn->tmp_index_do(sub { Git::IndexInfo->new });
4404         $self->{pathnameencoding} = Git::config('svn.pathnameencoding');
4405         $self;
4408 # this uses the Ra object, so it must be called before do_{switch,update},
4409 # not inside them (when the Git::SVN::Fetcher object is passed) to
4410 # do_{switch,update}
4411 sub _mark_empty_symlinks {
4412         my ($git_svn, $switch_path) = @_;
4413         my $bool = Git::config_bool('svn.brokenSymlinkWorkaround');
4414         return {} if (!defined($bool)) || (defined($bool) && ! $bool);
4416         my %ret;
4417         my ($rev, $cmt) = $git_svn->last_rev_commit;
4418         return {} unless ($rev && $cmt);
4420         # allow the warning to be printed for each revision we fetch to
4421         # ensure the user sees it.  The user can also disable the workaround
4422         # on the repository even while git svn is running and the next
4423         # revision fetched will skip this expensive function.
4424         my $printed_warning;
4425         chomp(my $empty_blob = `git hash-object -t blob --stdin < /dev/null`);
4426         my ($ls, $ctx) = command_output_pipe(qw/ls-tree -r -z/, $cmt);
4427         local $/ = "\0";
4428         my $pfx = defined($switch_path) ? $switch_path : $git_svn->{path};
4429         $pfx .= '/' if length($pfx);
4430         while (<$ls>) {
4431                 chomp;
4432                 s/\A100644 blob $empty_blob\t//o or next;
4433                 unless ($printed_warning) {
4434                         print STDERR "Scanning for empty symlinks, ",
4435                                      "this may take a while if you have ",
4436                                      "many empty files\n",
4437                                      "You may disable this with `",
4438                                      "git config svn.brokenSymlinkWorkaround ",
4439                                      "false'.\n",
4440                                      "This may be done in a different ",
4441                                      "terminal without restarting ",
4442                                      "git svn\n";
4443                         $printed_warning = 1;
4444                 }
4445                 my $path = $_;
4446                 my (undef, $props) =
4447                                $git_svn->ra->get_file($pfx.$path, $rev, undef);
4448                 if ($props->{'svn:special'}) {
4449                         $ret{$path} = 1;
4450                 }
4451         }
4452         command_close_pipe($ls, $ctx);
4453         \%ret;
4456 # returns true if a given path is inside a ".git" directory
4457 sub in_dot_git {
4458         $_[0] =~ m{(?:^|/)\.git(?:/|$)};
4461 # return value: 0 -- don't ignore, 1 -- ignore
4462 sub is_path_ignored {
4463         my ($self, $path) = @_;
4464         return 1 if in_dot_git($path);
4465         return 1 if defined($self->{ignore_regex}) &&
4466                     $path =~ m!$self->{ignore_regex}!;
4467         return 0 unless defined($_ignore_regex);
4468         return 1 if $path =~ m!$_ignore_regex!o;
4469         return 0;
4472 sub set_path_strip {
4473         my ($self, $path) = @_;
4474         $self->{path_strip} = qr/^\Q$path\E(\/|$)/ if length $path;
4477 sub open_root {
4478         { path => '' };
4481 sub open_directory {
4482         my ($self, $path, $pb, $rev) = @_;
4483         { path => $path };
4486 sub git_path {
4487         my ($self, $path) = @_;
4488         if (my $enc = $self->{pathnameencoding}) {
4489                 require Encode;
4490                 Encode::from_to($path, 'UTF-8', $enc);
4491         }
4492         if ($self->{path_strip}) {
4493                 $path =~ s!$self->{path_strip}!! or
4494                   die "Failed to strip path '$path' ($self->{path_strip})\n";
4495         }
4496         $path;
4499 sub delete_entry {
4500         my ($self, $path, $rev, $pb) = @_;
4501         return undef if $self->is_path_ignored($path);
4503         my $gpath = $self->git_path($path);
4504         return undef if ($gpath eq '');
4506         # remove entire directories.
4507         my ($tree) = (command('ls-tree', '-z', $self->{c}, "./$gpath")
4508                          =~ /\A040000 tree ([a-f\d]{40})\t\Q$gpath\E\0/);
4509         if ($tree) {
4510                 my ($ls, $ctx) = command_output_pipe(qw/ls-tree
4511                                                      -r --name-only -z/,
4512                                                      $tree);
4513                 local $/ = "\0";
4514                 while (<$ls>) {
4515                         chomp;
4516                         my $rmpath = "$gpath/$_";
4517                         $self->{gii}->remove($rmpath);
4518                         print "\tD\t$rmpath\n" unless $::_q;
4519                 }
4520                 print "\tD\t$gpath/\n" unless $::_q;
4521                 command_close_pipe($ls, $ctx);
4522         } else {
4523                 $self->{gii}->remove($gpath);
4524                 print "\tD\t$gpath\n" unless $::_q;
4525         }
4526         # Don't add to @deleted_gpath if we're deleting a placeholder file.
4527         push @deleted_gpath, $gpath unless $added_placeholder{dirname($path)};
4528         $self->{empty}->{$path} = 0;
4529         undef;
4532 sub open_file {
4533         my ($self, $path, $pb, $rev) = @_;
4534         my ($mode, $blob);
4536         goto out if $self->is_path_ignored($path);
4538         my $gpath = $self->git_path($path);
4539         ($mode, $blob) = (command('ls-tree', '-z', $self->{c}, "./$gpath")
4540                              =~ /\A(\d{6}) blob ([a-f\d]{40})\t\Q$gpath\E\0/);
4541         unless (defined $mode && defined $blob) {
4542                 die "$path was not found in commit $self->{c} (r$rev)\n";
4543         }
4544         if ($mode eq '100644' && $self->{empty_symlinks}->{$path}) {
4545                 $mode = '120000';
4546         }
4547 out:
4548         { path => $path, mode_a => $mode, mode_b => $mode, blob => $blob,
4549           pool => SVN::Pool->new, action => 'M' };
4552 sub add_file {
4553         my ($self, $path, $pb, $cp_path, $cp_rev) = @_;
4554         my $mode;
4556         if (!$self->is_path_ignored($path)) {
4557                 my ($dir, $file) = ($path =~ m#^(.*?)/?([^/]+)$#);
4558                 delete $self->{empty}->{$dir};
4559                 $mode = '100644';
4561                 if ($added_placeholder{$dir}) {
4562                         # Remove our placeholder file, if we created one.
4563                         delete_entry($self, $added_placeholder{$dir})
4564                                 unless $path eq $added_placeholder{$dir};
4565                         delete $added_placeholder{$dir}
4566                 }
4567         }
4569         { path => $path, mode_a => $mode, mode_b => $mode,
4570           pool => SVN::Pool->new, action => 'A' };
4573 sub add_directory {
4574         my ($self, $path, $cp_path, $cp_rev) = @_;
4575         goto out if $self->is_path_ignored($path);
4576         my $gpath = $self->git_path($path);
4577         if ($gpath eq '') {
4578                 my ($ls, $ctx) = command_output_pipe(qw/ls-tree
4579                                                      -r --name-only -z/,
4580                                                      $self->{c});
4581                 local $/ = "\0";
4582                 while (<$ls>) {
4583                         chomp;
4584                         $self->{gii}->remove($_);
4585                         print "\tD\t$_\n" unless $::_q;
4586                         push @deleted_gpath, $gpath;
4587                 }
4588                 command_close_pipe($ls, $ctx);
4589                 $self->{empty}->{$path} = 0;
4590         }
4591         my ($dir, $file) = ($path =~ m#^(.*?)/?([^/]+)$#);
4592         delete $self->{empty}->{$dir};
4593         $self->{empty}->{$path} = 1;
4595         if ($added_placeholder{$dir}) {
4596                 # Remove our placeholder file, if we created one.
4597                 delete_entry($self, $added_placeholder{$dir});
4598                 delete $added_placeholder{$dir}
4599         }
4601 out:
4602         { path => $path };
4605 sub change_dir_prop {
4606         my ($self, $db, $prop, $value) = @_;
4607         return undef if $self->is_path_ignored($db->{path});
4608         $self->{dir_prop}->{$db->{path}} ||= {};
4609         $self->{dir_prop}->{$db->{path}}->{$prop} = $value;
4610         undef;
4613 sub absent_directory {
4614         my ($self, $path, $pb) = @_;
4615         return undef if $self->is_path_ignored($path);
4616         $self->{absent_dir}->{$pb->{path}} ||= [];
4617         push @{$self->{absent_dir}->{$pb->{path}}}, $path;
4618         undef;
4621 sub absent_file {
4622         my ($self, $path, $pb) = @_;
4623         return undef if $self->is_path_ignored($path);
4624         $self->{absent_file}->{$pb->{path}} ||= [];
4625         push @{$self->{absent_file}->{$pb->{path}}}, $path;
4626         undef;
4629 sub change_file_prop {
4630         my ($self, $fb, $prop, $value) = @_;
4631         return undef if $self->is_path_ignored($fb->{path});
4632         if ($prop eq 'svn:executable') {
4633                 if ($fb->{mode_b} != 120000) {
4634                         $fb->{mode_b} = defined $value ? 100755 : 100644;
4635                 }
4636         } elsif ($prop eq 'svn:special') {
4637                 $fb->{mode_b} = defined $value ? 120000 : 100644;
4638         } else {
4639                 $self->{file_prop}->{$fb->{path}} ||= {};
4640                 $self->{file_prop}->{$fb->{path}}->{$prop} = $value;
4641         }
4642         undef;
4645 sub apply_textdelta {
4646         my ($self, $fb, $exp) = @_;
4647         return undef if $self->is_path_ignored($fb->{path});
4648         my $fh = $::_repository->temp_acquire('svn_delta');
4649         # $fh gets auto-closed() by SVN::TxDelta::apply(),
4650         # (but $base does not,) so dup() it for reading in close_file
4651         open my $dup, '<&', $fh or croak $!;
4652         my $base = $::_repository->temp_acquire('git_blob');
4654         if ($fb->{blob}) {
4655                 my ($base_is_link, $size);
4657                 if ($fb->{mode_a} eq '120000' &&
4658                     ! $self->{empty_symlinks}->{$fb->{path}}) {
4659                         print $base 'link ' or die "print $!\n";
4660                         $base_is_link = 1;
4661                 }
4662         retry:
4663                 $size = $::_repository->cat_blob($fb->{blob}, $base);
4664                 die "Failed to read object $fb->{blob}" if ($size < 0);
4666                 if (defined $exp) {
4667                         seek $base, 0, 0 or croak $!;
4668                         my $got = ::md5sum($base);
4669                         if ($got ne $exp) {
4670                                 my $err = "Checksum mismatch: ".
4671                                        "$fb->{path} $fb->{blob}\n" .
4672                                        "expected: $exp\n" .
4673                                        "     got: $got\n";
4674                                 if ($base_is_link) {
4675                                         warn $err,
4676                                              "Retrying... (possibly ",
4677                                              "a bad symlink from SVN)\n";
4678                                         $::_repository->temp_reset($base);
4679                                         $base_is_link = 0;
4680                                         goto retry;
4681                                 }
4682                                 die $err;
4683                         }
4684                 }
4685         }
4686         seek $base, 0, 0 or croak $!;
4687         $fb->{fh} = $fh;
4688         $fb->{base} = $base;
4689         [ SVN::TxDelta::apply($base, $dup, undef, $fb->{path}, $fb->{pool}) ];
4692 sub close_file {
4693         my ($self, $fb, $exp) = @_;
4694         return undef if $self->is_path_ignored($fb->{path});
4696         my $hash;
4697         my $path = $self->git_path($fb->{path});
4698         if (my $fh = $fb->{fh}) {
4699                 if (defined $exp) {
4700                         seek($fh, 0, 0) or croak $!;
4701                         my $got = ::md5sum($fh);
4702                         if ($got ne $exp) {
4703                                 die "Checksum mismatch: $path\n",
4704                                     "expected: $exp\n    got: $got\n";
4705                         }
4706                 }
4707                 if ($fb->{mode_b} == 120000) {
4708                         sysseek($fh, 0, 0) or croak $!;
4709                         my $rd = sysread($fh, my $buf, 5);
4711                         if (!defined $rd) {
4712                                 croak "sysread: $!\n";
4713                         } elsif ($rd == 0) {
4714                                 warn "$path has mode 120000",
4715                                      " but it points to nothing\n",
4716                                      "converting to an empty file with mode",
4717                                      " 100644\n";
4718                                 $fb->{mode_b} = '100644';
4719                         } elsif ($buf ne 'link ') {
4720                                 warn "$path has mode 120000",
4721                                      " but is not a link\n";
4722                         } else {
4723                                 my $tmp_fh = $::_repository->temp_acquire(
4724                                         'svn_hash');
4725                                 my $res;
4726                                 while ($res = sysread($fh, my $str, 1024)) {
4727                                         my $out = syswrite($tmp_fh, $str, $res);
4728                                         defined($out) && $out == $res
4729                                                 or croak("write ",
4730                                                         Git::temp_path($tmp_fh),
4731                                                         ": $!\n");
4732                                 }
4733                                 defined $res or croak $!;
4735                                 ($fh, $tmp_fh) = ($tmp_fh, $fh);
4736                                 Git::temp_release($tmp_fh, 1);
4737                         }
4738                 }
4740                 $hash = $::_repository->hash_and_insert_object(
4741                                 Git::temp_path($fh));
4742                 $hash =~ /^[a-f\d]{40}$/ or die "not a sha1: $hash\n";
4744                 Git::temp_release($fb->{base}, 1);
4745                 Git::temp_release($fh, 1);
4746         } else {
4747                 $hash = $fb->{blob} or die "no blob information\n";
4748         }
4749         $fb->{pool}->clear;
4750         $self->{gii}->update($fb->{mode_b}, $hash, $path) or croak $!;
4751         print "\t$fb->{action}\t$path\n" if $fb->{action} && ! $::_q;
4752         undef;
4755 sub abort_edit {
4756         my $self = shift;
4757         $self->{nr} = $self->{gii}->{nr};
4758         delete $self->{gii};
4759         $self->SUPER::abort_edit(@_);
4762 sub close_edit {
4763         my $self = shift;
4765         if ($_preserve_empty_dirs) {
4766                 my @empty_dirs;
4768                 # Any entry flagged as empty that also has an associated
4769                 # dir_prop represents a newly created empty directory.
4770                 foreach my $i (keys %{$self->{empty}}) {
4771                         push @empty_dirs, $i if exists $self->{dir_prop}->{$i};
4772                 }
4774                 # Search for directories that have become empty due subsequent
4775                 # file deletes.
4776                 push @empty_dirs, $self->find_empty_directories();
4778                 # Finally, add a placeholder file to each empty directory.
4779                 $self->add_placeholder_file($_) foreach (@empty_dirs);
4781                 $self->stash_placeholder_list();
4782         }
4784         $self->{git_commit_ok} = 1;
4785         $self->{nr} = $self->{gii}->{nr};
4786         delete $self->{gii};
4787         $self->SUPER::close_edit(@_);
4790 sub find_empty_directories {
4791         my ($self) = @_;
4792         my @empty_dirs;
4793         my %dirs = map { dirname($_) => 1 } @deleted_gpath;
4795         foreach my $dir (sort keys %dirs) {
4796                 next if $dir eq ".";
4798                 # If there have been any additions to this directory, there is
4799                 # no reason to check if it is empty.
4800                 my $skip_added = 0;
4801                 foreach my $t (qw/dir_prop file_prop/) {
4802                         foreach my $path (keys %{ $self->{$t} }) {
4803                                 if (exists $self->{$t}->{dirname($path)}) {
4804                                         $skip_added = 1;
4805                                         last;
4806                                 }
4807                         }
4808                         last if $skip_added;
4809                 }
4810                 next if $skip_added;
4812                 # Use `git ls-tree` to get the filenames of this directory
4813                 # that existed prior to this particular commit.
4814                 my $ls = command('ls-tree', '-z', '--name-only',
4815                                  $self->{c}, "$dir/");
4816                 my %files = map { $_ => 1 } split(/\0/, $ls);
4818                 # Remove the filenames that were deleted during this commit.
4819                 delete $files{$_} foreach (@deleted_gpath);
4821                 # Report the directory if there are no filenames left.
4822                 push @empty_dirs, $dir unless (scalar %files);
4823         }
4824         @empty_dirs;
4827 sub add_placeholder_file {
4828         my ($self, $dir) = @_;
4829         my $path = "$dir/$_placeholder_filename";
4830         my $gpath = $self->git_path($path);
4832         my $fh = $::_repository->temp_acquire($gpath);
4833         my $hash = $::_repository->hash_and_insert_object(Git::temp_path($fh));
4834         Git::temp_release($fh, 1);
4835         $self->{gii}->update('100644', $hash, $gpath) or croak $!;
4837         # The directory should no longer be considered empty.
4838         delete $self->{empty}->{$dir} if exists $self->{empty}->{$dir};
4840         # Keep track of any placeholder files we create.
4841         $added_placeholder{$dir} = $path;
4844 sub stash_placeholder_list {
4845         my ($self) = @_;
4846         my $k = "svn-remote.$repo_id.added-placeholder";
4847         my $v = eval { command_oneline('config', '--get-all', $k) };
4848         command_noisy('config', '--unset-all', $k) if $v;
4849         foreach (values %added_placeholder) {
4850                 command_noisy('config', '--add', $k, $_);
4851         }
4854 package SVN::Git::Editor;
4855 use vars qw/@ISA $_rmdir $_cp_similarity $_find_copies_harder $_rename_limit/;
4856 use strict;
4857 use warnings;
4858 use Carp qw/croak/;
4859 use IO::File;
4861 sub new {
4862         my ($class, $opts) = @_;
4863         foreach (qw/svn_path r ra tree_a tree_b log editor_cb/) {
4864                 die "$_ required!\n" unless (defined $opts->{$_});
4865         }
4867         my $pool = SVN::Pool->new;
4868         my $mods = generate_diff($opts->{tree_a}, $opts->{tree_b});
4869         my $types = check_diff_paths($opts->{ra}, $opts->{svn_path},
4870                                      $opts->{r}, $mods);
4872         # $opts->{ra} functions should not be used after this:
4873         my @ce  = $opts->{ra}->get_commit_editor($opts->{log},
4874                                                 $opts->{editor_cb}, $pool);
4875         my $self = SVN::Delta::Editor->new(@ce, $pool);
4876         bless $self, $class;
4877         foreach (qw/svn_path r tree_a tree_b/) {
4878                 $self->{$_} = $opts->{$_};
4879         }
4880         $self->{url} = $opts->{ra}->{url};
4881         $self->{mods} = $mods;
4882         $self->{types} = $types;
4883         $self->{pool} = $pool;
4884         $self->{bat} = { '' => $self->open_root($self->{r}, $self->{pool}) };
4885         $self->{rm} = { };
4886         $self->{path_prefix} = length $self->{svn_path} ?
4887                                "$self->{svn_path}/" : '';
4888         $self->{config} = $opts->{config};
4889         $self->{mergeinfo} = $opts->{mergeinfo};
4890         return $self;
4893 sub generate_diff {
4894         my ($tree_a, $tree_b) = @_;
4895         my @diff_tree = qw(diff-tree -z -r);
4896         if ($_cp_similarity) {
4897                 push @diff_tree, "-C$_cp_similarity";
4898         } else {
4899                 push @diff_tree, '-C';
4900         }
4901         push @diff_tree, '--find-copies-harder' if $_find_copies_harder;
4902         push @diff_tree, "-l$_rename_limit" if defined $_rename_limit;
4903         push @diff_tree, $tree_a, $tree_b;
4904         my ($diff_fh, $ctx) = command_output_pipe(@diff_tree);
4905         local $/ = "\0";
4906         my $state = 'meta';
4907         my @mods;
4908         while (<$diff_fh>) {
4909                 chomp $_; # this gets rid of the trailing "\0"
4910                 if ($state eq 'meta' && /^:(\d{6})\s(\d{6})\s
4911                                         ($::sha1)\s($::sha1)\s
4912                                         ([MTCRAD])\d*$/xo) {
4913                         push @mods, {   mode_a => $1, mode_b => $2,
4914                                         sha1_a => $3, sha1_b => $4,
4915                                         chg => $5 };
4916                         if ($5 =~ /^(?:C|R)$/) {
4917                                 $state = 'file_a';
4918                         } else {
4919                                 $state = 'file_b';
4920                         }
4921                 } elsif ($state eq 'file_a') {
4922                         my $x = $mods[$#mods] or croak "Empty array\n";
4923                         if ($x->{chg} !~ /^(?:C|R)$/) {
4924                                 croak "Error parsing $_, $x->{chg}\n";
4925                         }
4926                         $x->{file_a} = $_;
4927                         $state = 'file_b';
4928                 } elsif ($state eq 'file_b') {
4929                         my $x = $mods[$#mods] or croak "Empty array\n";
4930                         if (exists $x->{file_a} && $x->{chg} !~ /^(?:C|R)$/) {
4931                                 croak "Error parsing $_, $x->{chg}\n";
4932                         }
4933                         if (!exists $x->{file_a} && $x->{chg} =~ /^(?:C|R)$/) {
4934                                 croak "Error parsing $_, $x->{chg}\n";
4935                         }
4936                         $x->{file_b} = $_;
4937                         $state = 'meta';
4938                 } else {
4939                         croak "Error parsing $_\n";
4940                 }
4941         }
4942         command_close_pipe($diff_fh, $ctx);
4943         \@mods;
4946 sub check_diff_paths {
4947         my ($ra, $pfx, $rev, $mods) = @_;
4948         my %types;
4949         $pfx .= '/' if length $pfx;
4951         sub type_diff_paths {
4952                 my ($ra, $types, $path, $rev) = @_;
4953                 my @p = split m#/+#, $path;
4954                 my $c = shift @p;
4955                 unless (defined $types->{$c}) {
4956                         $types->{$c} = $ra->check_path($c, $rev);
4957                 }
4958                 while (@p) {
4959                         $c .= '/' . shift @p;
4960                         next if defined $types->{$c};
4961                         $types->{$c} = $ra->check_path($c, $rev);
4962                 }
4963         }
4965         foreach my $m (@$mods) {
4966                 foreach my $f (qw/file_a file_b/) {
4967                         next unless defined $m->{$f};
4968                         my ($dir) = ($m->{$f} =~ m#^(.*?)/?(?:[^/]+)$#);
4969                         if (length $pfx.$dir && ! defined $types{$dir}) {
4970                                 type_diff_paths($ra, \%types, $pfx.$dir, $rev);
4971                         }
4972                 }
4973         }
4974         \%types;
4977 sub split_path {
4978         return ($_[0] =~ m#^(.*?)/?([^/]+)$#);
4981 sub repo_path {
4982         my ($self, $path) = @_;
4983         if (my $enc = $self->{pathnameencoding}) {
4984                 require Encode;
4985                 Encode::from_to($path, $enc, 'UTF-8');
4986         }
4987         $self->{path_prefix}.(defined $path ? $path : '');
4990 sub url_path {
4991         my ($self, $path) = @_;
4992         if ($self->{url} =~ m#^https?://#) {
4993                 $path =~ s!([^~a-zA-Z0-9_./-])!uc sprintf("%%%02x",ord($1))!eg;
4994         }
4995         $self->{url} . '/' . $self->repo_path($path);
4998 sub rmdirs {
4999         my ($self) = @_;
5000         my $rm = $self->{rm};
5001         delete $rm->{''}; # we never delete the url we're tracking
5002         return unless %$rm;
5004         foreach (keys %$rm) {
5005                 my @d = split m#/#, $_;
5006                 my $c = shift @d;
5007                 $rm->{$c} = 1;
5008                 while (@d) {
5009                         $c .= '/' . shift @d;
5010                         $rm->{$c} = 1;
5011                 }
5012         }
5013         delete $rm->{$self->{svn_path}};
5014         delete $rm->{''}; # we never delete the url we're tracking
5015         return unless %$rm;
5017         my ($fh, $ctx) = command_output_pipe(qw/ls-tree --name-only -r -z/,
5018                                              $self->{tree_b});
5019         local $/ = "\0";
5020         while (<$fh>) {
5021                 chomp;
5022                 my @dn = split m#/#, $_;
5023                 while (pop @dn) {
5024                         delete $rm->{join '/', @dn};
5025                 }
5026                 unless (%$rm) {
5027                         close $fh;
5028                         return;
5029                 }
5030         }
5031         command_close_pipe($fh, $ctx);
5033         my ($r, $p, $bat) = ($self->{r}, $self->{pool}, $self->{bat});
5034         foreach my $d (sort { $b =~ tr#/#/# <=> $a =~ tr#/#/# } keys %$rm) {
5035                 $self->close_directory($bat->{$d}, $p);
5036                 my ($dn) = ($d =~ m#^(.*?)/?(?:[^/]+)$#);
5037                 print "\tD+\t$d/\n" unless $::_q;
5038                 $self->SUPER::delete_entry($d, $r, $bat->{$dn}, $p);
5039                 delete $bat->{$d};
5040         }
5043 sub open_or_add_dir {
5044         my ($self, $full_path, $baton) = @_;
5045         my $t = $self->{types}->{$full_path};
5046         if (!defined $t) {
5047                 die "$full_path not known in r$self->{r} or we have a bug!\n";
5048         }
5049         {
5050                 no warnings 'once';
5051                 # SVN::Node::none and SVN::Node::file are used only once,
5052                 # so we're shutting up Perl's warnings about them.
5053                 if ($t == $SVN::Node::none) {
5054                         return $self->add_directory($full_path, $baton,
5055                             undef, -1, $self->{pool});
5056                 } elsif ($t == $SVN::Node::dir) {
5057                         return $self->open_directory($full_path, $baton,
5058                             $self->{r}, $self->{pool});
5059                 } # no warnings 'once'
5060                 print STDERR "$full_path already exists in repository at ",
5061                     "r$self->{r} and it is not a directory (",
5062                     ($t == $SVN::Node::file ? 'file' : 'unknown'),"/$t)\n";
5063         } # no warnings 'once'
5064         exit 1;
5067 sub ensure_path {
5068         my ($self, $path) = @_;
5069         my $bat = $self->{bat};
5070         my $repo_path = $self->repo_path($path);
5071         return $bat->{''} unless (length $repo_path);
5072         my @p = split m#/+#, $repo_path;
5073         my $c = shift @p;
5074         $bat->{$c} ||= $self->open_or_add_dir($c, $bat->{''});
5075         while (@p) {
5076                 my $c0 = $c;
5077                 $c .= '/' . shift @p;
5078                 $bat->{$c} ||= $self->open_or_add_dir($c, $bat->{$c0});
5079         }
5080         return $bat->{$c};
5083 # Subroutine to convert a globbing pattern to a regular expression.
5084 # From perl cookbook.
5085 sub glob2pat {
5086         my $globstr = shift;
5087         my %patmap = ('*' => '.*', '?' => '.', '[' => '[', ']' => ']');
5088         $globstr =~ s{(.)} { $patmap{$1} || "\Q$1" }ge;
5089         return '^' . $globstr . '$';
5092 sub check_autoprop {
5093         my ($self, $pattern, $properties, $file, $fbat) = @_;
5094         # Convert the globbing pattern to a regular expression.
5095         my $regex = glob2pat($pattern);
5096         # Check if the pattern matches the file name.
5097         if($file =~ m/($regex)/) {
5098                 # Parse the list of properties to set.
5099                 my @props = split(/;/, $properties);
5100                 foreach my $prop (@props) {
5101                         # Parse 'name=value' syntax and set the property.
5102                         if ($prop =~ /([^=]+)=(.*)/) {
5103                                 my ($n,$v) = ($1,$2);
5104                                 for ($n, $v) {
5105                                         s/^\s+//; s/\s+$//;
5106                                 }
5107                                 $self->change_file_prop($fbat, $n, $v);
5108                         }
5109                 }
5110         }
5113 sub apply_autoprops {
5114         my ($self, $file, $fbat) = @_;
5115         my $conf_t = ${$self->{config}}{'config'};
5116         no warnings 'once';
5117         # Check [miscellany]/enable-auto-props in svn configuration.
5118         if (SVN::_Core::svn_config_get_bool(
5119                 $conf_t,
5120                 $SVN::_Core::SVN_CONFIG_SECTION_MISCELLANY,
5121                 $SVN::_Core::SVN_CONFIG_OPTION_ENABLE_AUTO_PROPS,
5122                 0)) {
5123                 # Auto-props are enabled.  Enumerate them to look for matches.
5124                 my $callback = sub {
5125                         $self->check_autoprop($_[0], $_[1], $file, $fbat);
5126                 };
5127                 SVN::_Core::svn_config_enumerate(
5128                         $conf_t,
5129                         $SVN::_Core::SVN_CONFIG_SECTION_AUTO_PROPS,
5130                         $callback);
5131         }
5134 sub A {
5135         my ($self, $m) = @_;
5136         my ($dir, $file) = split_path($m->{file_b});
5137         my $pbat = $self->ensure_path($dir);
5138         my $fbat = $self->add_file($self->repo_path($m->{file_b}), $pbat,
5139                                         undef, -1);
5140         print "\tA\t$m->{file_b}\n" unless $::_q;
5141         $self->apply_autoprops($file, $fbat);
5142         $self->chg_file($fbat, $m);
5143         $self->close_file($fbat,undef,$self->{pool});
5146 sub C {
5147         my ($self, $m) = @_;
5148         my ($dir, $file) = split_path($m->{file_b});
5149         my $pbat = $self->ensure_path($dir);
5150         my $fbat = $self->add_file($self->repo_path($m->{file_b}), $pbat,
5151                                 $self->url_path($m->{file_a}), $self->{r});
5152         print "\tC\t$m->{file_a} => $m->{file_b}\n" unless $::_q;
5153         $self->chg_file($fbat, $m);
5154         $self->close_file($fbat,undef,$self->{pool});
5157 sub delete_entry {
5158         my ($self, $path, $pbat) = @_;
5159         my $rpath = $self->repo_path($path);
5160         my ($dir, $file) = split_path($rpath);
5161         $self->{rm}->{$dir} = 1;
5162         $self->SUPER::delete_entry($rpath, $self->{r}, $pbat, $self->{pool});
5165 sub R {
5166         my ($self, $m) = @_;
5167         my ($dir, $file) = split_path($m->{file_b});
5168         my $pbat = $self->ensure_path($dir);
5169         my $fbat = $self->add_file($self->repo_path($m->{file_b}), $pbat,
5170                                 $self->url_path($m->{file_a}), $self->{r});
5171         print "\tR\t$m->{file_a} => $m->{file_b}\n" unless $::_q;
5172         $self->apply_autoprops($file, $fbat);
5173         $self->chg_file($fbat, $m);
5174         $self->close_file($fbat,undef,$self->{pool});
5176         ($dir, $file) = split_path($m->{file_a});
5177         $pbat = $self->ensure_path($dir);
5178         $self->delete_entry($m->{file_a}, $pbat);
5181 sub M {
5182         my ($self, $m) = @_;
5183         my ($dir, $file) = split_path($m->{file_b});
5184         my $pbat = $self->ensure_path($dir);
5185         my $fbat = $self->open_file($self->repo_path($m->{file_b}),
5186                                 $pbat,$self->{r},$self->{pool});
5187         print "\t$m->{chg}\t$m->{file_b}\n" unless $::_q;
5188         $self->chg_file($fbat, $m);
5189         $self->close_file($fbat,undef,$self->{pool});
5192 sub T { shift->M(@_) }
5194 sub change_file_prop {
5195         my ($self, $fbat, $pname, $pval) = @_;
5196         $self->SUPER::change_file_prop($fbat, $pname, $pval, $self->{pool});
5199 sub change_dir_prop {
5200         my ($self, $pbat, $pname, $pval) = @_;
5201         $self->SUPER::change_dir_prop($pbat, $pname, $pval, $self->{pool});
5204 sub _chg_file_get_blob ($$$$) {
5205         my ($self, $fbat, $m, $which) = @_;
5206         my $fh = $::_repository->temp_acquire("git_blob_$which");
5207         if ($m->{"mode_$which"} =~ /^120/) {
5208                 print $fh 'link ' or croak $!;
5209                 $self->change_file_prop($fbat,'svn:special','*');
5210         } elsif ($m->{mode_a} =~ /^120/ && $m->{"mode_$which"} !~ /^120/) {
5211                 $self->change_file_prop($fbat,'svn:special',undef);
5212         }
5213         my $blob = $m->{"sha1_$which"};
5214         return ($fh,) if ($blob =~ /^0{40}$/);
5215         my $size = $::_repository->cat_blob($blob, $fh);
5216         croak "Failed to read object $blob" if ($size < 0);
5217         $fh->flush == 0 or croak $!;
5218         seek $fh, 0, 0 or croak $!;
5220         my $exp = ::md5sum($fh);
5221         seek $fh, 0, 0 or croak $!;
5222         return ($fh, $exp);
5225 sub chg_file {
5226         my ($self, $fbat, $m) = @_;
5227         if ($m->{mode_b} =~ /755$/ && $m->{mode_a} !~ /755$/) {
5228                 $self->change_file_prop($fbat,'svn:executable','*');
5229         } elsif ($m->{mode_b} !~ /755$/ && $m->{mode_a} =~ /755$/) {
5230                 $self->change_file_prop($fbat,'svn:executable',undef);
5231         }
5232         my ($fh_a, $exp_a) = _chg_file_get_blob $self, $fbat, $m, 'a';
5233         my ($fh_b, $exp_b) = _chg_file_get_blob $self, $fbat, $m, 'b';
5234         my $pool = SVN::Pool->new;
5235         my $atd = $self->apply_textdelta($fbat, $exp_a, $pool);
5236         if (-s $fh_a) {
5237                 my $txstream = SVN::TxDelta::new ($fh_a, $fh_b, $pool);
5238                 my $res = SVN::TxDelta::send_txstream($txstream, @$atd, $pool);
5239                 if (defined $res) {
5240                         die "Unexpected result from send_txstream: $res\n",
5241                             "(SVN::Core::VERSION: $SVN::Core::VERSION)\n";
5242                 }
5243         } else {
5244                 my $got = SVN::TxDelta::send_stream($fh_b, @$atd, $pool);
5245                 die "Checksum mismatch\nexpected: $exp_b\ngot: $got\n"
5246                     if ($got ne $exp_b);
5247         }
5248         Git::temp_release($fh_b, 1);
5249         Git::temp_release($fh_a, 1);
5250         $pool->clear;
5253 sub D {
5254         my ($self, $m) = @_;
5255         my ($dir, $file) = split_path($m->{file_b});
5256         my $pbat = $self->ensure_path($dir);
5257         print "\tD\t$m->{file_b}\n" unless $::_q;
5258         $self->delete_entry($m->{file_b}, $pbat);
5261 sub close_edit {
5262         my ($self) = @_;
5263         my ($p,$bat) = ($self->{pool}, $self->{bat});
5264         foreach (sort { $b =~ tr#/#/# <=> $a =~ tr#/#/# } keys %$bat) {
5265                 next if $_ eq '';
5266                 $self->close_directory($bat->{$_}, $p);
5267         }
5268         $self->close_directory($bat->{''}, $p);
5269         $self->SUPER::close_edit($p);
5270         $p->clear;
5273 sub abort_edit {
5274         my ($self) = @_;
5275         $self->SUPER::abort_edit($self->{pool});
5278 sub DESTROY {
5279         my $self = shift;
5280         $self->SUPER::DESTROY(@_);
5281         $self->{pool}->clear;
5284 # this drives the editor
5285 sub apply_diff {
5286         my ($self) = @_;
5287         my $mods = $self->{mods};
5288         my %o = ( D => 1, R => 0, C => -1, A => 3, M => 3, T => 3 );
5289         foreach my $m (sort { $o{$a->{chg}} <=> $o{$b->{chg}} } @$mods) {
5290                 my $f = $m->{chg};
5291                 if (defined $o{$f}) {
5292                         $self->$f($m);
5293                 } else {
5294                         fatal("Invalid change type: $f");
5295                 }
5296         }
5298         if (defined($self->{mergeinfo})) {
5299                 $self->change_dir_prop($self->{bat}{''}, "svn:mergeinfo",
5300                                        $self->{mergeinfo});
5301         }
5302         $self->rmdirs if $_rmdir;
5303         if (@$mods == 0) {
5304                 $self->abort_edit;
5305         } else {
5306                 $self->close_edit;
5307         }
5308         return scalar @$mods;
5311 package Git::SVN::Ra;
5312 use vars qw/@ISA $config_dir $_log_window_size/;
5313 use strict;
5314 use warnings;
5315 my ($ra_invalid, $can_do_switch, %ignored_err, $RA);
5317 BEGIN {
5318         # enforce temporary pool usage for some simple functions
5319         no strict 'refs';
5320         for my $f (qw/rev_proplist get_latest_revnum get_uuid get_repos_root
5321                       get_file/) {
5322                 my $SUPER = "SUPER::$f";
5323                 *$f = sub {
5324                         my $self = shift;
5325                         my $pool = SVN::Pool->new;
5326                         my @ret = $self->$SUPER(@_,$pool);
5327                         $pool->clear;
5328                         wantarray ? @ret : $ret[0];
5329                 };
5330         }
5333 sub _auth_providers () {
5334         [
5335           SVN::Client::get_simple_provider(),
5336           SVN::Client::get_ssl_server_trust_file_provider(),
5337           SVN::Client::get_simple_prompt_provider(
5338             \&Git::SVN::Prompt::simple, 2),
5339           SVN::Client::get_ssl_client_cert_file_provider(),
5340           SVN::Client::get_ssl_client_cert_prompt_provider(
5341             \&Git::SVN::Prompt::ssl_client_cert, 2),
5342           SVN::Client::get_ssl_client_cert_pw_file_provider(),
5343           SVN::Client::get_ssl_client_cert_pw_prompt_provider(
5344             \&Git::SVN::Prompt::ssl_client_cert_pw, 2),
5345           SVN::Client::get_username_provider(),
5346           SVN::Client::get_ssl_server_trust_prompt_provider(
5347             \&Git::SVN::Prompt::ssl_server_trust),
5348           SVN::Client::get_username_prompt_provider(
5349             \&Git::SVN::Prompt::username, 2)
5350         ]
5353 sub escape_uri_only {
5354         my ($uri) = @_;
5355         my @tmp;
5356         foreach (split m{/}, $uri) {
5357                 s/([^~\w.%+-]|%(?![a-fA-F0-9]{2}))/sprintf("%%%02X",ord($1))/eg;
5358                 push @tmp, $_;
5359         }
5360         join('/', @tmp);
5363 sub escape_url {
5364         my ($url) = @_;
5365         if ($url =~ m#^(https?)://([^/]+)(.*)$#) {
5366                 my ($scheme, $domain, $uri) = ($1, $2, escape_uri_only($3));
5367                 $url = "$scheme://$domain$uri";
5368         }
5369         $url;
5372 sub new {
5373         my ($class, $url) = @_;
5374         $url =~ s!/+$!!;
5375         return $RA if ($RA && $RA->{url} eq $url);
5377         ::_req_svn();
5379         SVN::_Core::svn_config_ensure($config_dir, undef);
5380         my ($baton, $callbacks) = SVN::Core::auth_open_helper(_auth_providers);
5381         my $config = SVN::Core::config_get_config($config_dir);
5382         $RA = undef;
5383         my $dont_store_passwords = 1;
5384         my $conf_t = ${$config}{'config'};
5385         {
5386                 no warnings 'once';
5387                 # The usage of $SVN::_Core::SVN_CONFIG_* variables
5388                 # produces warnings that variables are used only once.
5389                 # I had not found the better way to shut them up, so
5390                 # the warnings of type 'once' are disabled in this block.
5391                 if (SVN::_Core::svn_config_get_bool($conf_t,
5392                     $SVN::_Core::SVN_CONFIG_SECTION_AUTH,
5393                     $SVN::_Core::SVN_CONFIG_OPTION_STORE_PASSWORDS,
5394                     1) == 0) {
5395                         SVN::_Core::svn_auth_set_parameter($baton,
5396                             $SVN::_Core::SVN_AUTH_PARAM_DONT_STORE_PASSWORDS,
5397                             bless (\$dont_store_passwords, "_p_void"));
5398                 }
5399                 if (SVN::_Core::svn_config_get_bool($conf_t,
5400                     $SVN::_Core::SVN_CONFIG_SECTION_AUTH,
5401                     $SVN::_Core::SVN_CONFIG_OPTION_STORE_AUTH_CREDS,
5402                     1) == 0) {
5403                         $Git::SVN::Prompt::_no_auth_cache = 1;
5404                 }
5405         } # no warnings 'once'
5406         my $self = SVN::Ra->new(url => escape_url($url), auth => $baton,
5407                               config => $config,
5408                               pool => SVN::Pool->new,
5409                               auth_provider_callbacks => $callbacks);
5410         $self->{url} = $url;
5411         $self->{svn_path} = $url;
5412         $self->{repos_root} = $self->get_repos_root;
5413         $self->{svn_path} =~ s#^\Q$self->{repos_root}\E(/|$)##;
5414         $self->{cache} = { check_path => { r => 0, data => {} },
5415                            get_dir => { r => 0, data => {} } };
5416         $RA = bless $self, $class;
5419 sub check_path {
5420         my ($self, $path, $r) = @_;
5421         my $cache = $self->{cache}->{check_path};
5422         if ($r == $cache->{r} && exists $cache->{data}->{$path}) {
5423                 return $cache->{data}->{$path};
5424         }
5425         my $pool = SVN::Pool->new;
5426         my $t = $self->SUPER::check_path($path, $r, $pool);
5427         $pool->clear;
5428         if ($r != $cache->{r}) {
5429                 %{$cache->{data}} = ();
5430                 $cache->{r} = $r;
5431         }
5432         $cache->{data}->{$path} = $t;
5435 sub get_dir {
5436         my ($self, $dir, $r) = @_;
5437         my $cache = $self->{cache}->{get_dir};
5438         if ($r == $cache->{r}) {
5439                 if (my $x = $cache->{data}->{$dir}) {
5440                         return wantarray ? @$x : $x->[0];
5441                 }
5442         }
5443         my $pool = SVN::Pool->new;
5444         my ($d, undef, $props) = $self->SUPER::get_dir($dir, $r, $pool);
5445         my %dirents = map { $_ => { kind => $d->{$_}->kind } } keys %$d;
5446         $pool->clear;
5447         if ($r != $cache->{r}) {
5448                 %{$cache->{data}} = ();
5449                 $cache->{r} = $r;
5450         }
5451         $cache->{data}->{$dir} = [ \%dirents, $r, $props ];
5452         wantarray ? (\%dirents, $r, $props) : \%dirents;
5455 sub DESTROY {
5456         # do not call the real DESTROY since we store ourselves in $RA
5459 # get_log(paths, start, end, limit,
5460 #         discover_changed_paths, strict_node_history, receiver)
5461 sub get_log {
5462         my ($self, @args) = @_;
5463         my $pool = SVN::Pool->new;
5465         # svn_log_changed_path_t objects passed to get_log are likely to be
5466         # overwritten even if only the refs are copied to an external variable,
5467         # so we should dup the structures in their entirety.  Using an
5468         # externally passed pool (instead of our temporary and quickly cleared
5469         # pool in Git::SVN::Ra) does not help matters at all...
5470         my $receiver = pop @args;
5471         my $prefix = "/".$self->{svn_path};
5472         $prefix =~ s#/+($)##;
5473         my $prefix_regex = qr#^\Q$prefix\E#;
5474         push(@args, sub {
5475                 my ($paths) = $_[0];
5476                 return &$receiver(@_) unless $paths;
5477                 $_[0] = ();
5478                 foreach my $p (keys %$paths) {
5479                         my $i = $paths->{$p};
5480                         # Make path relative to our url, not repos_root
5481                         $p =~ s/$prefix_regex//;
5482                         my %s = map { $_ => $i->$_; }
5483                                 qw/copyfrom_path copyfrom_rev action/;
5484                         if ($s{'copyfrom_path'}) {
5485                                 $s{'copyfrom_path'} =~ s/$prefix_regex//;
5486                         }
5487                         $_[0]{$p} = \%s;
5488                 }
5489                 &$receiver(@_);
5490         });
5493         # the limit parameter was not supported in SVN 1.1.x, so we
5494         # drop it.  Therefore, the receiver callback passed to it
5495         # is made aware of this limitation by being wrapped if
5496         # the limit passed to is being wrapped.
5497         if ($SVN::Core::VERSION le '1.2.0') {
5498                 my $limit = splice(@args, 3, 1);
5499                 if ($limit > 0) {
5500                         my $receiver = pop @args;
5501                         push(@args, sub { &$receiver(@_) if (--$limit >= 0) });
5502                 }
5503         }
5504         my $ret = $self->SUPER::get_log(@args, $pool);
5505         $pool->clear;
5506         $ret;
5509 sub trees_match {
5510         my ($self, $url1, $rev1, $url2, $rev2) = @_;
5511         my $ctx = SVN::Client->new(auth => _auth_providers);
5512         my $out = IO::File->new_tmpfile;
5514         # older SVN (1.1.x) doesn't take $pool as the last parameter for
5515         # $ctx->diff(), so we'll create a default one
5516         my $pool = SVN::Pool->new_default_sub;
5518         $ra_invalid = 1; # this will open a new SVN::Ra connection to $url1
5519         $ctx->diff([], $url1, $rev1, $url2, $rev2, 1, 1, 0, $out, $out);
5520         $out->flush;
5521         my $ret = (($out->stat)[7] == 0);
5522         close $out or croak $!;
5524         $ret;
5527 sub get_commit_editor {
5528         my ($self, $log, $cb, $pool) = @_;
5529         my @lock = $SVN::Core::VERSION ge '1.2.0' ? (undef, 0) : ();
5530         $self->SUPER::get_commit_editor($log, $cb, @lock, $pool);
5533 sub gs_do_update {
5534         my ($self, $rev_a, $rev_b, $gs, $editor) = @_;
5535         my $new = ($rev_a == $rev_b);
5536         my $path = $gs->{path};
5538         if ($new && -e $gs->{index}) {
5539                 unlink $gs->{index} or die
5540                   "Couldn't unlink index: $gs->{index}: $!\n";
5541         }
5542         my $pool = SVN::Pool->new;
5543         $editor->set_path_strip($path);
5544         my (@pc) = split m#/#, $path;
5545         my $reporter = $self->do_update($rev_b, (@pc ? shift @pc : ''),
5546                                         1, $editor, $pool);
5547         my @lock = $SVN::Core::VERSION ge '1.2.0' ? (undef) : ();
5549         # Since we can't rely on svn_ra_reparent being available, we'll
5550         # just have to do some magic with set_path to make it so
5551         # we only want a partial path.
5552         my $sp = '';
5553         my $final = join('/', @pc);
5554         while (@pc) {
5555                 $reporter->set_path($sp, $rev_b, 0, @lock, $pool);
5556                 $sp .= '/' if length $sp;
5557                 $sp .= shift @pc;
5558         }
5559         die "BUG: '$sp' != '$final'\n" if ($sp ne $final);
5561         $reporter->set_path($sp, $rev_a, $new, @lock, $pool);
5563         $reporter->finish_report($pool);
5564         $pool->clear;
5565         $editor->{git_commit_ok};
5568 # this requires SVN 1.4.3 or later (do_switch didn't work before 1.4.3, and
5569 # svn_ra_reparent didn't work before 1.4)
5570 sub gs_do_switch {
5571         my ($self, $rev_a, $rev_b, $gs, $url_b, $editor) = @_;
5572         my $path = $gs->{path};
5573         my $pool = SVN::Pool->new;
5575         my $full_url = $self->{url};
5576         my $old_url = $full_url;
5577         $full_url .= '/' . $path if length $path;
5578         my ($ra, $reparented);
5580         if ($old_url =~ m#^svn(\+ssh)?://# ||
5581             ($full_url =~ m#^https?://# &&
5582              escape_url($full_url) ne $full_url)) {
5583                 $_[0] = undef;
5584                 $self = undef;
5585                 $RA = undef;
5586                 $ra = Git::SVN::Ra->new($full_url);
5587                 $ra_invalid = 1;
5588         } elsif ($old_url ne $full_url) {
5589                 SVN::_Ra::svn_ra_reparent($self->{session}, $full_url, $pool);
5590                 $self->{url} = $full_url;
5591                 $reparented = 1;
5592         }
5594         $ra ||= $self;
5595         $url_b = escape_url($url_b);
5596         my $reporter = $ra->do_switch($rev_b, '', 1, $url_b, $editor, $pool);
5597         my @lock = $SVN::Core::VERSION ge '1.2.0' ? (undef) : ();
5598         $reporter->set_path('', $rev_a, 0, @lock, $pool);
5599         $reporter->finish_report($pool);
5601         if ($reparented) {
5602                 SVN::_Ra::svn_ra_reparent($self->{session}, $old_url, $pool);
5603                 $self->{url} = $old_url;
5604         }
5606         $pool->clear;
5607         $editor->{git_commit_ok};
5610 sub longest_common_path {
5611         my ($gsv, $globs) = @_;
5612         my %common;
5613         my $common_max = scalar @$gsv;
5615         foreach my $gs (@$gsv) {
5616                 my @tmp = split m#/#, $gs->{path};
5617                 my $p = '';
5618                 foreach (@tmp) {
5619                         $p .= length($p) ? "/$_" : $_;
5620                         $common{$p} ||= 0;
5621                         $common{$p}++;
5622                 }
5623         }
5624         $globs ||= [];
5625         $common_max += scalar @$globs;
5626         foreach my $glob (@$globs) {
5627                 my @tmp = split m#/#, $glob->{path}->{left};
5628                 my $p = '';
5629                 foreach (@tmp) {
5630                         $p .= length($p) ? "/$_" : $_;
5631                         $common{$p} ||= 0;
5632                         $common{$p}++;
5633                 }
5634         }
5636         my $longest_path = '';
5637         foreach (sort {length $b <=> length $a} keys %common) {
5638                 if ($common{$_} == $common_max) {
5639                         $longest_path = $_;
5640                         last;
5641                 }
5642         }
5643         $longest_path;
5646 sub gs_fetch_loop_common {
5647         my ($self, $base, $head, $gsv, $globs) = @_;
5648         return if ($base > $head);
5649         my $inc = $_log_window_size;
5650         my ($min, $max) = ($base, $head < $base + $inc ? $head : $base + $inc);
5651         my $longest_path = longest_common_path($gsv, $globs);
5652         my $ra_url = $self->{url};
5653         my $find_trailing_edge;
5654         while (1) {
5655                 my %revs;
5656                 my $err;
5657                 my $err_handler = $SVN::Error::handler;
5658                 $SVN::Error::handler = sub {
5659                         ($err) = @_;
5660                         skip_unknown_revs($err);
5661                 };
5662                 sub _cb {
5663                         my ($paths, $r, $author, $date, $log) = @_;
5664                         [ $paths,
5665                           { author => $author, date => $date, log => $log } ];
5666                 }
5667                 $self->get_log([$longest_path], $min, $max, 0, 1, 1,
5668                                sub { $revs{$_[1]} = _cb(@_) });
5669                 if ($err) {
5670                         print "Checked through r$max\r";
5671                 } else {
5672                         $find_trailing_edge = 1;
5673                 }
5674                 if ($err and $find_trailing_edge) {
5675                         print STDERR "Path '$longest_path' ",
5676                                      "was probably deleted:\n",
5677                                      $err->expanded_message,
5678                                      "\nWill attempt to follow ",
5679                                      "revisions r$min .. r$max ",
5680                                      "committed before the deletion\n";
5681                         my $hi = $max;
5682                         while (--$hi >= $min) {
5683                                 my $ok;
5684                                 $self->get_log([$longest_path], $min, $hi,
5685                                                0, 1, 1, sub {
5686                                                $ok = $_[1];
5687                                                $revs{$_[1]} = _cb(@_) });
5688                                 if ($ok) {
5689                                         print STDERR "r$min .. r$ok OK\n";
5690                                         last;
5691                                 }
5692                         }
5693                         $find_trailing_edge = 0;
5694                 }
5695                 $SVN::Error::handler = $err_handler;
5697                 my %exists = map { $_->{path} => $_ } @$gsv;
5698                 foreach my $r (sort {$a <=> $b} keys %revs) {
5699                         my ($paths, $logged) = @{$revs{$r}};
5701                         foreach my $gs ($self->match_globs(\%exists, $paths,
5702                                                            $globs, $r)) {
5703                                 if ($gs->rev_map_max >= $r) {
5704                                         next;
5705                                 }
5706                                 next unless $gs->match_paths($paths, $r);
5707                                 $gs->{logged_rev_props} = $logged;
5708                                 if (my $last_commit = $gs->last_commit) {
5709                                         $gs->assert_index_clean($last_commit);
5710                                 }
5711                                 my $log_entry = $gs->do_fetch($paths, $r);
5712                                 if ($log_entry) {
5713                                         $gs->do_git_commit($log_entry);
5714                                 }
5715                                 $INDEX_FILES{$gs->{index}} = 1;
5716                         }
5717                         foreach my $g (@$globs) {
5718                                 my $k = "svn-remote.$g->{remote}." .
5719                                         "$g->{t}-maxRev";
5720                                 Git::SVN::tmp_config($k, $r);
5721                         }
5722                         if ($ra_invalid) {
5723                                 $_[0] = undef;
5724                                 $self = undef;
5725                                 $RA = undef;
5726                                 $self = Git::SVN::Ra->new($ra_url);
5727                                 $ra_invalid = undef;
5728                         }
5729                 }
5730                 # pre-fill the .rev_db since it'll eventually get filled in
5731                 # with '0' x40 if something new gets committed
5732                 foreach my $gs (@$gsv) {
5733                         next if $gs->rev_map_max >= $max;
5734                         next if defined $gs->rev_map_get($max);
5735                         $gs->rev_map_set($max, 0 x40);
5736                 }
5737                 foreach my $g (@$globs) {
5738                         my $k = "svn-remote.$g->{remote}.$g->{t}-maxRev";
5739                         Git::SVN::tmp_config($k, $max);
5740                 }
5741                 last if $max >= $head;
5742                 $min = $max + 1;
5743                 $max += $inc;
5744                 $max = $head if ($max > $head);
5745         }
5746         Git::SVN::gc();
5749 sub get_dir_globbed {
5750         my ($self, $left, $depth, $r) = @_;
5752         my @x = eval { $self->get_dir($left, $r) };
5753         return unless scalar @x == 3;
5754         my $dirents = $x[0];
5755         my @finalents;
5756         foreach my $de (keys %$dirents) {
5757                 next if $dirents->{$de}->{kind} != $SVN::Node::dir;
5758                 if ($depth > 1) {
5759                         my @args = ("$left/$de", $depth - 1, $r);
5760                         foreach my $dir ($self->get_dir_globbed(@args)) {
5761                                 push @finalents, "$de/$dir";
5762                         }
5763                 } else {
5764                         push @finalents, $de;
5765                 }
5766         }
5767         @finalents;
5770 sub match_globs {
5771         my ($self, $exists, $paths, $globs, $r) = @_;
5773         sub get_dir_check {
5774                 my ($self, $exists, $g, $r) = @_;
5776                 my @dirs = $self->get_dir_globbed($g->{path}->{left},
5777                                                   $g->{path}->{depth},
5778                                                   $r);
5780                 foreach my $de (@dirs) {
5781                         my $p = $g->{path}->full_path($de);
5782                         next if $exists->{$p};
5783                         next if (length $g->{path}->{right} &&
5784                                  ($self->check_path($p, $r) !=
5785                                   $SVN::Node::dir));
5786                         next unless $p =~ /$g->{path}->{regex}/;
5787                         $exists->{$p} = Git::SVN->init($self->{url}, $p, undef,
5788                                          $g->{ref}->full_path($de), 1);
5789                 }
5790         }
5791         foreach my $g (@$globs) {
5792                 if (my $path = $paths->{"/$g->{path}->{left}"}) {
5793                         if ($path->{action} =~ /^[AR]$/) {
5794                                 get_dir_check($self, $exists, $g, $r);
5795                         }
5796                 }
5797                 foreach (keys %$paths) {
5798                         if (/$g->{path}->{left_regex}/ &&
5799                             !/$g->{path}->{regex}/) {
5800                                 next if $paths->{$_}->{action} !~ /^[AR]$/;
5801                                 get_dir_check($self, $exists, $g, $r);
5802                         }
5803                         next unless /$g->{path}->{regex}/;
5804                         my $p = $1;
5805                         my $pathname = $g->{path}->full_path($p);
5806                         next if $exists->{$pathname};
5807                         next if ($self->check_path($pathname, $r) !=
5808                                  $SVN::Node::dir);
5809                         $exists->{$pathname} = Git::SVN->init(
5810                                               $self->{url}, $pathname, undef,
5811                                               $g->{ref}->full_path($p), 1);
5812                 }
5813                 my $c = '';
5814                 foreach (split m#/#, $g->{path}->{left}) {
5815                         $c .= "/$_";
5816                         next unless ($paths->{$c} &&
5817                                      ($paths->{$c}->{action} =~ /^[AR]$/));
5818                         get_dir_check($self, $exists, $g, $r);
5819                 }
5820         }
5821         values %$exists;
5824 sub minimize_url {
5825         my ($self) = @_;
5826         return $self->{url} if ($self->{url} eq $self->{repos_root});
5827         my $url = $self->{repos_root};
5828         my @components = split(m!/!, $self->{svn_path});
5829         my $c = '';
5830         do {
5831                 $url .= "/$c" if length $c;
5832                 eval {
5833                         my $ra = (ref $self)->new($url);
5834                         my $latest = $ra->get_latest_revnum;
5835                         $ra->get_log("", $latest, 0, 1, 0, 1, sub {});
5836                 };
5837         } while ($@ && ($c = shift @components));
5838         $url;
5841 sub can_do_switch {
5842         my $self = shift;
5843         unless (defined $can_do_switch) {
5844                 my $pool = SVN::Pool->new;
5845                 my $rep = eval {
5846                         $self->do_switch(1, '', 0, $self->{url},
5847                                          SVN::Delta::Editor->new, $pool);
5848                 };
5849                 if ($@) {
5850                         $can_do_switch = 0;
5851                 } else {
5852                         $rep->abort_report($pool);
5853                         $can_do_switch = 1;
5854                 }
5855                 $pool->clear;
5856         }
5857         $can_do_switch;
5860 sub skip_unknown_revs {
5861         my ($err) = @_;
5862         my $errno = $err->apr_err();
5863         # Maybe the branch we're tracking didn't
5864         # exist when the repo started, so it's
5865         # not an error if it doesn't, just continue
5866         #
5867         # Wonderfully consistent library, eh?
5868         # 160013 - svn:// and file://
5869         # 175002 - http(s)://
5870         # 175007 - http(s):// (this repo required authorization, too...)
5871         #   More codes may be discovered later...
5872         if ($errno == 175007 || $errno == 175002 || $errno == 160013) {
5873                 my $err_key = $err->expanded_message;
5874                 # revision numbers change every time, filter them out
5875                 $err_key =~ s/\d+/\0/g;
5876                 $err_key = "$errno\0$err_key";
5877                 unless ($ignored_err{$err_key}) {
5878                         warn "W: Ignoring error from SVN, path probably ",
5879                              "does not exist: ($errno): ",
5880                              $err->expanded_message,"\n";
5881                         warn "W: Do not be alarmed at the above message ",
5882                              "git-svn is just searching aggressively for ",
5883                              "old history.\n",
5884                              "This may take a while on large repositories\n";
5885                         $ignored_err{$err_key} = 1;
5886                 }
5887                 return;
5888         }
5889         die "Error from SVN, ($errno): ", $err->expanded_message,"\n";
5892 package Git::SVN::Log;
5893 use strict;
5894 use warnings;
5895 use POSIX qw/strftime/;
5896 use Time::Local;
5897 use constant commit_log_separator => ('-' x 72) . "\n";
5898 use vars qw/$TZ $limit $color $pager $non_recursive $verbose $oneline
5899             %rusers $show_commit $incremental/;
5900 my $l_fmt;
5902 sub cmt_showable {
5903         my ($c) = @_;
5904         return 1 if defined $c->{r};
5906         # big commit message got truncated by the 16k pretty buffer in rev-list
5907         if ($c->{l} && $c->{l}->[-1] eq "...\n" &&
5908                                 $c->{a_raw} =~ /\@([a-f\d\-]+)>$/) {
5909                 @{$c->{l}} = ();
5910                 my @log = command(qw/cat-file commit/, $c->{c});
5912                 # shift off the headers
5913                 shift @log while ($log[0] ne '');
5914                 shift @log;
5916                 # TODO: make $c->{l} not have a trailing newline in the future
5917                 @{$c->{l}} = map { "$_\n" } grep !/^git-svn-id: /, @log;
5919                 (undef, $c->{r}, undef) = ::extract_metadata(
5920                                 (grep(/^git-svn-id: /, @log))[-1]);
5921         }
5922         return defined $c->{r};
5925 sub log_use_color {
5926         return $color || Git->repository->get_colorbool('color.diff');
5929 sub git_svn_log_cmd {
5930         my ($r_min, $r_max, @args) = @_;
5931         my $head = 'HEAD';
5932         my (@files, @log_opts);
5933         foreach my $x (@args) {
5934                 if ($x eq '--' || @files) {
5935                         push @files, $x;
5936                 } else {
5937                         if (::verify_ref("$x^0")) {
5938                                 $head = $x;
5939                         } else {
5940                                 push @log_opts, $x;
5941                         }
5942                 }
5943         }
5945         my ($url, $rev, $uuid, $gs) = ::working_head_info($head);
5946         $gs ||= Git::SVN->_new;
5947         my @cmd = (qw/log --abbrev-commit --pretty=raw --default/,
5948                    $gs->refname);
5949         push @cmd, '-r' unless $non_recursive;
5950         push @cmd, qw/--raw --name-status/ if $verbose;
5951         push @cmd, '--color' if log_use_color();
5952         push @cmd, @log_opts;
5953         if (defined $r_max && $r_max == $r_min) {
5954                 push @cmd, '--max-count=1';
5955                 if (my $c = $gs->rev_map_get($r_max)) {
5956                         push @cmd, $c;
5957                 }
5958         } elsif (defined $r_max) {
5959                 if ($r_max < $r_min) {
5960                         ($r_min, $r_max) = ($r_max, $r_min);
5961                 }
5962                 my (undef, $c_max) = $gs->find_rev_before($r_max, 1, $r_min);
5963                 my (undef, $c_min) = $gs->find_rev_after($r_min, 1, $r_max);
5964                 # If there are no commits in the range, both $c_max and $c_min
5965                 # will be undefined.  If there is at least 1 commit in the
5966                 # range, both will be defined.
5967                 return () if !defined $c_min || !defined $c_max;
5968                 if ($c_min eq $c_max) {
5969                         push @cmd, '--max-count=1', $c_min;
5970                 } else {
5971                         push @cmd, '--boundary', "$c_min..$c_max";
5972                 }
5973         }
5974         return (@cmd, @files);
5977 # adapted from pager.c
5978 sub config_pager {
5979         if (! -t *STDOUT) {
5980                 $ENV{GIT_PAGER_IN_USE} = 'false';
5981                 $pager = undef;
5982                 return;
5983         }
5984         chomp($pager = command_oneline(qw(var GIT_PAGER)));
5985         if ($pager eq 'cat') {
5986                 $pager = undef;
5987         }
5988         $ENV{GIT_PAGER_IN_USE} = defined($pager);
5991 sub run_pager {
5992         return unless defined $pager;
5993         pipe my ($rfd, $wfd) or return;
5994         defined(my $pid = fork) or ::fatal "Can't fork: $!";
5995         if (!$pid) {
5996                 open STDOUT, '>&', $wfd or
5997                                      ::fatal "Can't redirect to stdout: $!";
5998                 return;
5999         }
6000         open STDIN, '<&', $rfd or ::fatal "Can't redirect stdin: $!";
6001         $ENV{LESS} ||= 'FRSX';
6002         exec $pager or ::fatal "Can't run pager: $! ($pager)";
6005 sub format_svn_date {
6006         # some systmes don't handle or mishandle %z, so be creative.
6007         my $t = shift || time;
6008         my $gm = timelocal(gmtime($t));
6009         my $sign = qw( + + - )[ $t <=> $gm ];
6010         my $gmoff = sprintf("%s%02d%02d", $sign, (gmtime(abs($t - $gm)))[2,1]);
6011         return strftime("%Y-%m-%d %H:%M:%S $gmoff (%a, %d %b %Y)", localtime($t));
6014 sub parse_git_date {
6015         my ($t, $tz) = @_;
6016         # Date::Parse isn't in the standard Perl distro :(
6017         if ($tz =~ s/^\+//) {
6018                 $t += tz_to_s_offset($tz);
6019         } elsif ($tz =~ s/^\-//) {
6020                 $t -= tz_to_s_offset($tz);
6021         }
6022         return $t;
6025 sub set_local_timezone {
6026         if (defined $TZ) {
6027                 $ENV{TZ} = $TZ;
6028         } else {
6029                 delete $ENV{TZ};
6030         }
6033 sub tz_to_s_offset {
6034         my ($tz) = @_;
6035         $tz =~ s/(\d\d)$//;
6036         return ($1 * 60) + ($tz * 3600);
6039 sub get_author_info {
6040         my ($dest, $author, $t, $tz) = @_;
6041         $author =~ s/(?:^\s*|\s*$)//g;
6042         $dest->{a_raw} = $author;
6043         my $au;
6044         if ($::_authors) {
6045                 $au = $rusers{$author} || undef;
6046         }
6047         if (!$au) {
6048                 ($au) = ($author =~ /<([^>]+)\@[^>]+>$/);
6049         }
6050         $dest->{t} = $t;
6051         $dest->{tz} = $tz;
6052         $dest->{a} = $au;
6053         $dest->{t_utc} = parse_git_date($t, $tz);
6056 sub process_commit {
6057         my ($c, $r_min, $r_max, $defer) = @_;
6058         if (defined $r_min && defined $r_max) {
6059                 if ($r_min == $c->{r} && $r_min == $r_max) {
6060                         show_commit($c);
6061                         return 0;
6062                 }
6063                 return 1 if $r_min == $r_max;
6064                 if ($r_min < $r_max) {
6065                         # we need to reverse the print order
6066                         return 0 if (defined $limit && --$limit < 0);
6067                         push @$defer, $c;
6068                         return 1;
6069                 }
6070                 if ($r_min != $r_max) {
6071                         return 1 if ($r_min < $c->{r});
6072                         return 1 if ($r_max > $c->{r});
6073                 }
6074         }
6075         return 0 if (defined $limit && --$limit < 0);
6076         show_commit($c);
6077         return 1;
6080 sub show_commit {
6081         my $c = shift;
6082         if ($oneline) {
6083                 my $x = "\n";
6084                 if (my $l = $c->{l}) {
6085                         while ($l->[0] =~ /^\s*$/) { shift @$l }
6086                         $x = $l->[0];
6087                 }
6088                 $l_fmt ||= 'A' . length($c->{r});
6089                 print 'r',pack($l_fmt, $c->{r}),' | ';
6090                 print "$c->{c} | " if $show_commit;
6091                 print $x;
6092         } else {
6093                 show_commit_normal($c);
6094         }
6097 sub show_commit_changed_paths {
6098         my ($c) = @_;
6099         return unless $c->{changed};
6100         print "Changed paths:\n", @{$c->{changed}};
6103 sub show_commit_normal {
6104         my ($c) = @_;
6105         print commit_log_separator, "r$c->{r} | ";
6106         print "$c->{c} | " if $show_commit;
6107         print "$c->{a} | ", format_svn_date($c->{t_utc}), ' | ';
6108         my $nr_line = 0;
6110         if (my $l = $c->{l}) {
6111                 while ($l->[$#$l] eq "\n" && $#$l > 0
6112                                           && $l->[($#$l - 1)] eq "\n") {
6113                         pop @$l;
6114                 }
6115                 $nr_line = scalar @$l;
6116                 if (!$nr_line) {
6117                         print "1 line\n\n\n";
6118                 } else {
6119                         if ($nr_line == 1) {
6120                                 $nr_line = '1 line';
6121                         } else {
6122                                 $nr_line .= ' lines';
6123                         }
6124                         print $nr_line, "\n";
6125                         show_commit_changed_paths($c);
6126                         print "\n";
6127                         print $_ foreach @$l;
6128                 }
6129         } else {
6130                 print "1 line\n";
6131                 show_commit_changed_paths($c);
6132                 print "\n";
6134         }
6135         foreach my $x (qw/raw stat diff/) {
6136                 if ($c->{$x}) {
6137                         print "\n";
6138                         print $_ foreach @{$c->{$x}}
6139                 }
6140         }
6143 sub cmd_show_log {
6144         my (@args) = @_;
6145         my ($r_min, $r_max);
6146         my $r_last = -1; # prevent dupes
6147         set_local_timezone();
6148         if (defined $::_revision) {
6149                 if ($::_revision =~ /^(\d+):(\d+)$/) {
6150                         ($r_min, $r_max) = ($1, $2);
6151                 } elsif ($::_revision =~ /^\d+$/) {
6152                         $r_min = $r_max = $::_revision;
6153                 } else {
6154                         ::fatal "-r$::_revision is not supported, use ",
6155                                 "standard 'git log' arguments instead";
6156                 }
6157         }
6159         config_pager();
6160         @args = git_svn_log_cmd($r_min, $r_max, @args);
6161         if (!@args) {
6162                 print commit_log_separator unless $incremental || $oneline;
6163                 return;
6164         }
6165         my $log = command_output_pipe(@args);
6166         run_pager();
6167         my (@k, $c, $d, $stat);
6168         my $esc_color = qr/(?:\033\[(?:(?:\d+;)*\d*)?m)*/;
6169         while (<$log>) {
6170                 if (/^${esc_color}commit (?:- )?($::sha1_short)/o) {
6171                         my $cmt = $1;
6172                         if ($c && cmt_showable($c) && $c->{r} != $r_last) {
6173                                 $r_last = $c->{r};
6174                                 process_commit($c, $r_min, $r_max, \@k) or
6175                                                                 goto out;
6176                         }
6177                         $d = undef;
6178                         $c = { c => $cmt };
6179                 } elsif (/^${esc_color}author (.+) (\d+) ([\-\+]?\d+)$/o) {
6180                         get_author_info($c, $1, $2, $3);
6181                 } elsif (/^${esc_color}(?:tree|parent|committer) /o) {
6182                         # ignore
6183                 } elsif (/^${esc_color}:\d{6} \d{6} $::sha1_short/o) {
6184                         push @{$c->{raw}}, $_;
6185                 } elsif (/^${esc_color}[ACRMDT]\t/) {
6186                         # we could add $SVN->{svn_path} here, but that requires
6187                         # remote access at the moment (repo_path_split)...
6188                         s#^(${esc_color})([ACRMDT])\t#$1   $2 #o;
6189                         push @{$c->{changed}}, $_;
6190                 } elsif (/^${esc_color}diff /o) {
6191                         $d = 1;
6192                         push @{$c->{diff}}, $_;
6193                 } elsif ($d) {
6194                         push @{$c->{diff}}, $_;
6195                 } elsif (/^\ .+\ \|\s*\d+\ $esc_color[\+\-]*
6196                           $esc_color*[\+\-]*$esc_color$/x) {
6197                         $stat = 1;
6198                         push @{$c->{stat}}, $_;
6199                 } elsif ($stat && /^ \d+ files changed, \d+ insertions/) {
6200                         push @{$c->{stat}}, $_;
6201                         $stat = undef;
6202                 } elsif (/^${esc_color}    (git-svn-id:.+)$/o) {
6203                         ($c->{url}, $c->{r}, undef) = ::extract_metadata($1);
6204                 } elsif (s/^${esc_color}    //o) {
6205                         push @{$c->{l}}, $_;
6206                 }
6207         }
6208         if ($c && defined $c->{r} && $c->{r} != $r_last) {
6209                 $r_last = $c->{r};
6210                 process_commit($c, $r_min, $r_max, \@k);
6211         }
6212         if (@k) {
6213                 ($r_min, $r_max) = ($r_max, $r_min);
6214                 process_commit($_, $r_min, $r_max) foreach reverse @k;
6215         }
6216 out:
6217         close $log;
6218         print commit_log_separator unless $incremental || $oneline;
6221 sub cmd_blame {
6222         my $path = pop;
6224         config_pager();
6225         run_pager();
6227         my ($fh, $ctx, $rev);
6229         if ($_git_format) {
6230                 ($fh, $ctx) = command_output_pipe('blame', @_, $path);
6231                 while (my $line = <$fh>) {
6232                         if ($line =~ /^\^?([[:xdigit:]]+)\s/) {
6233                                 # Uncommitted edits show up as a rev ID of
6234                                 # all zeros, which we can't look up with
6235                                 # cmt_metadata
6236                                 if ($1 !~ /^0+$/) {
6237                                         (undef, $rev, undef) =
6238                                                 ::cmt_metadata($1);
6239                                         $rev = '0' if (!$rev);
6240                                 } else {
6241                                         $rev = '0';
6242                                 }
6243                                 $rev = sprintf('%-10s', $rev);
6244                                 $line =~ s/^\^?[[:xdigit:]]+(\s)/$rev$1/;
6245                         }
6246                         print $line;
6247                 }
6248         } else {
6249                 ($fh, $ctx) = command_output_pipe('blame', '-p', @_, 'HEAD',
6250                                                   '--', $path);
6251                 my ($sha1);
6252                 my %authors;
6253                 my @buffer;
6254                 my %dsha; #distinct sha keys
6256                 while (my $line = <$fh>) {
6257                         push @buffer, $line;
6258                         if ($line =~ /^([[:xdigit:]]{40})\s\d+\s\d+/) {
6259                                 $dsha{$1} = 1;
6260                         }
6261                 }
6263                 my $s2r = ::cmt_sha2rev_batch([keys %dsha]);
6265                 foreach my $line (@buffer) {
6266                         if ($line =~ /^([[:xdigit:]]{40})\s\d+\s\d+/) {
6267                                 $rev = $s2r->{$1};
6268                                 $rev = '0' if (!$rev)
6269                         }
6270                         elsif ($line =~ /^author (.*)/) {
6271                                 $authors{$rev} = $1;
6272                                 $authors{$rev} =~ s/\s/_/g;
6273                         }
6274                         elsif ($line =~ /^\t(.*)$/) {
6275                                 printf("%6s %10s %s\n", $rev, $authors{$rev}, $1);
6276                         }
6277                 }
6278         }
6279         command_close_pipe($fh, $ctx);
6282 package Git::SVN::Migration;
6283 # these version numbers do NOT correspond to actual version numbers
6284 # of git nor git-svn.  They are just relative.
6286 # v0 layout: .git/$id/info/url, refs/heads/$id-HEAD
6288 # v1 layout: .git/$id/info/url, refs/remotes/$id
6290 # v2 layout: .git/svn/$id/info/url, refs/remotes/$id
6292 # v3 layout: .git/svn/$id, refs/remotes/$id
6293 #            - info/url may remain for backwards compatibility
6294 #            - this is what we migrate up to this layout automatically,
6295 #            - this will be used by git svn init on single branches
6296 # v3.1 layout (auto migrated):
6297 #            - .rev_db => .rev_db.$UUID, .rev_db will remain as a symlink
6298 #              for backwards compatibility
6300 # v4 layout: .git/svn/$repo_id/$id, refs/remotes/$repo_id/$id
6301 #            - this is only created for newly multi-init-ed
6302 #              repositories.  Similar in spirit to the
6303 #              --use-separate-remotes option in git-clone (now default)
6304 #            - we do not automatically migrate to this (following
6305 #              the example set by core git)
6307 # v5 layout: .rev_db.$UUID => .rev_map.$UUID
6308 #            - newer, more-efficient format that uses 24-bytes per record
6309 #              with no filler space.
6310 #            - use xxd -c24 < .rev_map.$UUID to view and debug
6311 #            - This is a one-way migration, repositories updated to the
6312 #              new format will not be able to use old git-svn without
6313 #              rebuilding the .rev_db.  Rebuilding the rev_db is not
6314 #              possible if noMetadata or useSvmProps are set; but should
6315 #              be no problem for users that use the (sensible) defaults.
6316 use strict;
6317 use warnings;
6318 use Carp qw/croak/;
6319 use File::Path qw/mkpath/;
6320 use File::Basename qw/dirname basename/;
6321 use vars qw/$_minimize/;
6323 sub migrate_from_v0 {
6324         my $git_dir = $ENV{GIT_DIR};
6325         return undef unless -d $git_dir;
6326         my ($fh, $ctx) = command_output_pipe(qw/rev-parse --symbolic --all/);
6327         my $migrated = 0;
6328         while (<$fh>) {
6329                 chomp;
6330                 my ($id, $orig_ref) = ($_, $_);
6331                 next unless $id =~ s#^refs/heads/(.+)-HEAD$#$1#;
6332                 next unless -f "$git_dir/$id/info/url";
6333                 my $new_ref = "refs/remotes/$id";
6334                 if (::verify_ref("$new_ref^0")) {
6335                         print STDERR "W: $orig_ref is probably an old ",
6336                                      "branch used by an ancient version of ",
6337                                      "git-svn.\n",
6338                                      "However, $new_ref also exists.\n",
6339                                      "We will not be able ",
6340                                      "to use this branch until this ",
6341                                      "ambiguity is resolved.\n";
6342                         next;
6343                 }
6344                 print STDERR "Migrating from v0 layout...\n" if !$migrated;
6345                 print STDERR "Renaming ref: $orig_ref => $new_ref\n";
6346                 command_noisy('update-ref', $new_ref, $orig_ref);
6347                 command_noisy('update-ref', '-d', $orig_ref, $orig_ref);
6348                 $migrated++;
6349         }
6350         command_close_pipe($fh, $ctx);
6351         print STDERR "Done migrating from v0 layout...\n" if $migrated;
6352         $migrated;
6355 sub migrate_from_v1 {
6356         my $git_dir = $ENV{GIT_DIR};
6357         my $migrated = 0;
6358         return $migrated unless -d $git_dir;
6359         my $svn_dir = "$git_dir/svn";
6361         # just in case somebody used 'svn' as their $id at some point...
6362         return $migrated if -d $svn_dir && ! -f "$svn_dir/info/url";
6364         print STDERR "Migrating from a git-svn v1 layout...\n";
6365         mkpath([$svn_dir]);
6366         print STDERR "Data from a previous version of git-svn exists, but\n\t",
6367                      "$svn_dir\n\t(required for this version ",
6368                      "($::VERSION) of git-svn) does not exist.\n";
6369         my ($fh, $ctx) = command_output_pipe(qw/rev-parse --symbolic --all/);
6370         while (<$fh>) {
6371                 my $x = $_;
6372                 next unless $x =~ s#^refs/remotes/##;
6373                 chomp $x;
6374                 next unless -f "$git_dir/$x/info/url";
6375                 my $u = eval { ::file_to_s("$git_dir/$x/info/url") };
6376                 next unless $u;
6377                 my $dn = dirname("$git_dir/svn/$x");
6378                 mkpath([$dn]) unless -d $dn;
6379                 if ($x eq 'svn') { # they used 'svn' as GIT_SVN_ID:
6380                         mkpath(["$git_dir/svn/svn"]);
6381                         print STDERR " - $git_dir/$x/info => ",
6382                                         "$git_dir/svn/$x/info\n";
6383                         rename "$git_dir/$x/info", "$git_dir/svn/$x/info" or
6384                                croak "$!: $x";
6385                         # don't worry too much about these, they probably
6386                         # don't exist with repos this old (save for index,
6387                         # and we can easily regenerate that)
6388                         foreach my $f (qw/unhandled.log index .rev_db/) {
6389                                 rename "$git_dir/$x/$f", "$git_dir/svn/$x/$f";
6390                         }
6391                 } else {
6392                         print STDERR " - $git_dir/$x => $git_dir/svn/$x\n";
6393                         rename "$git_dir/$x", "$git_dir/svn/$x" or
6394                                croak "$!: $x";
6395                 }
6396                 $migrated++;
6397         }
6398         command_close_pipe($fh, $ctx);
6399         print STDERR "Done migrating from a git-svn v1 layout\n";
6400         $migrated;
6403 sub read_old_urls {
6404         my ($l_map, $pfx, $path) = @_;
6405         my @dir;
6406         foreach (<$path/*>) {
6407                 if (-r "$_/info/url") {
6408                         $pfx .= '/' if $pfx && $pfx !~ m!/$!;
6409                         my $ref_id = $pfx . basename $_;
6410                         my $url = ::file_to_s("$_/info/url");
6411                         $l_map->{$ref_id} = $url;
6412                 } elsif (-d $_) {
6413                         push @dir, $_;
6414                 }
6415         }
6416         foreach (@dir) {
6417                 my $x = $_;
6418                 $x =~ s!^\Q$ENV{GIT_DIR}\E/svn/!!o;
6419                 read_old_urls($l_map, $x, $_);
6420         }
6423 sub migrate_from_v2 {
6424         my @cfg = command(qw/config -l/);
6425         return if grep /^svn-remote\..+\.url=/, @cfg;
6426         my %l_map;
6427         read_old_urls(\%l_map, '', "$ENV{GIT_DIR}/svn");
6428         my $migrated = 0;
6430         foreach my $ref_id (sort keys %l_map) {
6431                 eval { Git::SVN->init($l_map{$ref_id}, '', undef, $ref_id) };
6432                 if ($@) {
6433                         Git::SVN->init($l_map{$ref_id}, '', $ref_id, $ref_id);
6434                 }
6435                 $migrated++;
6436         }
6437         $migrated;
6440 sub minimize_connections {
6441         my $r = Git::SVN::read_all_remotes();
6442         my $new_urls = {};
6443         my $root_repos = {};
6444         foreach my $repo_id (keys %$r) {
6445                 my $url = $r->{$repo_id}->{url} or next;
6446                 my $fetch = $r->{$repo_id}->{fetch} or next;
6447                 my $ra = Git::SVN::Ra->new($url);
6449                 # skip existing cases where we already connect to the root
6450                 if (($ra->{url} eq $ra->{repos_root}) ||
6451                     ($ra->{repos_root} eq $repo_id)) {
6452                         $root_repos->{$ra->{url}} = $repo_id;
6453                         next;
6454                 }
6456                 my $root_ra = Git::SVN::Ra->new($ra->{repos_root});
6457                 my $root_path = $ra->{url};
6458                 $root_path =~ s#^\Q$ra->{repos_root}\E(/|$)##;
6459                 foreach my $path (keys %$fetch) {
6460                         my $ref_id = $fetch->{$path};
6461                         my $gs = Git::SVN->new($ref_id, $repo_id, $path);
6463                         # make sure we can read when connecting to
6464                         # a higher level of a repository
6465                         my ($last_rev, undef) = $gs->last_rev_commit;
6466                         if (!defined $last_rev) {
6467                                 $last_rev = eval {
6468                                         $root_ra->get_latest_revnum;
6469                                 };
6470                                 next if $@;
6471                         }
6472                         my $new = $root_path;
6473                         $new .= length $path ? "/$path" : '';
6474                         eval {
6475                                 $root_ra->get_log([$new], $last_rev, $last_rev,
6476                                                   0, 0, 1, sub { });
6477                         };
6478                         next if $@;
6479                         $new_urls->{$ra->{repos_root}}->{$new} =
6480                                 { ref_id => $ref_id,
6481                                   old_repo_id => $repo_id,
6482                                   old_path => $path };
6483                 }
6484         }
6486         my @emptied;
6487         foreach my $url (keys %$new_urls) {
6488                 # see if we can re-use an existing [svn-remote "repo_id"]
6489                 # instead of creating a(n ugly) new section:
6490                 my $repo_id = $root_repos->{$url} || $url;
6492                 my $fetch = $new_urls->{$url};
6493                 foreach my $path (keys %$fetch) {
6494                         my $x = $fetch->{$path};
6495                         Git::SVN->init($url, $path, $repo_id, $x->{ref_id});
6496                         my $pfx = "svn-remote.$x->{old_repo_id}";
6498                         my $old_fetch = quotemeta("$x->{old_path}:".
6499                                                   "$x->{ref_id}");
6500                         command_noisy(qw/config --unset/,
6501                                       "$pfx.fetch", '^'. $old_fetch . '$');
6502                         delete $r->{$x->{old_repo_id}}->
6503                                {fetch}->{$x->{old_path}};
6504                         if (!keys %{$r->{$x->{old_repo_id}}->{fetch}}) {
6505                                 command_noisy(qw/config --unset/,
6506                                               "$pfx.url");
6507                                 push @emptied, $x->{old_repo_id}
6508                         }
6509                 }
6510         }
6511         if (@emptied) {
6512                 my $file = $ENV{GIT_CONFIG} || "$ENV{GIT_DIR}/config";
6513                 print STDERR <<EOF;
6514 The following [svn-remote] sections in your config file ($file) are empty
6515 and can be safely removed:
6516 EOF
6517                 print STDERR "[svn-remote \"$_\"]\n" foreach @emptied;
6518         }
6521 sub migration_check {
6522         migrate_from_v0();
6523         migrate_from_v1();
6524         migrate_from_v2();
6525         minimize_connections() if $_minimize;
6528 package Git::IndexInfo;
6529 use strict;
6530 use warnings;
6531 use Git qw/command_input_pipe command_close_pipe/;
6533 sub new {
6534         my ($class) = @_;
6535         my ($gui, $ctx) = command_input_pipe(qw/update-index -z --index-info/);
6536         bless { gui => $gui, ctx => $ctx, nr => 0}, $class;
6539 sub remove {
6540         my ($self, $path) = @_;
6541         if (print { $self->{gui} } '0 ', 0 x 40, "\t", $path, "\0") {
6542                 return ++$self->{nr};
6543         }
6544         undef;
6547 sub update {
6548         my ($self, $mode, $hash, $path) = @_;
6549         if (print { $self->{gui} } $mode, ' ', $hash, "\t", $path, "\0") {
6550                 return ++$self->{nr};
6551         }
6552         undef;
6555 sub DESTROY {
6556         my ($self) = @_;
6557         command_close_pipe($self->{gui}, $self->{ctx});
6560 package Git::SVN::GlobSpec;
6561 use strict;
6562 use warnings;
6564 sub new {
6565         my ($class, $glob, $pattern_ok) = @_;
6566         my $re = $glob;
6567         $re =~ s!/+$!!g; # no need for trailing slashes
6568         my (@left, @right, @patterns);
6569         my $state = "left";
6570         my $die_msg = "Only one set of wildcard directories " .
6571                                 "(e.g. '*' or '*/*/*') is supported: '$glob'\n";
6572         for my $part (split(m|/|, $glob)) {
6573                 if ($part =~ /\*/ && $part ne "*") {
6574                         die "Invalid pattern in '$glob': $part\n";
6575                 } elsif ($pattern_ok && $part =~ /[{}]/ &&
6576                          $part !~ /^\{[^{}]+\}/) {
6577                         die "Invalid pattern in '$glob': $part\n";
6578                 }
6579                 if ($part eq "*") {
6580                         die $die_msg if $state eq "right";
6581                         $state = "pattern";
6582                         push(@patterns, "[^/]*");
6583                 } elsif ($pattern_ok && $part =~ /^\{(.*)\}$/) {
6584                         die $die_msg if $state eq "right";
6585                         $state = "pattern";
6586                         my $p = quotemeta($1);
6587                         $p =~ s/\\,/|/g;
6588                         push(@patterns, "(?:$p)");
6589                 } else {
6590                         if ($state eq "left") {
6591                                 push(@left, $part);
6592                         } else {
6593                                 push(@right, $part);
6594                                 $state = "right";
6595                         }
6596                 }
6597         }
6598         my $depth = @patterns;
6599         if ($depth == 0) {
6600                 die "One '*' is needed in glob: '$glob'\n";
6601         }
6602         my $left = join('/', @left);
6603         my $right = join('/', @right);
6604         $re = join('/', @patterns);
6605         $re = join('\/',
6606                    grep(length, quotemeta($left), "($re)", quotemeta($right)));
6607         my $left_re = qr/^\/\Q$left\E(\/|$)/;
6608         bless { left => $left, right => $right, left_regex => $left_re,
6609                 regex => qr/$re/, glob => $glob, depth => $depth }, $class;
6612 sub full_path {
6613         my ($self, $path) = @_;
6614         return (length $self->{left} ? "$self->{left}/" : '') .
6615                $path . (length $self->{right} ? "/$self->{right}" : '');
6618 __END__
6620 Data structures:
6623 $remotes = { # returned by read_all_remotes()
6624         'svn' => {
6625                 # svn-remote.svn.url=https://svn.musicpd.org
6626                 url => 'https://svn.musicpd.org',
6627                 # svn-remote.svn.fetch=mpd/trunk:trunk
6628                 fetch => {
6629                         'mpd/trunk' => 'trunk',
6630                 },
6631                 # svn-remote.svn.tags=mpd/tags/*:tags/*
6632                 tags => {
6633                         path => {
6634                                 left => 'mpd/tags',
6635                                 right => '',
6636                                 regex => qr!mpd/tags/([^/]+)$!,
6637                                 glob => 'tags/*',
6638                         },
6639                         ref => {
6640                                 left => 'tags',
6641                                 right => '',
6642                                 regex => qr!tags/([^/]+)$!,
6643                                 glob => 'tags/*',
6644                         },
6645                 }
6646         }
6647 };
6649 $log_entry hashref as returned by libsvn_log_entry()
6651         log => 'whitespace-formatted log entry
6652 ',                                              # trailing newline is preserved
6653         revision => '8',                        # integer
6654         date => '2004-02-24T17:01:44.108345Z',  # commit date
6655         author => 'committer name'
6656 };
6659 # this is generated by generate_diff();
6660 @mods = array of diff-index line hashes, each element represents one line
6661         of diff-index output
6663 diff-index line ($m hash)
6665         mode_a => first column of diff-index output, no leading ':',
6666         mode_b => second column of diff-index output,
6667         sha1_b => sha1sum of the final blob,
6668         chg => change type [MCRADT],
6669         file_a => original file name of a file (iff chg is 'C' or 'R')
6670         file_b => new/current file name of a file (any chg)
6674 # retval of read_url_paths{,_all}();
6675 $l_map = {
6676         # repository root url
6677         'https://svn.musicpd.org' => {
6678                 # repository path               # GIT_SVN_ID
6679                 'mpd/trunk'             =>      'trunk',
6680                 'mpd/tags/0.11.5'       =>      'tags/0.11.5',
6681         },
6684 Notes:
6685         I don't trust the each() function on unless I created %hash myself
6686         because the internal iterator may not have started at base.