Code

If deriving SVN_SSH from GIT_SSH on msys, also add quotes
[git.git] / git-svn.perl
1 #!/usr/bin/env perl
2 # Copyright (C) 2006, Eric Wong <normalperson@yhbt.net>
3 # License: GPL v2 or later
4 use warnings;
5 use strict;
6 use vars qw/    $AUTHOR $VERSION
7                 $sha1 $sha1_short $_revision $_repository
8                 $_q $_authors $_authors_prog %users/;
9 $AUTHOR = 'Eric Wong <normalperson@yhbt.net>';
10 $VERSION = '@@GIT_VERSION@@';
12 # From which subdir have we been invoked?
13 my $cmd_dir_prefix = eval {
14         command_oneline([qw/rev-parse --show-prefix/], STDERR => 0)
15 } || '';
17 my $git_dir_user_set = 1 if defined $ENV{GIT_DIR};
18 $ENV{GIT_DIR} ||= '.git';
19 $Git::SVN::default_repo_id = 'svn';
20 $Git::SVN::default_ref_id = $ENV{GIT_SVN_ID} || 'git-svn';
21 $Git::SVN::Ra::_log_window_size = 100;
22 $Git::SVN::_minimize_url = 'unset';
24 if (! exists $ENV{SVN_SSH}) {
25         if (exists $ENV{GIT_SSH}) {
26                 $ENV{SVN_SSH} = $ENV{GIT_SSH};
27                 if ($^O eq 'msys') {
28                         $ENV{SVN_SSH} =~ s/\\/\\\\/g;
29                         $ENV{SVN_SSH} =~ s/(.*)/"$1"/;
30                 }
31         }
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 require SVN::Core; # use()-ing this causes segfaults for me... *shrug*
40 require SVN::Ra;
41 require SVN::Delta;
42 if ($SVN::Core::VERSION lt '1.1.0') {
43         fatal "Need SVN::Core 1.1.0 or better (got $SVN::Core::VERSION)";
44 }
45 my $can_compress = eval { require Compress::Zlib; 1};
46 push @Git::SVN::Ra::ISA, 'SVN::Ra';
47 push @SVN::Git::Editor::ISA, 'SVN::Delta::Editor';
48 push @SVN::Git::Fetcher::ISA, 'SVN::Delta::Editor';
49 use Carp qw/croak/;
50 use Digest::MD5;
51 use IO::File qw//;
52 use File::Basename qw/dirname basename/;
53 use File::Path qw/mkpath/;
54 use File::Spec;
55 use File::Find;
56 use Getopt::Long qw/:config gnu_getopt no_ignore_case auto_abbrev/;
57 use IPC::Open3;
58 use Git;
60 BEGIN {
61         # import functions from Git into our packages, en masse
62         no strict 'refs';
63         foreach (qw/command command_oneline command_noisy command_output_pipe
64                     command_input_pipe command_close_pipe
65                     command_bidi_pipe command_close_bidi_pipe/) {
66                 for my $package ( qw(SVN::Git::Editor SVN::Git::Fetcher
67                         Git::SVN::Migration Git::SVN::Log Git::SVN),
68                         __PACKAGE__) {
69                         *{"${package}::$_"} = \&{"Git::$_"};
70                 }
71         }
72 }
74 my ($SVN);
76 $sha1 = qr/[a-f\d]{40}/;
77 $sha1_short = qr/[a-f\d]{4,40}/;
78 my ($_stdin, $_help, $_edit,
79         $_message, $_file, $_branch_dest,
80         $_template, $_shared,
81         $_version, $_fetch_all, $_no_rebase, $_fetch_parent,
82         $_merge, $_strategy, $_dry_run, $_local,
83         $_prefix, $_no_checkout, $_url, $_verbose,
84         $_git_format, $_commit_url, $_tag);
85 $Git::SVN::_follow_parent = 1;
86 $_q ||= 0;
87 my %remote_opts = ( 'username=s' => \$Git::SVN::Prompt::_username,
88                     'config-dir=s' => \$Git::SVN::Ra::config_dir,
89                     'no-auth-cache' => \$Git::SVN::Prompt::_no_auth_cache,
90                     'ignore-paths=s' => \$SVN::Git::Fetcher::_ignore_regex );
91 my %fc_opts = ( 'follow-parent|follow!' => \$Git::SVN::_follow_parent,
92                 'authors-file|A=s' => \$_authors,
93                 'authors-prog=s' => \$_authors_prog,
94                 'repack:i' => \$Git::SVN::_repack,
95                 'noMetadata' => \$Git::SVN::_no_metadata,
96                 'useSvmProps' => \$Git::SVN::_use_svm_props,
97                 'useSvnsyncProps' => \$Git::SVN::_use_svnsync_props,
98                 'log-window-size=i' => \$Git::SVN::Ra::_log_window_size,
99                 'no-checkout' => \$_no_checkout,
100                 'quiet|q+' => \$_q,
101                 'repack-flags|repack-args|repack-opts=s' =>
102                    \$Git::SVN::_repack_flags,
103                 'use-log-author' => \$Git::SVN::_use_log_author,
104                 'add-author-from' => \$Git::SVN::_add_author_from,
105                 'localtime' => \$Git::SVN::_localtime,
106                 %remote_opts );
108 my ($_trunk, @_tags, @_branches, $_stdlayout);
109 my %icv;
110 my %init_opts = ( 'template=s' => \$_template, 'shared:s' => \$_shared,
111                   'trunk|T=s' => \$_trunk, 'tags|t=s@' => \@_tags,
112                   'branches|b=s@' => \@_branches, 'prefix=s' => \$_prefix,
113                   'stdlayout|s' => \$_stdlayout,
114                   'minimize-url|m!' => \$Git::SVN::_minimize_url,
115                   'no-metadata' => sub { $icv{noMetadata} = 1 },
116                   'use-svm-props' => sub { $icv{useSvmProps} = 1 },
117                   'use-svnsync-props' => sub { $icv{useSvnsyncProps} = 1 },
118                   'rewrite-root=s' => sub { $icv{rewriteRoot} = $_[1] },
119                   'rewrite-uuid=s' => sub { $icv{rewriteUUID} = $_[1] },
120                   %remote_opts );
121 my %cmt_opts = ( 'edit|e' => \$_edit,
122                 'rmdir' => \$SVN::Git::Editor::_rmdir,
123                 'find-copies-harder' => \$SVN::Git::Editor::_find_copies_harder,
124                 'l=i' => \$SVN::Git::Editor::_rename_limit,
125                 'copy-similarity|C=i'=> \$SVN::Git::Editor::_cp_similarity
126 );
128 my %cmd = (
129         fetch => [ \&cmd_fetch, "Download new revisions from SVN",
130                         { 'revision|r=s' => \$_revision,
131                           'fetch-all|all' => \$_fetch_all,
132                           'parent|p' => \$_fetch_parent,
133                            %fc_opts } ],
134         clone => [ \&cmd_clone, "Initialize and fetch revisions",
135                         { 'revision|r=s' => \$_revision,
136                            %fc_opts, %init_opts } ],
137         init => [ \&cmd_init, "Initialize a repo for tracking" .
138                           " (requires URL argument)",
139                           \%init_opts ],
140         'multi-init' => [ \&cmd_multi_init,
141                           "Deprecated alias for ".
142                           "'$0 init -T<trunk> -b<branches> -t<tags>'",
143                           \%init_opts ],
144         dcommit => [ \&cmd_dcommit,
145                      'Commit several diffs to merge with upstream',
146                         { 'merge|m|M' => \$_merge,
147                           'strategy|s=s' => \$_strategy,
148                           'verbose|v' => \$_verbose,
149                           'dry-run|n' => \$_dry_run,
150                           'fetch-all|all' => \$_fetch_all,
151                           'commit-url=s' => \$_commit_url,
152                           'revision|r=i' => \$_revision,
153                           'no-rebase' => \$_no_rebase,
154                         %cmt_opts, %fc_opts } ],
155         branch => [ \&cmd_branch,
156                     'Create a branch in the SVN repository',
157                     { 'message|m=s' => \$_message,
158                       'destination|d=s' => \$_branch_dest,
159                       'dry-run|n' => \$_dry_run,
160                       'tag|t' => \$_tag,
161                       'username=s' => \$Git::SVN::Prompt::_username,
162                       'commit-url=s' => \$_commit_url } ],
163         tag => [ sub { $_tag = 1; cmd_branch(@_) },
164                  'Create a tag in the SVN repository',
165                  { 'message|m=s' => \$_message,
166                    'destination|d=s' => \$_branch_dest,
167                    'dry-run|n' => \$_dry_run,
168                    'username=s' => \$Git::SVN::Prompt::_username,
169                    'commit-url=s' => \$_commit_url } ],
170         'set-tree' => [ \&cmd_set_tree,
171                         "Set an SVN repository to a git tree-ish",
172                         { 'stdin' => \$_stdin, %cmt_opts, %fc_opts, } ],
173         'create-ignore' => [ \&cmd_create_ignore,
174                              'Create a .gitignore per svn:ignore',
175                              { 'revision|r=i' => \$_revision
176                              } ],
177         'mkdirs' => [ \&cmd_mkdirs ,
178                       "recreate empty directories after a checkout",
179                       { 'revision|r=i' => \$_revision } ],
180         'propget' => [ \&cmd_propget,
181                        'Print the value of a property on a file or directory',
182                        { 'revision|r=i' => \$_revision } ],
183         'proplist' => [ \&cmd_proplist,
184                        'List all properties of a file or directory',
185                        { 'revision|r=i' => \$_revision } ],
186         'show-ignore' => [ \&cmd_show_ignore, "Show svn:ignore listings",
187                         { 'revision|r=i' => \$_revision
188                         } ],
189         'show-externals' => [ \&cmd_show_externals, "Show svn:externals listings",
190                         { 'revision|r=i' => \$_revision
191                         } ],
192         'multi-fetch' => [ \&cmd_multi_fetch,
193                            "Deprecated alias for $0 fetch --all",
194                            { 'revision|r=s' => \$_revision, %fc_opts } ],
195         'migrate' => [ sub { },
196                        # no-op, we automatically run this anyways,
197                        'Migrate configuration/metadata/layout from
198                         previous versions of git-svn',
199                        { 'minimize' => \$Git::SVN::Migration::_minimize,
200                          %remote_opts } ],
201         'log' => [ \&Git::SVN::Log::cmd_show_log, 'Show commit logs',
202                         { 'limit=i' => \$Git::SVN::Log::limit,
203                           'revision|r=s' => \$_revision,
204                           'verbose|v' => \$Git::SVN::Log::verbose,
205                           'incremental' => \$Git::SVN::Log::incremental,
206                           'oneline' => \$Git::SVN::Log::oneline,
207                           'show-commit' => \$Git::SVN::Log::show_commit,
208                           'non-recursive' => \$Git::SVN::Log::non_recursive,
209                           'authors-file|A=s' => \$_authors,
210                           'color' => \$Git::SVN::Log::color,
211                           'pager=s' => \$Git::SVN::Log::pager
212                         } ],
213         'find-rev' => [ \&cmd_find_rev,
214                         "Translate between SVN revision numbers and tree-ish",
215                         {} ],
216         'rebase' => [ \&cmd_rebase, "Fetch and rebase your working directory",
217                         { 'merge|m|M' => \$_merge,
218                           'verbose|v' => \$_verbose,
219                           'strategy|s=s' => \$_strategy,
220                           'local|l' => \$_local,
221                           'fetch-all|all' => \$_fetch_all,
222                           'dry-run|n' => \$_dry_run,
223                           %fc_opts } ],
224         'commit-diff' => [ \&cmd_commit_diff,
225                            'Commit a diff between two trees',
226                         { 'message|m=s' => \$_message,
227                           'file|F=s' => \$_file,
228                           'revision|r=s' => \$_revision,
229                         %cmt_opts } ],
230         'info' => [ \&cmd_info,
231                     "Show info about the latest SVN revision
232                      on the current branch",
233                     { 'url' => \$_url, } ],
234         'blame' => [ \&Git::SVN::Log::cmd_blame,
235                     "Show what revision and author last modified each line of a file",
236                     { 'git-format' => \$_git_format } ],
237         'reset' => [ \&cmd_reset,
238                      "Undo fetches back to the specified SVN revision",
239                      { 'revision|r=s' => \$_revision,
240                        'parent|p' => \$_fetch_parent } ],
241         'gc' => [ \&cmd_gc,
242                   "Compress unhandled.log files in .git/svn and remove " .
243                   "index files in .git/svn",
244                 {} ],
245 );
247 my $cmd;
248 for (my $i = 0; $i < @ARGV; $i++) {
249         if (defined $cmd{$ARGV[$i]}) {
250                 $cmd = $ARGV[$i];
251                 splice @ARGV, $i, 1;
252                 last;
253         } elsif ($ARGV[$i] eq 'help') {
254                 $cmd = $ARGV[$i+1];
255                 usage(0);
256         }
257 };
259 # make sure we're always running at the top-level working directory
260 unless ($cmd && $cmd =~ /(?:clone|init|multi-init)$/) {
261         unless (-d $ENV{GIT_DIR}) {
262                 if ($git_dir_user_set) {
263                         die "GIT_DIR=$ENV{GIT_DIR} explicitly set, ",
264                             "but it is not a directory\n";
265                 }
266                 my $git_dir = delete $ENV{GIT_DIR};
267                 my $cdup = undef;
268                 git_cmd_try {
269                         $cdup = command_oneline(qw/rev-parse --show-cdup/);
270                         $git_dir = '.' unless ($cdup);
271                         chomp $cdup if ($cdup);
272                         $cdup = "." unless ($cdup && length $cdup);
273                 } "Already at toplevel, but $git_dir not found\n";
274                 chdir $cdup or die "Unable to chdir up to '$cdup'\n";
275                 unless (-d $git_dir) {
276                         die "$git_dir still not found after going to ",
277                             "'$cdup'\n";
278                 }
279                 $ENV{GIT_DIR} = $git_dir;
280         }
281         $_repository = Git->repository(Repository => $ENV{GIT_DIR});
284 my %opts = %{$cmd{$cmd}->[2]} if (defined $cmd);
286 read_git_config(\%opts);
287 if ($cmd && ($cmd eq 'log' || $cmd eq 'blame')) {
288         Getopt::Long::Configure('pass_through');
290 my $rv = GetOptions(%opts, 'help|H|h' => \$_help, 'version|V' => \$_version,
291                     'minimize-connections' => \$Git::SVN::Migration::_minimize,
292                     'id|i=s' => \$Git::SVN::default_ref_id,
293                     'svn-remote|remote|R=s' => sub {
294                        $Git::SVN::no_reuse_existing = 1;
295                        $Git::SVN::default_repo_id = $_[1] });
296 exit 1 if (!$rv && $cmd && $cmd ne 'log');
298 usage(0) if $_help;
299 version() if $_version;
300 usage(1) unless defined $cmd;
301 load_authors() if $_authors;
302 if (defined $_authors_prog) {
303         $_authors_prog = "'" . File::Spec->rel2abs($_authors_prog) . "'";
306 unless ($cmd =~ /^(?:clone|init|multi-init|commit-diff)$/) {
307         Git::SVN::Migration::migration_check();
309 Git::SVN::init_vars();
310 eval {
311         Git::SVN::verify_remotes_sanity();
312         $cmd{$cmd}->[0]->(@ARGV);
313 };
314 fatal $@ if $@;
315 post_fetch_checkout();
316 exit 0;
318 ####################### primary functions ######################
319 sub usage {
320         my $exit = shift || 0;
321         my $fd = $exit ? \*STDERR : \*STDOUT;
322         print $fd <<"";
323 git-svn - bidirectional operations between a single Subversion tree and git
324 Usage: git svn <command> [options] [arguments]\n
326         print $fd "Available commands:\n" unless $cmd;
328         foreach (sort keys %cmd) {
329                 next if $cmd && $cmd ne $_;
330                 next if /^multi-/; # don't show deprecated commands
331                 print $fd '  ',pack('A17',$_),$cmd{$_}->[1],"\n";
332                 foreach (sort keys %{$cmd{$_}->[2]}) {
333                         # mixed-case options are for .git/config only
334                         next if /[A-Z]/ && /^[a-z]+$/i;
335                         # prints out arguments as they should be passed:
336                         my $x = s#[:=]s$## ? '<arg>' : s#[:=]i$## ? '<num>' : '';
337                         print $fd ' ' x 21, join(', ', map { length $_ > 1 ?
338                                                         "--$_" : "-$_" }
339                                                 split /\|/,$_)," $x\n";
340                 }
341         }
342         print $fd <<"";
343 \nGIT_SVN_ID may be set in the environment or via the --id/-i switch to an
344 arbitrary identifier if you're tracking multiple SVN branches/repositories in
345 one git repository and want to keep them separate.  See git-svn(1) for more
346 information.
348         exit $exit;
351 sub version {
352         print "git-svn version $VERSION (svn $SVN::Core::VERSION)\n";
353         exit 0;
356 sub do_git_init_db {
357         unless (-d $ENV{GIT_DIR}) {
358                 my @init_db = ('init');
359                 push @init_db, "--template=$_template" if defined $_template;
360                 if (defined $_shared) {
361                         if ($_shared =~ /[a-z]/) {
362                                 push @init_db, "--shared=$_shared";
363                         } else {
364                                 push @init_db, "--shared";
365                         }
366                 }
367                 command_noisy(@init_db);
368                 $_repository = Git->repository(Repository => ".git");
369         }
370         command_noisy('config', 'core.autocrlf', 'false');
371         my $set;
372         my $pfx = "svn-remote.$Git::SVN::default_repo_id";
373         foreach my $i (keys %icv) {
374                 die "'$set' and '$i' cannot both be set\n" if $set;
375                 next unless defined $icv{$i};
376                 command_noisy('config', "$pfx.$i", $icv{$i});
377                 $set = $i;
378         }
379         my $ignore_regex = \$SVN::Git::Fetcher::_ignore_regex;
380         command_noisy('config', "$pfx.ignore-paths", $$ignore_regex)
381                 if defined $$ignore_regex;
384 sub init_subdir {
385         my $repo_path = shift or return;
386         mkpath([$repo_path]) unless -d $repo_path;
387         chdir $repo_path or die "Couldn't chdir to $repo_path: $!\n";
388         $ENV{GIT_DIR} = '.git';
389         $_repository = Git->repository(Repository => $ENV{GIT_DIR});
392 sub cmd_clone {
393         my ($url, $path) = @_;
394         if (!defined $path &&
395             (defined $_trunk || @_branches || @_tags ||
396              defined $_stdlayout) &&
397             $url !~ m#^[a-z\+]+://#) {
398                 $path = $url;
399         }
400         $path = basename($url) if !defined $path || !length $path;
401         my $authors_absolute = $_authors ? File::Spec->rel2abs($_authors) : "";
402         cmd_init($url, $path);
403         command_oneline('config', 'svn.authorsfile', $authors_absolute)
404             if $_authors;
405         Git::SVN::fetch_all($Git::SVN::default_repo_id);
408 sub cmd_init {
409         if (defined $_stdlayout) {
410                 $_trunk = 'trunk' if (!defined $_trunk);
411                 @_tags = 'tags' if (! @_tags);
412                 @_branches = 'branches' if (! @_branches);
413         }
414         if (defined $_trunk || @_branches || @_tags) {
415                 return cmd_multi_init(@_);
416         }
417         my $url = shift or die "SVN repository location required ",
418                                "as a command-line argument\n";
419         $url = canonicalize_url($url);
420         init_subdir(@_);
421         do_git_init_db();
423         if ($Git::SVN::_minimize_url eq 'unset') {
424                 $Git::SVN::_minimize_url = 0;
425         }
427         Git::SVN->init($url);
430 sub cmd_fetch {
431         if (grep /^\d+=./, @_) {
432                 die "'<rev>=<commit>' fetch arguments are ",
433                     "no longer supported.\n";
434         }
435         my ($remote) = @_;
436         if (@_ > 1) {
437                 die "Usage: $0 fetch [--all] [--parent] [svn-remote]\n";
438         }
439         $Git::SVN::no_reuse_existing = undef;
440         if ($_fetch_parent) {
441                 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
442                 unless ($gs) {
443                         die "Unable to determine upstream SVN information from ",
444                             "working tree history\n";
445                 }
446                 # just fetch, don't checkout.
447                 $_no_checkout = 'true';
448                 $_fetch_all ? $gs->fetch_all : $gs->fetch;
449         } elsif ($_fetch_all) {
450                 cmd_multi_fetch();
451         } else {
452                 $remote ||= $Git::SVN::default_repo_id;
453                 Git::SVN::fetch_all($remote, Git::SVN::read_all_remotes());
454         }
457 sub cmd_set_tree {
458         my (@commits) = @_;
459         if ($_stdin || !@commits) {
460                 print "Reading from stdin...\n";
461                 @commits = ();
462                 while (<STDIN>) {
463                         if (/\b($sha1_short)\b/o) {
464                                 unshift @commits, $1;
465                         }
466                 }
467         }
468         my @revs;
469         foreach my $c (@commits) {
470                 my @tmp = command('rev-parse',$c);
471                 if (scalar @tmp == 1) {
472                         push @revs, $tmp[0];
473                 } elsif (scalar @tmp > 1) {
474                         push @revs, reverse(command('rev-list',@tmp));
475                 } else {
476                         fatal "Failed to rev-parse $c";
477                 }
478         }
479         my $gs = Git::SVN->new;
480         my ($r_last, $cmt_last) = $gs->last_rev_commit;
481         $gs->fetch;
482         if (defined $gs->{last_rev} && $r_last != $gs->{last_rev}) {
483                 fatal "There are new revisions that were fetched ",
484                       "and need to be merged (or acknowledged) ",
485                       "before committing.\nlast rev: $r_last\n",
486                       " current: $gs->{last_rev}";
487         }
488         $gs->set_tree($_) foreach @revs;
489         print "Done committing ",scalar @revs," revisions to SVN\n";
490         unlink $gs->{index};
493 sub cmd_dcommit {
494         my $head = shift;
495         git_cmd_try { command_oneline(qw/diff-index --quiet HEAD/) }
496                 'Cannot dcommit with a dirty index.  Commit your changes first, '
497                 . "or stash them with `git stash'.\n";
498         $head ||= 'HEAD';
500         my $old_head;
501         if ($head ne 'HEAD') {
502                 $old_head = eval {
503                         command_oneline([qw/symbolic-ref -q HEAD/])
504                 };
505                 if ($old_head) {
506                         $old_head =~ s{^refs/heads/}{};
507                 } else {
508                         $old_head = eval { command_oneline(qw/rev-parse HEAD/) };
509                 }
510                 command(['checkout', $head], STDERR => 0);
511         }
513         my @refs;
514         my ($url, $rev, $uuid, $gs) = working_head_info('HEAD', \@refs);
515         unless ($gs) {
516                 die "Unable to determine upstream SVN information from ",
517                     "$head history.\nPerhaps the repository is empty.";
518         }
520         if (defined $_commit_url) {
521                 $url = $_commit_url;
522         } else {
523                 $url = eval { command_oneline('config', '--get',
524                               "svn-remote.$gs->{repo_id}.commiturl") };
525                 if (!$url) {
526                         $url = $gs->full_url
527                 }
528         }
530         my $last_rev = $_revision if defined $_revision;
531         if ($url) {
532                 print "Committing to $url ...\n";
533         }
534         my ($linear_refs, $parents) = linearize_history($gs, \@refs);
535         if ($_no_rebase && scalar(@$linear_refs) > 1) {
536                 warn "Attempting to commit more than one change while ",
537                      "--no-rebase is enabled.\n",
538                      "If these changes depend on each other, re-running ",
539                      "without --no-rebase may be required."
540         }
541         my $expect_url = $url;
542         Git::SVN::remove_username($expect_url);
543         while (1) {
544                 my $d = shift @$linear_refs or last;
545                 unless (defined $last_rev) {
546                         (undef, $last_rev, undef) = cmt_metadata("$d~1");
547                         unless (defined $last_rev) {
548                                 fatal "Unable to extract revision information ",
549                                       "from commit $d~1";
550                         }
551                 }
552                 if ($_dry_run) {
553                         print "diff-tree $d~1 $d\n";
554                 } else {
555                         my $cmt_rev;
556                         my %ed_opts = ( r => $last_rev,
557                                         log => get_commit_entry($d)->{log},
558                                         ra => Git::SVN::Ra->new($url),
559                                         config => SVN::Core::config_get_config(
560                                                 $Git::SVN::Ra::config_dir
561                                         ),
562                                         tree_a => "$d~1",
563                                         tree_b => $d,
564                                         editor_cb => sub {
565                                                print "Committed r$_[0]\n";
566                                                $cmt_rev = $_[0];
567                                         },
568                                         svn_path => '');
569                         if (!SVN::Git::Editor->new(\%ed_opts)->apply_diff) {
570                                 print "No changes\n$d~1 == $d\n";
571                         } elsif ($parents->{$d} && @{$parents->{$d}}) {
572                                 $gs->{inject_parents_dcommit}->{$cmt_rev} =
573                                                                $parents->{$d};
574                         }
575                         $_fetch_all ? $gs->fetch_all : $gs->fetch;
576                         $last_rev = $cmt_rev;
577                         next if $_no_rebase;
579                         # we always want to rebase against the current HEAD,
580                         # not any head that was passed to us
581                         my @diff = command('diff-tree', $d,
582                                            $gs->refname, '--');
583                         my @finish;
584                         if (@diff) {
585                                 @finish = rebase_cmd();
586                                 print STDERR "W: $d and ", $gs->refname,
587                                              " differ, using @finish:\n",
588                                              join("\n", @diff), "\n";
589                         } else {
590                                 print "No changes between current HEAD and ",
591                                       $gs->refname,
592                                       "\nResetting to the latest ",
593                                       $gs->refname, "\n";
594                                 @finish = qw/reset --mixed/;
595                         }
596                         command_noisy(@finish, $gs->refname);
597                         if (@diff) {
598                                 @refs = ();
599                                 my ($url_, $rev_, $uuid_, $gs_) =
600                                               working_head_info('HEAD', \@refs);
601                                 my ($linear_refs_, $parents_) =
602                                               linearize_history($gs_, \@refs);
603                                 if (scalar(@$linear_refs) !=
604                                     scalar(@$linear_refs_)) {
605                                         fatal "# of revisions changed ",
606                                           "\nbefore:\n",
607                                           join("\n", @$linear_refs),
608                                           "\n\nafter:\n",
609                                           join("\n", @$linear_refs_), "\n",
610                                           'If you are attempting to commit ',
611                                           "merges, try running:\n\t",
612                                           'git rebase --interactive',
613                                           '--preserve-merges ',
614                                           $gs->refname,
615                                           "\nBefore dcommitting";
616                                 }
617                                 if ($url_ ne $expect_url) {
618                                         if ($url_ eq $gs->metadata_url) {
619                                                 print
620                                                   "Accepting rewritten URL:",
621                                                   " $url_\n";
622                                         } else {
623                                                 fatal
624                                                   "URL mismatch after rebase:",
625                                                   " $url_ != $expect_url";
626                                         }
627                                 }
628                                 if ($uuid_ ne $uuid) {
629                                         fatal "uuid mismatch after rebase: ",
630                                               "$uuid_ != $uuid";
631                                 }
632                                 # remap parents
633                                 my (%p, @l, $i);
634                                 for ($i = 0; $i < scalar @$linear_refs; $i++) {
635                                         my $new = $linear_refs_->[$i] or next;
636                                         $p{$new} =
637                                                 $parents->{$linear_refs->[$i]};
638                                         push @l, $new;
639                                 }
640                                 $parents = \%p;
641                                 $linear_refs = \@l;
642                         }
643                 }
644         }
646         if ($old_head) {
647                 my $new_head = command_oneline(qw/rev-parse HEAD/);
648                 my $new_is_symbolic = eval {
649                         command_oneline(qw/symbolic-ref -q HEAD/);
650                 };
651                 if ($new_is_symbolic) {
652                         print "dcommitted the branch ", $head, "\n";
653                 } else {
654                         print "dcommitted on a detached HEAD because you gave ",
655                               "a revision argument.\n",
656                               "The rewritten commit is: ", $new_head, "\n";
657                 }
658                 command(['checkout', $old_head], STDERR => 0);
659         }
661         unlink $gs->{index};
664 sub cmd_branch {
665         my ($branch_name, $head) = @_;
667         unless (defined $branch_name && length $branch_name) {
668                 die(($_tag ? "tag" : "branch") . " name required\n");
669         }
670         $head ||= 'HEAD';
672         my (undef, $rev, undef, $gs) = working_head_info($head);
673         my $src = $gs->full_url;
675         my $remote = Git::SVN::read_all_remotes()->{$gs->{repo_id}};
676         my $allglobs = $remote->{ $_tag ? 'tags' : 'branches' };
677         my $glob;
678         if ($#{$allglobs} == 0) {
679                 $glob = $allglobs->[0];
680         } else {
681                 unless(defined $_branch_dest) {
682                         die "Multiple ",
683                             $_tag ? "tag" : "branch",
684                             " paths defined for Subversion repository.\n",
685                             "You must specify where you want to create the ",
686                             $_tag ? "tag" : "branch",
687                             " with the --destination argument.\n";
688                 }
689                 foreach my $g (@{$allglobs}) {
690                         # SVN::Git::Editor could probably be moved to Git.pm..
691                         my $re = SVN::Git::Editor::glob2pat($g->{path}->{left});
692                         if ($_branch_dest =~ /$re/) {
693                                 $glob = $g;
694                                 last;
695                         }
696                 }
697                 unless (defined $glob) {
698                         my $dest_re = qr/\b\Q$_branch_dest\E\b/;
699                         foreach my $g (@{$allglobs}) {
700                                 $g->{path}->{left} =~ /$dest_re/ or next;
701                                 if (defined $glob) {
702                                         die "Ambiguous destination: ",
703                                             $_branch_dest, "\nmatches both '",
704                                             $glob->{path}->{left}, "' and '",
705                                             $g->{path}->{left}, "'\n";
706                                 }
707                                 $glob = $g;
708                         }
709                         unless (defined $glob) {
710                                 die "Unknown ",
711                                     $_tag ? "tag" : "branch",
712                                     " destination $_branch_dest\n";
713                         }
714                 }
715         }
716         my ($lft, $rgt) = @{ $glob->{path} }{qw/left right/};
717         my $url;
718         if (defined $_commit_url) {
719                 $url = $_commit_url;
720         } else {
721                 $url = eval { command_oneline('config', '--get',
722                         "svn-remote.$gs->{repo_id}.commiturl") };
723                 if (!$url) {
724                         $url = $remote->{url};
725                 }
726         }
727         my $dst = join '/', $url, $lft, $branch_name, ($rgt || ());
729         if ($dst =~ /^https:/ && $src =~ /^http:/) {
730                 $src=~s/^http:/https:/;
731         }
733         my $ctx = SVN::Client->new(
734                 auth    => Git::SVN::Ra::_auth_providers(),
735                 log_msg => sub {
736                         ${ $_[0] } = defined $_message
737                                 ? $_message
738                                 : 'Create ' . ($_tag ? 'tag ' : 'branch ' )
739                                 . $branch_name;
740                 },
741         );
743         eval {
744                 $ctx->ls($dst, 'HEAD', 0);
745         } and die "branch ${branch_name} already exists\n";
747         print "Copying ${src} at r${rev} to ${dst}...\n";
748         $ctx->copy($src, $rev, $dst)
749                 unless $_dry_run;
751         $gs->fetch_all;
754 sub cmd_find_rev {
755         my $revision_or_hash = shift or die "SVN or git revision required ",
756                                             "as a command-line argument\n";
757         my $result;
758         if ($revision_or_hash =~ /^r\d+$/) {
759                 my $head = shift;
760                 $head ||= 'HEAD';
761                 my @refs;
762                 my (undef, undef, $uuid, $gs) = working_head_info($head, \@refs);
763                 unless ($gs) {
764                         die "Unable to determine upstream SVN information from ",
765                             "$head history\n";
766                 }
767                 my $desired_revision = substr($revision_or_hash, 1);
768                 $result = $gs->rev_map_get($desired_revision, $uuid);
769         } else {
770                 my (undef, $rev, undef) = cmt_metadata($revision_or_hash);
771                 $result = $rev;
772         }
773         print "$result\n" if $result;
776 sub cmd_rebase {
777         command_noisy(qw/update-index --refresh/);
778         my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
779         unless ($gs) {
780                 die "Unable to determine upstream SVN information from ",
781                     "working tree history\n";
782         }
783         if ($_dry_run) {
784                 print "Remote Branch: " . $gs->refname . "\n";
785                 print "SVN URL: " . $url . "\n";
786                 return;
787         }
788         if (command(qw/diff-index HEAD --/)) {
789                 print STDERR "Cannot rebase with uncommited changes:\n";
790                 command_noisy('status');
791                 exit 1;
792         }
793         unless ($_local) {
794                 # rebase will checkout for us, so no need to do it explicitly
795                 $_no_checkout = 'true';
796                 $_fetch_all ? $gs->fetch_all : $gs->fetch;
797         }
798         command_noisy(rebase_cmd(), $gs->refname);
799         $gs->mkemptydirs;
802 sub cmd_show_ignore {
803         my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
804         $gs ||= Git::SVN->new;
805         my $r = (defined $_revision ? $_revision : $gs->ra->get_latest_revnum);
806         $gs->prop_walk($gs->{path}, $r, sub {
807                 my ($gs, $path, $props) = @_;
808                 print STDOUT "\n# $path\n";
809                 my $s = $props->{'svn:ignore'} or return;
810                 $s =~ s/[\r\n]+/\n/g;
811                 $s =~ s/^\n+//;
812                 chomp $s;
813                 $s =~ s#^#$path#gm;
814                 print STDOUT "$s\n";
815         });
818 sub cmd_show_externals {
819         my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
820         $gs ||= Git::SVN->new;
821         my $r = (defined $_revision ? $_revision : $gs->ra->get_latest_revnum);
822         $gs->prop_walk($gs->{path}, $r, sub {
823                 my ($gs, $path, $props) = @_;
824                 print STDOUT "\n# $path\n";
825                 my $s = $props->{'svn:externals'} or return;
826                 $s =~ s/[\r\n]+/\n/g;
827                 chomp $s;
828                 $s =~ s#^#$path#gm;
829                 print STDOUT "$s\n";
830         });
833 sub cmd_create_ignore {
834         my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
835         $gs ||= Git::SVN->new;
836         my $r = (defined $_revision ? $_revision : $gs->ra->get_latest_revnum);
837         $gs->prop_walk($gs->{path}, $r, sub {
838                 my ($gs, $path, $props) = @_;
839                 # $path is of the form /path/to/dir/
840                 $path = '.' . $path;
841                 # SVN can have attributes on empty directories,
842                 # which git won't track
843                 mkpath([$path]) unless -d $path;
844                 my $ignore = $path . '.gitignore';
845                 my $s = $props->{'svn:ignore'} or return;
846                 open(GITIGNORE, '>', $ignore)
847                   or fatal("Failed to open `$ignore' for writing: $!");
848                 $s =~ s/[\r\n]+/\n/g;
849                 $s =~ s/^\n+//;
850                 chomp $s;
851                 # Prefix all patterns so that the ignore doesn't apply
852                 # to sub-directories.
853                 $s =~ s#^#/#gm;
854                 print GITIGNORE "$s\n";
855                 close(GITIGNORE)
856                   or fatal("Failed to close `$ignore': $!");
857                 command_noisy('add', '-f', $ignore);
858         });
861 sub cmd_mkdirs {
862         my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
863         $gs ||= Git::SVN->new;
864         $gs->mkemptydirs($_revision);
867 sub canonicalize_path {
868         my ($path) = @_;
869         my $dot_slash_added = 0;
870         if (substr($path, 0, 1) ne "/") {
871                 $path = "./" . $path;
872                 $dot_slash_added = 1;
873         }
874         # File::Spec->canonpath doesn't collapse x/../y into y (for a
875         # good reason), so let's do this manually.
876         $path =~ s#/+#/#g;
877         $path =~ s#/\.(?:/|$)#/#g;
878         $path =~ s#/[^/]+/\.\.##g;
879         $path =~ s#/$##g;
880         $path =~ s#^\./## if $dot_slash_added;
881         $path =~ s#^/##;
882         $path =~ s#^\.$##;
883         return $path;
886 sub canonicalize_url {
887         my ($url) = @_;
888         $url =~ s#^([^:]+://[^/]*/)(.*)$#$1 . canonicalize_path($2)#e;
889         return $url;
892 # get_svnprops(PATH)
893 # ------------------
894 # Helper for cmd_propget and cmd_proplist below.
895 sub get_svnprops {
896         my $path = shift;
897         my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
898         $gs ||= Git::SVN->new;
900         # prefix THE PATH by the sub-directory from which the user
901         # invoked us.
902         $path = $cmd_dir_prefix . $path;
903         fatal("No such file or directory: $path") unless -e $path;
904         my $is_dir = -d $path ? 1 : 0;
905         $path = $gs->{path} . '/' . $path;
907         # canonicalize the path (otherwise libsvn will abort or fail to
908         # find the file)
909         $path = canonicalize_path($path);
911         my $r = (defined $_revision ? $_revision : $gs->ra->get_latest_revnum);
912         my $props;
913         if ($is_dir) {
914                 (undef, undef, $props) = $gs->ra->get_dir($path, $r);
915         }
916         else {
917                 (undef, $props) = $gs->ra->get_file($path, $r, undef);
918         }
919         return $props;
922 # cmd_propget (PROP, PATH)
923 # ------------------------
924 # Print the SVN property PROP for PATH.
925 sub cmd_propget {
926         my ($prop, $path) = @_;
927         $path = '.' if not defined $path;
928         usage(1) if not defined $prop;
929         my $props = get_svnprops($path);
930         if (not defined $props->{$prop}) {
931                 fatal("`$path' does not have a `$prop' SVN property.");
932         }
933         print $props->{$prop} . "\n";
936 # cmd_proplist (PATH)
937 # -------------------
938 # Print the list of SVN properties for PATH.
939 sub cmd_proplist {
940         my $path = shift;
941         $path = '.' if not defined $path;
942         my $props = get_svnprops($path);
943         print "Properties on '$path':\n";
944         foreach (sort keys %{$props}) {
945                 print "  $_\n";
946         }
949 sub cmd_multi_init {
950         my $url = shift;
951         unless (defined $_trunk || @_branches || @_tags) {
952                 usage(1);
953         }
955         $_prefix = '' unless defined $_prefix;
956         if (defined $url) {
957                 $url = canonicalize_url($url);
958                 init_subdir(@_);
959         }
960         do_git_init_db();
961         if (defined $_trunk) {
962                 my $trunk_ref = 'refs/remotes/' . $_prefix . 'trunk';
963                 # try both old-style and new-style lookups:
964                 my $gs_trunk = eval { Git::SVN->new($trunk_ref) };
965                 unless ($gs_trunk) {
966                         my ($trunk_url, $trunk_path) =
967                                               complete_svn_url($url, $_trunk);
968                         $gs_trunk = Git::SVN->init($trunk_url, $trunk_path,
969                                                    undef, $trunk_ref);
970                 }
971         }
972         return unless @_branches || @_tags;
973         my $ra = $url ? Git::SVN::Ra->new($url) : undef;
974         foreach my $path (@_branches) {
975                 complete_url_ls_init($ra, $path, '--branches/-b', $_prefix);
976         }
977         foreach my $path (@_tags) {
978                 complete_url_ls_init($ra, $path, '--tags/-t', $_prefix.'tags/');
979         }
982 sub cmd_multi_fetch {
983         $Git::SVN::no_reuse_existing = undef;
984         my $remotes = Git::SVN::read_all_remotes();
985         foreach my $repo_id (sort keys %$remotes) {
986                 if ($remotes->{$repo_id}->{url}) {
987                         Git::SVN::fetch_all($repo_id, $remotes);
988                 }
989         }
992 # this command is special because it requires no metadata
993 sub cmd_commit_diff {
994         my ($ta, $tb, $url) = @_;
995         my $usage = "Usage: $0 commit-diff -r<revision> ".
996                     "<tree-ish> <tree-ish> [<URL>]";
997         fatal($usage) if (!defined $ta || !defined $tb);
998         my $svn_path = '';
999         if (!defined $url) {
1000                 my $gs = eval { Git::SVN->new };
1001                 if (!$gs) {
1002                         fatal("Needed URL or usable git-svn --id in ",
1003                               "the command-line\n", $usage);
1004                 }
1005                 $url = $gs->{url};
1006                 $svn_path = $gs->{path};
1007         }
1008         unless (defined $_revision) {
1009                 fatal("-r|--revision is a required argument\n", $usage);
1010         }
1011         if (defined $_message && defined $_file) {
1012                 fatal("Both --message/-m and --file/-F specified ",
1013                       "for the commit message.\n",
1014                       "I have no idea what you mean");
1015         }
1016         if (defined $_file) {
1017                 $_message = file_to_s($_file);
1018         } else {
1019                 $_message ||= get_commit_entry($tb)->{log};
1020         }
1021         my $ra ||= Git::SVN::Ra->new($url);
1022         my $r = $_revision;
1023         if ($r eq 'HEAD') {
1024                 $r = $ra->get_latest_revnum;
1025         } elsif ($r !~ /^\d+$/) {
1026                 die "revision argument: $r not understood by git-svn\n";
1027         }
1028         my %ed_opts = ( r => $r,
1029                         log => $_message,
1030                         ra => $ra,
1031                         tree_a => $ta,
1032                         tree_b => $tb,
1033                         editor_cb => sub { print "Committed r$_[0]\n" },
1034                         svn_path => $svn_path );
1035         if (!SVN::Git::Editor->new(\%ed_opts)->apply_diff) {
1036                 print "No changes\n$ta == $tb\n";
1037         }
1040 sub escape_uri_only {
1041         my ($uri) = @_;
1042         my @tmp;
1043         foreach (split m{/}, $uri) {
1044                 s/([^~\w.%+-]|%(?![a-fA-F0-9]{2}))/sprintf("%%%02X",ord($1))/eg;
1045                 push @tmp, $_;
1046         }
1047         join('/', @tmp);
1050 sub escape_url {
1051         my ($url) = @_;
1052         if ($url =~ m#^([^:]+)://([^/]*)(.*)$#) {
1053                 my ($scheme, $domain, $uri) = ($1, $2, escape_uri_only($3));
1054                 $url = "$scheme://$domain$uri";
1055         }
1056         $url;
1059 sub cmd_info {
1060         my $path = canonicalize_path(defined($_[0]) ? $_[0] : ".");
1061         my $fullpath = canonicalize_path($cmd_dir_prefix . $path);
1062         if (exists $_[1]) {
1063                 die "Too many arguments specified\n";
1064         }
1066         my ($file_type, $diff_status) = find_file_type_and_diff_status($path);
1068         if (!$file_type && !$diff_status) {
1069                 print STDERR "svn: '$path' is not under version control\n";
1070                 exit 1;
1071         }
1073         my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
1074         unless ($gs) {
1075                 die "Unable to determine upstream SVN information from ",
1076                     "working tree history\n";
1077         }
1079         # canonicalize_path() will return "" to make libsvn 1.5.x happy,
1080         $path = "." if $path eq "";
1082         my $full_url = $url . ($fullpath eq "" ? "" : "/$fullpath");
1084         if ($_url) {
1085                 print escape_url($full_url), "\n";
1086                 return;
1087         }
1089         my $result = "Path: $path\n";
1090         $result .= "Name: " . basename($path) . "\n" if $file_type ne "dir";
1091         $result .= "URL: " . escape_url($full_url) . "\n";
1093         eval {
1094                 my $repos_root = $gs->repos_root;
1095                 Git::SVN::remove_username($repos_root);
1096                 $result .= "Repository Root: " . escape_url($repos_root) . "\n";
1097         };
1098         if ($@) {
1099                 $result .= "Repository Root: (offline)\n";
1100         }
1101         $result .= "Repository UUID: $uuid\n" unless $diff_status eq "A" &&
1102                 ($SVN::Core::VERSION le '1.5.4' || $file_type ne "dir");
1103         $result .= "Revision: " . ($diff_status eq "A" ? 0 : $rev) . "\n";
1105         $result .= "Node Kind: " .
1106                    ($file_type eq "dir" ? "directory" : "file") . "\n";
1108         my $schedule = $diff_status eq "A"
1109                        ? "add"
1110                        : ($diff_status eq "D" ? "delete" : "normal");
1111         $result .= "Schedule: $schedule\n";
1113         if ($diff_status eq "A") {
1114                 print $result, "\n";
1115                 return;
1116         }
1118         my ($lc_author, $lc_rev, $lc_date_utc);
1119         my @args = Git::SVN::Log::git_svn_log_cmd($rev, $rev, "--", $fullpath);
1120         my $log = command_output_pipe(@args);
1121         my $esc_color = qr/(?:\033\[(?:(?:\d+;)*\d*)?m)*/;
1122         while (<$log>) {
1123                 if (/^${esc_color}author (.+) <[^>]+> (\d+) ([\-\+]?\d+)$/o) {
1124                         $lc_author = $1;
1125                         $lc_date_utc = Git::SVN::Log::parse_git_date($2, $3);
1126                 } elsif (/^${esc_color}    (git-svn-id:.+)$/o) {
1127                         (undef, $lc_rev, undef) = ::extract_metadata($1);
1128                 }
1129         }
1130         close $log;
1132         Git::SVN::Log::set_local_timezone();
1134         $result .= "Last Changed Author: $lc_author\n";
1135         $result .= "Last Changed Rev: $lc_rev\n";
1136         $result .= "Last Changed Date: " .
1137                    Git::SVN::Log::format_svn_date($lc_date_utc) . "\n";
1139         if ($file_type ne "dir") {
1140                 my $text_last_updated_date =
1141                     ($diff_status eq "D" ? $lc_date_utc : (stat $path)[9]);
1142                 $result .=
1143                     "Text Last Updated: " .
1144                     Git::SVN::Log::format_svn_date($text_last_updated_date) .
1145                     "\n";
1146                 my $checksum;
1147                 if ($diff_status eq "D") {
1148                         my ($fh, $ctx) =
1149                             command_output_pipe(qw(cat-file blob), "HEAD:$path");
1150                         if ($file_type eq "link") {
1151                                 my $file_name = <$fh>;
1152                                 $checksum = md5sum("link $file_name");
1153                         } else {
1154                                 $checksum = md5sum($fh);
1155                         }
1156                         command_close_pipe($fh, $ctx);
1157                 } elsif ($file_type eq "link") {
1158                         my $file_name =
1159                             command(qw(cat-file blob), "HEAD:$path");
1160                         $checksum =
1161                             md5sum("link " . $file_name);
1162                 } else {
1163                         open FILE, "<", $path or die $!;
1164                         $checksum = md5sum(\*FILE);
1165                         close FILE or die $!;
1166                 }
1167                 $result .= "Checksum: " . $checksum . "\n";
1168         }
1170         print $result, "\n";
1173 sub cmd_reset {
1174         my $target = shift || $_revision or die "SVN revision required\n";
1175         $target = $1 if $target =~ /^r(\d+)$/;
1176         $target =~ /^\d+$/ or die "Numeric SVN revision expected\n";
1177         my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
1178         unless ($gs) {
1179                 die "Unable to determine upstream SVN information from ".
1180                     "history\n";
1181         }
1182         my ($r, $c) = $gs->find_rev_before($target, not $_fetch_parent);
1183         $gs->rev_map_set($r, $c, 'reset', $uuid);
1184         print "r$r = $c ($gs->{ref_id})\n";
1187 sub cmd_gc {
1188         if (!$can_compress) {
1189                 warn "Compress::Zlib could not be found; unhandled.log " .
1190                      "files will not be compressed.\n";
1191         }
1192         find({ wanted => \&gc_directory, no_chdir => 1}, "$ENV{GIT_DIR}/svn");
1195 ########################### utility functions #########################
1197 sub rebase_cmd {
1198         my @cmd = qw/rebase/;
1199         push @cmd, '-v' if $_verbose;
1200         push @cmd, qw/--merge/ if $_merge;
1201         push @cmd, "--strategy=$_strategy" if $_strategy;
1202         @cmd;
1205 sub post_fetch_checkout {
1206         return if $_no_checkout;
1207         my $gs = $Git::SVN::_head or return;
1208         return if verify_ref('refs/heads/master^0');
1210         # look for "trunk" ref if it exists
1211         my $remote = Git::SVN::read_all_remotes()->{$gs->{repo_id}};
1212         my $fetch = $remote->{fetch};
1213         if ($fetch) {
1214                 foreach my $p (keys %$fetch) {
1215                         basename($fetch->{$p}) eq 'trunk' or next;
1216                         $gs = Git::SVN->new($fetch->{$p}, $gs->{repo_id}, $p);
1217                         last;
1218                 }
1219         }
1221         my $valid_head = verify_ref('HEAD^0');
1222         command_noisy(qw(update-ref refs/heads/master), $gs->refname);
1223         return if ($valid_head || !verify_ref('HEAD^0'));
1225         return if $ENV{GIT_DIR} !~ m#^(?:.*/)?\.git$#;
1226         my $index = $ENV{GIT_INDEX_FILE} || "$ENV{GIT_DIR}/index";
1227         return if -f $index;
1229         return if command_oneline(qw/rev-parse --is-inside-work-tree/) eq 'false';
1230         return if command_oneline(qw/rev-parse --is-inside-git-dir/) eq 'true';
1231         command_noisy(qw/read-tree -m -u -v HEAD HEAD/);
1232         print STDERR "Checked out HEAD:\n  ",
1233                      $gs->full_url, " r", $gs->last_rev, "\n";
1234         $gs->mkemptydirs($gs->last_rev);
1237 sub complete_svn_url {
1238         my ($url, $path) = @_;
1239         $path =~ s#/+$##;
1240         if ($path !~ m#^[a-z\+]+://#) {
1241                 if (!defined $url || $url !~ m#^[a-z\+]+://#) {
1242                         fatal("E: '$path' is not a complete URL ",
1243                               "and a separate URL is not specified");
1244                 }
1245                 return ($url, $path);
1246         }
1247         return ($path, '');
1250 sub complete_url_ls_init {
1251         my ($ra, $repo_path, $switch, $pfx) = @_;
1252         unless ($repo_path) {
1253                 print STDERR "W: $switch not specified\n";
1254                 return;
1255         }
1256         $repo_path =~ s#/+$##;
1257         if ($repo_path =~ m#^[a-z\+]+://#) {
1258                 $ra = Git::SVN::Ra->new($repo_path);
1259                 $repo_path = '';
1260         } else {
1261                 $repo_path =~ s#^/+##;
1262                 unless ($ra) {
1263                         fatal("E: '$repo_path' is not a complete URL ",
1264                               "and a separate URL is not specified");
1265                 }
1266         }
1267         my $url = $ra->{url};
1268         my $gs = Git::SVN->init($url, undef, undef, undef, 1);
1269         my $k = "svn-remote.$gs->{repo_id}.url";
1270         my $orig_url = eval { command_oneline(qw/config --get/, $k) };
1271         if ($orig_url && ($orig_url ne $gs->{url})) {
1272                 die "$k already set: $orig_url\n",
1273                     "wanted to set to: $gs->{url}\n";
1274         }
1275         command_oneline('config', $k, $gs->{url}) unless $orig_url;
1276         my $remote_path = "$gs->{path}/$repo_path";
1277         $remote_path =~ s{%([0-9A-F]{2})}{chr hex($1)}ieg;
1278         $remote_path =~ s#/+#/#g;
1279         $remote_path =~ s#^/##g;
1280         $remote_path .= "/*" if $remote_path !~ /\*/;
1281         my ($n) = ($switch =~ /^--(\w+)/);
1282         if (length $pfx && $pfx !~ m#/$#) {
1283                 die "--prefix='$pfx' must have a trailing slash '/'\n";
1284         }
1285         command_noisy('config',
1286                       '--add',
1287                       "svn-remote.$gs->{repo_id}.$n",
1288                       "$remote_path:refs/remotes/$pfx*" .
1289                         ('/*' x (($remote_path =~ tr/*/*/) - 1)) );
1292 sub verify_ref {
1293         my ($ref) = @_;
1294         eval { command_oneline([ 'rev-parse', '--verify', $ref ],
1295                                { STDERR => 0 }); };
1298 sub get_tree_from_treeish {
1299         my ($treeish) = @_;
1300         # $treeish can be a symbolic ref, too:
1301         my $type = command_oneline(qw/cat-file -t/, $treeish);
1302         my $expected;
1303         while ($type eq 'tag') {
1304                 ($treeish, $type) = command(qw/cat-file tag/, $treeish);
1305         }
1306         if ($type eq 'commit') {
1307                 $expected = (grep /^tree /, command(qw/cat-file commit/,
1308                                                     $treeish))[0];
1309                 ($expected) = ($expected =~ /^tree ($sha1)$/o);
1310                 die "Unable to get tree from $treeish\n" unless $expected;
1311         } elsif ($type eq 'tree') {
1312                 $expected = $treeish;
1313         } else {
1314                 die "$treeish is a $type, expected tree, tag or commit\n";
1315         }
1316         return $expected;
1319 sub get_commit_entry {
1320         my ($treeish) = shift;
1321         my %log_entry = ( log => '', tree => get_tree_from_treeish($treeish) );
1322         my $commit_editmsg = "$ENV{GIT_DIR}/COMMIT_EDITMSG";
1323         my $commit_msg = "$ENV{GIT_DIR}/COMMIT_MSG";
1324         open my $log_fh, '>', $commit_editmsg or croak $!;
1326         my $type = command_oneline(qw/cat-file -t/, $treeish);
1327         if ($type eq 'commit' || $type eq 'tag') {
1328                 my ($msg_fh, $ctx) = command_output_pipe('cat-file',
1329                                                          $type, $treeish);
1330                 my $in_msg = 0;
1331                 my $author;
1332                 my $saw_from = 0;
1333                 my $msgbuf = "";
1334                 while (<$msg_fh>) {
1335                         if (!$in_msg) {
1336                                 $in_msg = 1 if (/^\s*$/);
1337                                 $author = $1 if (/^author (.*>)/);
1338                         } elsif (/^git-svn-id: /) {
1339                                 # skip this for now, we regenerate the
1340                                 # correct one on re-fetch anyways
1341                                 # TODO: set *:merge properties or like...
1342                         } else {
1343                                 if (/^From:/ || /^Signed-off-by:/) {
1344                                         $saw_from = 1;
1345                                 }
1346                                 $msgbuf .= $_;
1347                         }
1348                 }
1349                 $msgbuf =~ s/\s+$//s;
1350                 if ($Git::SVN::_add_author_from && defined($author)
1351                     && !$saw_from) {
1352                         $msgbuf .= "\n\nFrom: $author";
1353                 }
1354                 print $log_fh $msgbuf or croak $!;
1355                 command_close_pipe($msg_fh, $ctx);
1356         }
1357         close $log_fh or croak $!;
1359         if ($_edit || ($type eq 'tree')) {
1360                 chomp(my $editor = command_oneline(qw(var GIT_EDITOR)));
1361                 system('sh', '-c', $editor.' "$@"', $editor, $commit_editmsg);
1362         }
1363         rename $commit_editmsg, $commit_msg or croak $!;
1364         {
1365                 require Encode;
1366                 # SVN requires messages to be UTF-8 when entering the repo
1367                 local $/;
1368                 open $log_fh, '<', $commit_msg or croak $!;
1369                 binmode $log_fh;
1370                 chomp($log_entry{log} = <$log_fh>);
1372                 my $enc = Git::config('i18n.commitencoding') || 'UTF-8';
1373                 my $msg = $log_entry{log};
1375                 eval { $msg = Encode::decode($enc, $msg, 1) };
1376                 if ($@) {
1377                         die "Could not decode as $enc:\n", $msg,
1378                             "\nPerhaps you need to set i18n.commitencoding\n";
1379                 }
1381                 eval { $msg = Encode::encode('UTF-8', $msg, 1) };
1382                 die "Could not encode as UTF-8:\n$msg\n" if $@;
1384                 $log_entry{log} = $msg;
1386                 close $log_fh or croak $!;
1387         }
1388         unlink $commit_msg;
1389         \%log_entry;
1392 sub s_to_file {
1393         my ($str, $file, $mode) = @_;
1394         open my $fd,'>',$file or croak $!;
1395         print $fd $str,"\n" or croak $!;
1396         close $fd or croak $!;
1397         chmod ($mode &~ umask, $file) if (defined $mode);
1400 sub file_to_s {
1401         my $file = shift;
1402         open my $fd,'<',$file or croak "$!: file: $file\n";
1403         local $/;
1404         my $ret = <$fd>;
1405         close $fd or croak $!;
1406         $ret =~ s/\s*$//s;
1407         return $ret;
1410 # '<svn username> = real-name <email address>' mapping based on git-svnimport:
1411 sub load_authors {
1412         open my $authors, '<', $_authors or die "Can't open $_authors $!\n";
1413         my $log = $cmd eq 'log';
1414         while (<$authors>) {
1415                 chomp;
1416                 next unless /^(.+?|\(no author\))\s*=\s*(.+?)\s*<(.+)>\s*$/;
1417                 my ($user, $name, $email) = ($1, $2, $3);
1418                 if ($log) {
1419                         $Git::SVN::Log::rusers{"$name <$email>"} = $user;
1420                 } else {
1421                         $users{$user} = [$name, $email];
1422                 }
1423         }
1424         close $authors or croak $!;
1427 # convert GetOpt::Long specs for use by git-config
1428 sub read_git_config {
1429         my $opts = shift;
1430         my @config_only;
1431         foreach my $o (keys %$opts) {
1432                 # if we have mixedCase and a long option-only, then
1433                 # it's a config-only variable that we don't need for
1434                 # the command-line.
1435                 push @config_only, $o if ($o =~ /[A-Z]/ && $o =~ /^[a-z]+$/i);
1436                 my $v = $opts->{$o};
1437                 my ($key) = ($o =~ /^([a-zA-Z\-]+)/);
1438                 $key =~ s/-//g;
1439                 my $arg = 'git config';
1440                 $arg .= ' --int' if ($o =~ /[:=]i$/);
1441                 $arg .= ' --bool' if ($o !~ /[:=][sfi]$/);
1442                 if (ref $v eq 'ARRAY') {
1443                         chomp(my @tmp = `$arg --get-all svn.$key`);
1444                         @$v = @tmp if @tmp;
1445                 } else {
1446                         chomp(my $tmp = `$arg --get svn.$key`);
1447                         if ($tmp && !($arg =~ / --bool/ && $tmp eq 'false')) {
1448                                 $$v = $tmp;
1449                         }
1450                 }
1451         }
1452         delete @$opts{@config_only} if @config_only;
1455 sub extract_metadata {
1456         my $id = shift or return (undef, undef, undef);
1457         my ($url, $rev, $uuid) = ($id =~ /^\s*git-svn-id:\s+(.*)\@(\d+)
1458                                                         \s([a-f\d\-]+)$/ix);
1459         if (!defined $rev || !$uuid || !$url) {
1460                 # some of the original repositories I made had
1461                 # identifiers like this:
1462                 ($rev, $uuid) = ($id =~/^\s*git-svn-id:\s(\d+)\@([a-f\d\-]+)/i);
1463         }
1464         return ($url, $rev, $uuid);
1467 sub cmt_metadata {
1468         return extract_metadata((grep(/^git-svn-id: /,
1469                 command(qw/cat-file commit/, shift)))[-1]);
1472 sub cmt_sha2rev_batch {
1473         my %s2r;
1474         my ($pid, $in, $out, $ctx) = command_bidi_pipe(qw/cat-file --batch/);
1475         my $list = shift;
1477         foreach my $sha (@{$list}) {
1478                 my $first = 1;
1479                 my $size = 0;
1480                 print $out $sha, "\n";
1482                 while (my $line = <$in>) {
1483                         if ($first && $line =~ /^[[:xdigit:]]{40}\smissing$/) {
1484                                 last;
1485                         } elsif ($first &&
1486                                $line =~ /^[[:xdigit:]]{40}\scommit\s(\d+)$/) {
1487                                 $first = 0;
1488                                 $size = $1;
1489                                 next;
1490                         } elsif ($line =~ /^(git-svn-id: )/) {
1491                                 my (undef, $rev, undef) =
1492                                                       extract_metadata($line);
1493                                 $s2r{$sha} = $rev;
1494                         }
1496                         $size -= length($line);
1497                         last if ($size == 0);
1498                 }
1499         }
1501         command_close_bidi_pipe($pid, $in, $out, $ctx);
1503         return \%s2r;
1506 sub working_head_info {
1507         my ($head, $refs) = @_;
1508         my @args = ('log', '--no-color', '--first-parent', '--pretty=medium');
1509         my ($fh, $ctx) = command_output_pipe(@args, $head);
1510         my $hash;
1511         my %max;
1512         while (<$fh>) {
1513                 if ( m{^commit ($::sha1)$} ) {
1514                         unshift @$refs, $hash if $hash and $refs;
1515                         $hash = $1;
1516                         next;
1517                 }
1518                 next unless s{^\s*(git-svn-id:)}{$1};
1519                 my ($url, $rev, $uuid) = extract_metadata($_);
1520                 if (defined $url && defined $rev) {
1521                         next if $max{$url} and $max{$url} < $rev;
1522                         if (my $gs = Git::SVN->find_by_url($url)) {
1523                                 my $c = $gs->rev_map_get($rev, $uuid);
1524                                 if ($c && $c eq $hash) {
1525                                         close $fh; # break the pipe
1526                                         return ($url, $rev, $uuid, $gs);
1527                                 } else {
1528                                         $max{$url} ||= $gs->rev_map_max;
1529                                 }
1530                         }
1531                 }
1532         }
1533         command_close_pipe($fh, $ctx);
1534         (undef, undef, undef, undef);
1537 sub read_commit_parents {
1538         my ($parents, $c) = @_;
1539         chomp(my $p = command_oneline(qw/rev-list --parents -1/, $c));
1540         $p =~ s/^($c)\s*// or die "rev-list --parents -1 $c failed!\n";
1541         @{$parents->{$c}} = split(/ /, $p);
1544 sub linearize_history {
1545         my ($gs, $refs) = @_;
1546         my %parents;
1547         foreach my $c (@$refs) {
1548                 read_commit_parents(\%parents, $c);
1549         }
1551         my @linear_refs;
1552         my %skip = ();
1553         my $last_svn_commit = $gs->last_commit;
1554         foreach my $c (reverse @$refs) {
1555                 next if $c eq $last_svn_commit;
1556                 last if $skip{$c};
1558                 unshift @linear_refs, $c;
1559                 $skip{$c} = 1;
1561                 # we only want the first parent to diff against for linear
1562                 # history, we save the rest to inject when we finalize the
1563                 # svn commit
1564                 my $fp_a = verify_ref("$c~1");
1565                 my $fp_b = shift @{$parents{$c}} if $parents{$c};
1566                 if (!$fp_a || !$fp_b) {
1567                         die "Commit $c\n",
1568                             "has no parent commit, and therefore ",
1569                             "nothing to diff against.\n",
1570                             "You should be working from a repository ",
1571                             "originally created by git-svn\n";
1572                 }
1573                 if ($fp_a ne $fp_b) {
1574                         die "$c~1 = $fp_a, however parsing commit $c ",
1575                             "revealed that:\n$c~1 = $fp_b\nBUG!\n";
1576                 }
1578                 foreach my $p (@{$parents{$c}}) {
1579                         $skip{$p} = 1;
1580                 }
1581         }
1582         (\@linear_refs, \%parents);
1585 sub find_file_type_and_diff_status {
1586         my ($path) = @_;
1587         return ('dir', '') if $path eq '';
1589         my $diff_output =
1590             command_oneline(qw(diff --cached --name-status --), $path) || "";
1591         my $diff_status = (split(' ', $diff_output))[0] || "";
1593         my $ls_tree = command_oneline(qw(ls-tree HEAD), $path) || "";
1595         return (undef, undef) if !$diff_status && !$ls_tree;
1597         if ($diff_status eq "A") {
1598                 return ("link", $diff_status) if -l $path;
1599                 return ("dir", $diff_status) if -d $path;
1600                 return ("file", $diff_status);
1601         }
1603         my $mode = (split(' ', $ls_tree))[0] || "";
1605         return ("link", $diff_status) if $mode eq "120000";
1606         return ("dir", $diff_status) if $mode eq "040000";
1607         return ("file", $diff_status);
1610 sub md5sum {
1611         my $arg = shift;
1612         my $ref = ref $arg;
1613         my $md5 = Digest::MD5->new();
1614         if ($ref eq 'GLOB' || $ref eq 'IO::File' || $ref eq 'File::Temp') {
1615                 $md5->addfile($arg) or croak $!;
1616         } elsif ($ref eq 'SCALAR') {
1617                 $md5->add($$arg) or croak $!;
1618         } elsif (!$ref) {
1619                 $md5->add($arg) or croak $!;
1620         } else {
1621                 ::fatal "Can't provide MD5 hash for unknown ref type: '", $ref, "'";
1622         }
1623         return $md5->hexdigest();
1626 sub gc_directory {
1627         if ($can_compress && -f $_ && basename($_) eq "unhandled.log") {
1628                 my $out_filename = $_ . ".gz";
1629                 open my $in_fh, "<", $_ or die "Unable to open $_: $!\n";
1630                 binmode $in_fh;
1631                 my $gz = Compress::Zlib::gzopen($out_filename, "ab") or
1632                                 die "Unable to open $out_filename: $!\n";
1634                 my $res;
1635                 while ($res = sysread($in_fh, my $str, 1024)) {
1636                         $gz->gzwrite($str) or
1637                                 die "Unable to write: ".$gz->gzerror()."!\n";
1638                 }
1639                 unlink $_ or die "unlink $File::Find::name: $!\n";
1640         } elsif (-f $_ && basename($_) eq "index") {
1641                 unlink $_ or die "unlink $_: $!\n";
1642         }
1645 package Git::SVN;
1646 use strict;
1647 use warnings;
1648 use Fcntl qw/:DEFAULT :seek/;
1649 use constant rev_map_fmt => 'NH40';
1650 use vars qw/$default_repo_id $default_ref_id $_no_metadata $_follow_parent
1651             $_repack $_repack_flags $_use_svm_props $_head
1652             $_use_svnsync_props $no_reuse_existing $_minimize_url
1653             $_use_log_author $_add_author_from $_localtime/;
1654 use Carp qw/croak/;
1655 use File::Path qw/mkpath/;
1656 use File::Copy qw/copy/;
1657 use IPC::Open3;
1658 use Memoize;  # core since 5.8.0, Jul 2002
1660 my ($_gc_nr, $_gc_period);
1662 # properties that we do not log:
1663 my %SKIP_PROP;
1664 BEGIN {
1665         %SKIP_PROP = map { $_ => 1 } qw/svn:wc:ra_dav:version-url
1666                                         svn:special svn:executable
1667                                         svn:entry:committed-rev
1668                                         svn:entry:last-author
1669                                         svn:entry:uuid
1670                                         svn:entry:committed-date/;
1672         # some options are read globally, but can be overridden locally
1673         # per [svn-remote "..."] section.  Command-line options will *NOT*
1674         # override options set in an [svn-remote "..."] section
1675         no strict 'refs';
1676         for my $option (qw/follow_parent no_metadata use_svm_props
1677                            use_svnsync_props/) {
1678                 my $key = $option;
1679                 $key =~ tr/_//d;
1680                 my $prop = "-$option";
1681                 *$option = sub {
1682                         my ($self) = @_;
1683                         return $self->{$prop} if exists $self->{$prop};
1684                         my $k = "svn-remote.$self->{repo_id}.$key";
1685                         eval { command_oneline(qw/config --get/, $k) };
1686                         if ($@) {
1687                                 $self->{$prop} = ${"Git::SVN::_$option"};
1688                         } else {
1689                                 my $v = command_oneline(qw/config --bool/,$k);
1690                                 $self->{$prop} = $v eq 'false' ? 0 : 1;
1691                         }
1692                         return $self->{$prop};
1693                 }
1694         }
1698 my (%LOCKFILES, %INDEX_FILES);
1699 END {
1700         unlink keys %LOCKFILES if %LOCKFILES;
1701         unlink keys %INDEX_FILES if %INDEX_FILES;
1704 sub resolve_local_globs {
1705         my ($url, $fetch, $glob_spec) = @_;
1706         return unless defined $glob_spec;
1707         my $ref = $glob_spec->{ref};
1708         my $path = $glob_spec->{path};
1709         foreach (command(qw#for-each-ref --format=%(refname) refs/#)) {
1710                 next unless m#^$ref->{regex}$#;
1711                 my $p = $1;
1712                 my $pathname = desanitize_refname($path->full_path($p));
1713                 my $refname = desanitize_refname($ref->full_path($p));
1714                 if (my $existing = $fetch->{$pathname}) {
1715                         if ($existing ne $refname) {
1716                                 die "Refspec conflict:\n",
1717                                     "existing: $existing\n",
1718                                     " globbed: $refname\n";
1719                         }
1720                         my $u = (::cmt_metadata("$refname"))[0];
1721                         $u =~ s!^\Q$url\E(/|$)!! or die
1722                           "$refname: '$url' not found in '$u'\n";
1723                         if ($pathname ne $u) {
1724                                 warn "W: Refspec glob conflict ",
1725                                      "(ref: $refname):\n",
1726                                      "expected path: $pathname\n",
1727                                      "    real path: $u\n",
1728                                      "Continuing ahead with $u\n";
1729                                 next;
1730                         }
1731                 } else {
1732                         $fetch->{$pathname} = $refname;
1733                 }
1734         }
1737 sub parse_revision_argument {
1738         my ($base, $head) = @_;
1739         if (!defined $::_revision || $::_revision eq 'BASE:HEAD') {
1740                 return ($base, $head);
1741         }
1742         return ($1, $2) if ($::_revision =~ /^(\d+):(\d+)$/);
1743         return ($::_revision, $::_revision) if ($::_revision =~ /^\d+$/);
1744         return ($head, $head) if ($::_revision eq 'HEAD');
1745         return ($base, $1) if ($::_revision =~ /^BASE:(\d+)$/);
1746         return ($1, $head) if ($::_revision =~ /^(\d+):HEAD$/);
1747         die "revision argument: $::_revision not understood by git-svn\n";
1750 sub fetch_all {
1751         my ($repo_id, $remotes) = @_;
1752         if (ref $repo_id) {
1753                 my $gs = $repo_id;
1754                 $repo_id = undef;
1755                 $repo_id = $gs->{repo_id};
1756         }
1757         $remotes ||= read_all_remotes();
1758         my $remote = $remotes->{$repo_id} or
1759                      die "[svn-remote \"$repo_id\"] unknown\n";
1760         my $fetch = $remote->{fetch};
1761         my $url = $remote->{url} or die "svn-remote.$repo_id.url not defined\n";
1762         my (@gs, @globs);
1763         my $ra = Git::SVN::Ra->new($url);
1764         my $uuid = $ra->get_uuid;
1765         my $head = $ra->get_latest_revnum;
1767         # ignore errors, $head revision may not even exist anymore
1768         eval { $ra->get_log("", $head, 0, 1, 0, 1, sub { $head = $_[1] }) };
1769         warn "W: $@\n" if $@;
1771         my $base = defined $fetch ? $head : 0;
1773         # read the max revs for wildcard expansion (branches/*, tags/*)
1774         foreach my $t (qw/branches tags/) {
1775                 defined $remote->{$t} or next;
1776                 push @globs, @{$remote->{$t}};
1778                 my $max_rev = eval { tmp_config(qw/--int --get/,
1779                                          "svn-remote.$repo_id.${t}-maxRev") };
1780                 if (defined $max_rev && ($max_rev < $base)) {
1781                         $base = $max_rev;
1782                 } elsif (!defined $max_rev) {
1783                         $base = 0;
1784                 }
1785         }
1787         if ($fetch) {
1788                 foreach my $p (sort keys %$fetch) {
1789                         my $gs = Git::SVN->new($fetch->{$p}, $repo_id, $p);
1790                         my $lr = $gs->rev_map_max;
1791                         if (defined $lr) {
1792                                 $base = $lr if ($lr < $base);
1793                         }
1794                         push @gs, $gs;
1795                 }
1796         }
1798         ($base, $head) = parse_revision_argument($base, $head);
1799         $ra->gs_fetch_loop_common($base, $head, \@gs, \@globs);
1802 sub read_all_remotes {
1803         my $r = {};
1804         my $use_svm_props = eval { command_oneline(qw/config --bool
1805             svn.useSvmProps/) };
1806         $use_svm_props = $use_svm_props eq 'true' if $use_svm_props;
1807         my $svn_refspec = qr{\s*(.*?)\s*:\s*(.+?)\s*};
1808         foreach (grep { s/^svn-remote\.// } command(qw/config -l/)) {
1809                 if (m!^(.+)\.fetch=$svn_refspec$!) {
1810                         my ($remote, $local_ref, $remote_ref) = ($1, $2, $3);
1811                         die("svn-remote.$remote: remote ref '$remote_ref' "
1812                             . "must start with 'refs/'\n")
1813                                 unless $remote_ref =~ m{^refs/};
1814                         $r->{$remote}->{fetch}->{$local_ref} = $remote_ref;
1815                         $r->{$remote}->{svm} = {} if $use_svm_props;
1816                 } elsif (m!^(.+)\.usesvmprops=\s*(.*)\s*$!) {
1817                         $r->{$1}->{svm} = {};
1818                 } elsif (m!^(.+)\.url=\s*(.*)\s*$!) {
1819                         $r->{$1}->{url} = $2;
1820                 } elsif (m!^(.+)\.(branches|tags)=$svn_refspec$!) {
1821                         my ($remote, $t, $local_ref, $remote_ref) =
1822                                                              ($1, $2, $3, $4);
1823                         die("svn-remote.$remote: remote ref '$remote_ref' ($t) "
1824                             . "must start with 'refs/'\n")
1825                                 unless $remote_ref =~ m{^refs/};
1826                         my $rs = {
1827                             t => $t,
1828                             remote => $remote,
1829                             path => Git::SVN::GlobSpec->new($local_ref, 1),
1830                             ref => Git::SVN::GlobSpec->new($remote_ref, 0) };
1831                         if (length($rs->{ref}->{right}) != 0) {
1832                                 die "The '*' glob character must be the last ",
1833                                     "character of '$remote_ref'\n";
1834                         }
1835                         push @{ $r->{$remote}->{$t} }, $rs;
1836                 }
1837         }
1839         map {
1840                 if (defined $r->{$_}->{svm}) {
1841                         my $svm;
1842                         eval {
1843                                 my $section = "svn-remote.$_";
1844                                 $svm = {
1845                                         source => tmp_config('--get',
1846                                             "$section.svm-source"),
1847                                         replace => tmp_config('--get',
1848                                             "$section.svm-replace"),
1849                                 }
1850                         };
1851                         $r->{$_}->{svm} = $svm;
1852                 }
1853         } keys %$r;
1855         $r;
1858 sub init_vars {
1859         $_gc_nr = $_gc_period = 1000;
1860         if (defined $_repack || defined $_repack_flags) {
1861                warn "Repack options are obsolete; they have no effect.\n";
1862         }
1865 sub verify_remotes_sanity {
1866         return unless -d $ENV{GIT_DIR};
1867         my %seen;
1868         foreach (command(qw/config -l/)) {
1869                 if (m!^svn-remote\.(?:.+)\.fetch=.*:refs/remotes/(\S+)\s*$!) {
1870                         if ($seen{$1}) {
1871                                 die "Remote ref refs/remote/$1 is tracked by",
1872                                     "\n  \"$_\"\nand\n  \"$seen{$1}\"\n",
1873                                     "Please resolve this ambiguity in ",
1874                                     "your git configuration file before ",
1875                                     "continuing\n";
1876                         }
1877                         $seen{$1} = $_;
1878                 }
1879         }
1882 sub find_existing_remote {
1883         my ($url, $remotes) = @_;
1884         return undef if $no_reuse_existing;
1885         my $existing;
1886         foreach my $repo_id (keys %$remotes) {
1887                 my $u = $remotes->{$repo_id}->{url} or next;
1888                 next if $u ne $url;
1889                 $existing = $repo_id;
1890                 last;
1891         }
1892         $existing;
1895 sub init_remote_config {
1896         my ($self, $url, $no_write) = @_;
1897         $url =~ s!/+$!!; # strip trailing slash
1898         my $r = read_all_remotes();
1899         my $existing = find_existing_remote($url, $r);
1900         if ($existing) {
1901                 unless ($no_write) {
1902                         print STDERR "Using existing ",
1903                                      "[svn-remote \"$existing\"]\n";
1904                 }
1905                 $self->{repo_id} = $existing;
1906         } elsif ($_minimize_url) {
1907                 my $min_url = Git::SVN::Ra->new($url)->minimize_url;
1908                 $existing = find_existing_remote($min_url, $r);
1909                 if ($existing) {
1910                         unless ($no_write) {
1911                                 print STDERR "Using existing ",
1912                                              "[svn-remote \"$existing\"]\n";
1913                         }
1914                         $self->{repo_id} = $existing;
1915                 }
1916                 if ($min_url ne $url) {
1917                         unless ($no_write) {
1918                                 print STDERR "Using higher level of URL: ",
1919                                              "$url => $min_url\n";
1920                         }
1921                         my $old_path = $self->{path};
1922                         $self->{path} = $url;
1923                         $self->{path} =~ s!^\Q$min_url\E(/|$)!!;
1924                         if (length $old_path) {
1925                                 $self->{path} .= "/$old_path";
1926                         }
1927                         $url = $min_url;
1928                 }
1929         }
1930         my $orig_url;
1931         if (!$existing) {
1932                 # verify that we aren't overwriting anything:
1933                 $orig_url = eval {
1934                         command_oneline('config', '--get',
1935                                         "svn-remote.$self->{repo_id}.url")
1936                 };
1937                 if ($orig_url && ($orig_url ne $url)) {
1938                         die "svn-remote.$self->{repo_id}.url already set: ",
1939                             "$orig_url\nwanted to set to: $url\n";
1940                 }
1941         }
1942         my ($xrepo_id, $xpath) = find_ref($self->refname);
1943         if (!$no_write && defined $xpath) {
1944                 die "svn-remote.$xrepo_id.fetch already set to track ",
1945                     "$xpath:", $self->refname, "\n";
1946         }
1947         unless ($no_write) {
1948                 command_noisy('config',
1949                               "svn-remote.$self->{repo_id}.url", $url);
1950                 $self->{path} =~ s{^/}{};
1951                 $self->{path} =~ s{%([0-9A-F]{2})}{chr hex($1)}ieg;
1952                 command_noisy('config', '--add',
1953                               "svn-remote.$self->{repo_id}.fetch",
1954                               "$self->{path}:".$self->refname);
1955         }
1956         $self->{url} = $url;
1959 sub find_by_url { # repos_root and, path are optional
1960         my ($class, $full_url, $repos_root, $path) = @_;
1962         return undef unless defined $full_url;
1963         remove_username($full_url);
1964         remove_username($repos_root) if defined $repos_root;
1965         my $remotes = read_all_remotes();
1966         if (defined $full_url && defined $repos_root && !defined $path) {
1967                 $path = $full_url;
1968                 $path =~ s#^\Q$repos_root\E(?:/|$)##;
1969         }
1970         foreach my $repo_id (keys %$remotes) {
1971                 my $u = $remotes->{$repo_id}->{url} or next;
1972                 remove_username($u);
1973                 next if defined $repos_root && $repos_root ne $u;
1975                 my $fetch = $remotes->{$repo_id}->{fetch} || {};
1976                 foreach my $t (qw/branches tags/) {
1977                         foreach my $globspec (@{$remotes->{$repo_id}->{$t}}) {
1978                                 resolve_local_globs($u, $fetch, $globspec);
1979                         }
1980                 }
1981                 my $p = $path;
1982                 my $rwr = rewrite_root({repo_id => $repo_id});
1983                 my $svm = $remotes->{$repo_id}->{svm}
1984                         if defined $remotes->{$repo_id}->{svm};
1985                 unless (defined $p) {
1986                         $p = $full_url;
1987                         my $z = $u;
1988                         my $prefix = '';
1989                         if ($rwr) {
1990                                 $z = $rwr;
1991                                 remove_username($z);
1992                         } elsif (defined $svm) {
1993                                 $z = $svm->{source};
1994                                 $prefix = $svm->{replace};
1995                                 $prefix =~ s#^\Q$u\E(?:/|$)##;
1996                                 $prefix =~ s#/$##;
1997                         }
1998                         $p =~ s#^\Q$z\E(?:/|$)#$prefix# or next;
1999                 }
2000                 foreach my $f (keys %$fetch) {
2001                         next if $f ne $p;
2002                         return Git::SVN->new($fetch->{$f}, $repo_id, $f);
2003                 }
2004         }
2005         undef;
2008 sub init {
2009         my ($class, $url, $path, $repo_id, $ref_id, $no_write) = @_;
2010         my $self = _new($class, $repo_id, $ref_id, $path);
2011         if (defined $url) {
2012                 $self->init_remote_config($url, $no_write);
2013         }
2014         $self;
2017 sub find_ref {
2018         my ($ref_id) = @_;
2019         foreach (command(qw/config -l/)) {
2020                 next unless m!^svn-remote\.(.+)\.fetch=
2021                               \s*(.*?)\s*:\s*(.+?)\s*$!x;
2022                 my ($repo_id, $path, $ref) = ($1, $2, $3);
2023                 if ($ref eq $ref_id) {
2024                         $path = '' if ($path =~ m#^\./?#);
2025                         return ($repo_id, $path);
2026                 }
2027         }
2028         (undef, undef, undef);
2031 sub new {
2032         my ($class, $ref_id, $repo_id, $path) = @_;
2033         if (defined $ref_id && !defined $repo_id && !defined $path) {
2034                 ($repo_id, $path) = find_ref($ref_id);
2035                 if (!defined $repo_id) {
2036                         die "Could not find a \"svn-remote.*.fetch\" key ",
2037                             "in the repository configuration matching: ",
2038                             "$ref_id\n";
2039                 }
2040         }
2041         my $self = _new($class, $repo_id, $ref_id, $path);
2042         if (!defined $self->{path} || !length $self->{path}) {
2043                 my $fetch = command_oneline('config', '--get',
2044                                             "svn-remote.$repo_id.fetch",
2045                                             ":$ref_id\$") or
2046                      die "Failed to read \"svn-remote.$repo_id.fetch\" ",
2047                          "\":$ref_id\$\" in config\n";
2048                 ($self->{path}, undef) = split(/\s*:\s*/, $fetch);
2049         }
2050         $self->{url} = command_oneline('config', '--get',
2051                                        "svn-remote.$repo_id.url") or
2052                   die "Failed to read \"svn-remote.$repo_id.url\" in config\n";
2053         $self->rebuild;
2054         $self;
2057 sub refname {
2058         my ($refname) = $_[0]->{ref_id} ;
2060         # It cannot end with a slash /, we'll throw up on this because
2061         # SVN can't have directories with a slash in their name, either:
2062         if ($refname =~ m{/$}) {
2063                 die "ref: '$refname' ends with a trailing slash, this is ",
2064                     "not permitted by git nor Subversion\n";
2065         }
2067         # It cannot have ASCII control character space, tilde ~, caret ^,
2068         # colon :, question-mark ?, asterisk *, space, or open bracket [
2069         # anywhere.
2070         #
2071         # Additionally, % must be escaped because it is used for escaping
2072         # and we want our escaped refname to be reversible
2073         $refname =~ s{([ \%~\^:\?\*\[\t])}{uc sprintf('%%%02x',ord($1))}eg;
2075         # no slash-separated component can begin with a dot .
2076         # /.* becomes /%2E*
2077         $refname =~ s{/\.}{/%2E}g;
2079         # It cannot have two consecutive dots .. anywhere
2080         # .. becomes %2E%2E
2081         $refname =~ s{\.\.}{%2E%2E}g;
2083         return $refname;
2086 sub desanitize_refname {
2087         my ($refname) = @_;
2088         $refname =~ s{%(?:([0-9A-F]{2}))}{chr hex($1)}eg;
2089         return $refname;
2092 sub svm_uuid {
2093         my ($self) = @_;
2094         return $self->{svm}->{uuid} if $self->svm;
2095         $self->ra;
2096         unless ($self->{svm}) {
2097                 die "SVM UUID not cached, and reading remotely failed\n";
2098         }
2099         $self->{svm}->{uuid};
2102 sub svm {
2103         my ($self) = @_;
2104         return $self->{svm} if $self->{svm};
2105         my $svm;
2106         # see if we have it in our config, first:
2107         eval {
2108                 my $section = "svn-remote.$self->{repo_id}";
2109                 $svm = {
2110                   source => tmp_config('--get', "$section.svm-source"),
2111                   uuid => tmp_config('--get', "$section.svm-uuid"),
2112                   replace => tmp_config('--get', "$section.svm-replace"),
2113                 }
2114         };
2115         if ($svm && $svm->{source} && $svm->{uuid} && $svm->{replace}) {
2116                 $self->{svm} = $svm;
2117         }
2118         $self->{svm};
2121 sub _set_svm_vars {
2122         my ($self, $ra) = @_;
2123         return $ra if $self->svm;
2125         my @err = ( "useSvmProps set, but failed to read SVM properties\n",
2126                     "(svm:source, svm:uuid) ",
2127                     "from the following URLs:\n" );
2128         sub read_svm_props {
2129                 my ($self, $ra, $path, $r) = @_;
2130                 my $props = ($ra->get_dir($path, $r))[2];
2131                 my $src = $props->{'svm:source'};
2132                 my $uuid = $props->{'svm:uuid'};
2133                 return undef if (!$src || !$uuid);
2135                 chomp($src, $uuid);
2137                 $uuid =~ m{^[0-9a-f\-]{30,}$}i
2138                     or die "doesn't look right - svm:uuid is '$uuid'\n";
2140                 # the '!' is used to mark the repos_root!/relative/path
2141                 $src =~ s{/?!/?}{/};
2142                 $src =~ s{/+$}{}; # no trailing slashes please
2143                 # username is of no interest
2144                 $src =~ s{(^[a-z\+]*://)[^/@]*@}{$1};
2146                 my $replace = $ra->{url};
2147                 $replace .= "/$path" if length $path;
2149                 my $section = "svn-remote.$self->{repo_id}";
2150                 tmp_config("$section.svm-source", $src);
2151                 tmp_config("$section.svm-replace", $replace);
2152                 tmp_config("$section.svm-uuid", $uuid);
2153                 $self->{svm} = {
2154                         source => $src,
2155                         uuid => $uuid,
2156                         replace => $replace
2157                 };
2158         }
2160         my $r = $ra->get_latest_revnum;
2161         my $path = $self->{path};
2162         my %tried;
2163         while (length $path) {
2164                 unless ($tried{"$self->{url}/$path"}) {
2165                         return $ra if $self->read_svm_props($ra, $path, $r);
2166                         $tried{"$self->{url}/$path"} = 1;
2167                 }
2168                 $path =~ s#/?[^/]+$##;
2169         }
2170         die "Path: '$path' should be ''\n" if $path ne '';
2171         return $ra if $self->read_svm_props($ra, $path, $r);
2172         $tried{"$self->{url}/$path"} = 1;
2174         if ($ra->{repos_root} eq $self->{url}) {
2175                 die @err, (map { "  $_\n" } keys %tried), "\n";
2176         }
2178         # nope, make sure we're connected to the repository root:
2179         my $ok;
2180         my @tried_b;
2181         $path = $ra->{svn_path};
2182         $ra = Git::SVN::Ra->new($ra->{repos_root});
2183         while (length $path) {
2184                 unless ($tried{"$ra->{url}/$path"}) {
2185                         $ok = $self->read_svm_props($ra, $path, $r);
2186                         last if $ok;
2187                         $tried{"$ra->{url}/$path"} = 1;
2188                 }
2189                 $path =~ s#/?[^/]+$##;
2190         }
2191         die "Path: '$path' should be ''\n" if $path ne '';
2192         $ok ||= $self->read_svm_props($ra, $path, $r);
2193         $tried{"$ra->{url}/$path"} = 1;
2194         if (!$ok) {
2195                 die @err, (map { "  $_\n" } keys %tried), "\n";
2196         }
2197         Git::SVN::Ra->new($self->{url});
2200 sub svnsync {
2201         my ($self) = @_;
2202         return $self->{svnsync} if $self->{svnsync};
2204         if ($self->no_metadata) {
2205                 die "Can't have both 'noMetadata' and ",
2206                     "'useSvnsyncProps' options set!\n";
2207         }
2208         if ($self->rewrite_root) {
2209                 die "Can't have both 'useSvnsyncProps' and 'rewriteRoot' ",
2210                     "options set!\n";
2211         }
2212         if ($self->rewrite_uuid) {
2213                 die "Can't have both 'useSvnsyncProps' and 'rewriteUUID' ",
2214                     "options set!\n";
2215         }
2217         my $svnsync;
2218         # see if we have it in our config, first:
2219         eval {
2220                 my $section = "svn-remote.$self->{repo_id}";
2222                 my $url = tmp_config('--get', "$section.svnsync-url");
2223                 ($url) = ($url =~ m{^([a-z\+]+://\S+)$}) or
2224                    die "doesn't look right - svn:sync-from-url is '$url'\n";
2226                 my $uuid = tmp_config('--get', "$section.svnsync-uuid");
2227                 ($uuid) = ($uuid =~ m{^([0-9a-f\-]{30,})$}i) or
2228                    die "doesn't look right - svn:sync-from-uuid is '$uuid'\n";
2230                 $svnsync = { url => $url, uuid => $uuid }
2231         };
2232         if ($svnsync && $svnsync->{url} && $svnsync->{uuid}) {
2233                 return $self->{svnsync} = $svnsync;
2234         }
2236         my $err = "useSvnsyncProps set, but failed to read " .
2237                   "svnsync property: svn:sync-from-";
2238         my $rp = $self->ra->rev_proplist(0);
2240         my $url = $rp->{'svn:sync-from-url'} or die $err . "url\n";
2241         ($url) = ($url =~ m{^([a-z\+]+://\S+)$}) or
2242                    die "doesn't look right - svn:sync-from-url is '$url'\n";
2244         my $uuid = $rp->{'svn:sync-from-uuid'} or die $err . "uuid\n";
2245         ($uuid) = ($uuid =~ m{^([0-9a-f\-]{30,})$}i) or
2246                    die "doesn't look right - svn:sync-from-uuid is '$uuid'\n";
2248         my $section = "svn-remote.$self->{repo_id}";
2249         tmp_config('--add', "$section.svnsync-uuid", $uuid);
2250         tmp_config('--add', "$section.svnsync-url", $url);
2251         return $self->{svnsync} = { url => $url, uuid => $uuid };
2254 # this allows us to memoize our SVN::Ra UUID locally and avoid a
2255 # remote lookup (useful for 'git svn log').
2256 sub ra_uuid {
2257         my ($self) = @_;
2258         unless ($self->{ra_uuid}) {
2259                 my $key = "svn-remote.$self->{repo_id}.uuid";
2260                 my $uuid = eval { tmp_config('--get', $key) };
2261                 if (!$@ && $uuid && $uuid =~ /^([a-f\d\-]{30,})$/i) {
2262                         $self->{ra_uuid} = $uuid;
2263                 } else {
2264                         die "ra_uuid called without URL\n" unless $self->{url};
2265                         $self->{ra_uuid} = $self->ra->get_uuid;
2266                         tmp_config('--add', $key, $self->{ra_uuid});
2267                 }
2268         }
2269         $self->{ra_uuid};
2272 sub _set_repos_root {
2273         my ($self, $repos_root) = @_;
2274         my $k = "svn-remote.$self->{repo_id}.reposRoot";
2275         $repos_root ||= $self->ra->{repos_root};
2276         tmp_config($k, $repos_root);
2277         $repos_root;
2280 sub repos_root {
2281         my ($self) = @_;
2282         my $k = "svn-remote.$self->{repo_id}.reposRoot";
2283         eval { tmp_config('--get', $k) } || $self->_set_repos_root;
2286 sub ra {
2287         my ($self) = shift;
2288         my $ra = Git::SVN::Ra->new($self->{url});
2289         $self->_set_repos_root($ra->{repos_root});
2290         if ($self->use_svm_props && !$self->{svm}) {
2291                 if ($self->no_metadata) {
2292                         die "Can't have both 'noMetadata' and ",
2293                             "'useSvmProps' options set!\n";
2294                 } elsif ($self->use_svnsync_props) {
2295                         die "Can't have both 'useSvnsyncProps' and ",
2296                             "'useSvmProps' options set!\n";
2297                 }
2298                 $ra = $self->_set_svm_vars($ra);
2299                 $self->{-want_revprops} = 1;
2300         }
2301         $ra;
2304 # prop_walk(PATH, REV, SUB)
2305 # -------------------------
2306 # Recursively traverse PATH at revision REV and invoke SUB for each
2307 # directory that contains a SVN property.  SUB will be invoked as
2308 # follows:  &SUB(gs, path, props);  where `gs' is this instance of
2309 # Git::SVN, `path' the path to the directory where the properties
2310 # `props' were found.  The `path' will be relative to point of checkout,
2311 # that is, if url://repo/trunk is the current Git branch, and that
2312 # directory contains a sub-directory `d', SUB will be invoked with `/d/'
2313 # as `path' (note the trailing `/').
2314 sub prop_walk {
2315         my ($self, $path, $rev, $sub) = @_;
2317         $path =~ s#^/##;
2318         my ($dirent, undef, $props) = $self->ra->get_dir($path, $rev);
2319         $path =~ s#^/*#/#g;
2320         my $p = $path;
2321         # Strip the irrelevant part of the path.
2322         $p =~ s#^/+\Q$self->{path}\E(/|$)#/#;
2323         # Ensure the path is terminated by a `/'.
2324         $p =~ s#/*$#/#;
2326         # The properties contain all the internal SVN stuff nobody
2327         # (usually) cares about.
2328         my $interesting_props = 0;
2329         foreach (keys %{$props}) {
2330                 # If it doesn't start with `svn:', it must be a
2331                 # user-defined property.
2332                 ++$interesting_props and next if $_ !~ /^svn:/;
2333                 # FIXME: Fragile, if SVN adds new public properties,
2334                 # this needs to be updated.
2335                 ++$interesting_props if /^svn:(?:ignore|keywords|executable
2336                                                  |eol-style|mime-type
2337                                                  |externals|needs-lock)$/x;
2338         }
2339         &$sub($self, $p, $props) if $interesting_props;
2341         foreach (sort keys %$dirent) {
2342                 next if $dirent->{$_}->{kind} != $SVN::Node::dir;
2343                 $self->prop_walk($self->{path} . $p . $_, $rev, $sub);
2344         }
2347 sub last_rev { ($_[0]->last_rev_commit)[0] }
2348 sub last_commit { ($_[0]->last_rev_commit)[1] }
2350 # returns the newest SVN revision number and newest commit SHA1
2351 sub last_rev_commit {
2352         my ($self) = @_;
2353         if (defined $self->{last_rev} && defined $self->{last_commit}) {
2354                 return ($self->{last_rev}, $self->{last_commit});
2355         }
2356         my $c = ::verify_ref($self->refname.'^0');
2357         if ($c && !$self->use_svm_props && !$self->no_metadata) {
2358                 my $rev = (::cmt_metadata($c))[1];
2359                 if (defined $rev) {
2360                         ($self->{last_rev}, $self->{last_commit}) = ($rev, $c);
2361                         return ($rev, $c);
2362                 }
2363         }
2364         my $map_path = $self->map_path;
2365         unless (-e $map_path) {
2366                 ($self->{last_rev}, $self->{last_commit}) = (undef, undef);
2367                 return (undef, undef);
2368         }
2369         my ($rev, $commit) = $self->rev_map_max(1);
2370         ($self->{last_rev}, $self->{last_commit}) = ($rev, $commit);
2371         return ($rev, $commit);
2374 sub get_fetch_range {
2375         my ($self, $min, $max) = @_;
2376         $max ||= $self->ra->get_latest_revnum;
2377         $min ||= $self->rev_map_max;
2378         (++$min, $max);
2381 sub tmp_config {
2382         my (@args) = @_;
2383         my $old_def_config = "$ENV{GIT_DIR}/svn/config";
2384         my $config = "$ENV{GIT_DIR}/svn/.metadata";
2385         if (! -f $config && -f $old_def_config) {
2386                 rename $old_def_config, $config or
2387                        die "Failed rename $old_def_config => $config: $!\n";
2388         }
2389         my $old_config = $ENV{GIT_CONFIG};
2390         $ENV{GIT_CONFIG} = $config;
2391         $@ = undef;
2392         my @ret = eval {
2393                 unless (-f $config) {
2394                         mkfile($config);
2395                         open my $fh, '>', $config or
2396                             die "Can't open $config: $!\n";
2397                         print $fh "; This file is used internally by ",
2398                                   "git-svn\n" or die
2399                                   "Couldn't write to $config: $!\n";
2400                         print $fh "; You should not have to edit it\n" or
2401                               die "Couldn't write to $config: $!\n";
2402                         close $fh or die "Couldn't close $config: $!\n";
2403                 }
2404                 command('config', @args);
2405         };
2406         my $err = $@;
2407         if (defined $old_config) {
2408                 $ENV{GIT_CONFIG} = $old_config;
2409         } else {
2410                 delete $ENV{GIT_CONFIG};
2411         }
2412         die $err if $err;
2413         wantarray ? @ret : $ret[0];
2416 sub tmp_index_do {
2417         my ($self, $sub) = @_;
2418         my $old_index = $ENV{GIT_INDEX_FILE};
2419         $ENV{GIT_INDEX_FILE} = $self->{index};
2420         $@ = undef;
2421         my @ret = eval {
2422                 my ($dir, $base) = ($self->{index} =~ m#^(.*?)/?([^/]+)$#);
2423                 mkpath([$dir]) unless -d $dir;
2424                 &$sub;
2425         };
2426         my $err = $@;
2427         if (defined $old_index) {
2428                 $ENV{GIT_INDEX_FILE} = $old_index;
2429         } else {
2430                 delete $ENV{GIT_INDEX_FILE};
2431         }
2432         die $err if $err;
2433         wantarray ? @ret : $ret[0];
2436 sub assert_index_clean {
2437         my ($self, $treeish) = @_;
2439         $self->tmp_index_do(sub {
2440                 command_noisy('read-tree', $treeish) unless -e $self->{index};
2441                 my $x = command_oneline('write-tree');
2442                 my ($y) = (command(qw/cat-file commit/, $treeish) =~
2443                            /^tree ($::sha1)/mo);
2444                 return if $y eq $x;
2446                 warn "Index mismatch: $y != $x\nrereading $treeish\n";
2447                 unlink $self->{index} or die "unlink $self->{index}: $!\n";
2448                 command_noisy('read-tree', $treeish);
2449                 $x = command_oneline('write-tree');
2450                 if ($y ne $x) {
2451                         ::fatal "trees ($treeish) $y != $x\n",
2452                                 "Something is seriously wrong...";
2453                 }
2454         });
2457 sub get_commit_parents {
2458         my ($self, $log_entry) = @_;
2459         my (%seen, @ret, @tmp);
2460         # legacy support for 'set-tree'; this is only used by set_tree_cb:
2461         if (my $ip = $self->{inject_parents}) {
2462                 if (my $commit = delete $ip->{$log_entry->{revision}}) {
2463                         push @tmp, $commit;
2464                 }
2465         }
2466         if (my $cur = ::verify_ref($self->refname.'^0')) {
2467                 push @tmp, $cur;
2468         }
2469         if (my $ipd = $self->{inject_parents_dcommit}) {
2470                 if (my $commit = delete $ipd->{$log_entry->{revision}}) {
2471                         push @tmp, @$commit;
2472                 }
2473         }
2474         push @tmp, $_ foreach (@{$log_entry->{parents}}, @tmp);
2475         while (my $p = shift @tmp) {
2476                 next if $seen{$p};
2477                 $seen{$p} = 1;
2478                 push @ret, $p;
2479         }
2480         @ret;
2483 sub rewrite_root {
2484         my ($self) = @_;
2485         return $self->{-rewrite_root} if exists $self->{-rewrite_root};
2486         my $k = "svn-remote.$self->{repo_id}.rewriteRoot";
2487         my $rwr = eval { command_oneline(qw/config --get/, $k) };
2488         if ($rwr) {
2489                 $rwr =~ s#/+$##;
2490                 if ($rwr !~ m#^[a-z\+]+://#) {
2491                         die "$rwr is not a valid URL (key: $k)\n";
2492                 }
2493         }
2494         $self->{-rewrite_root} = $rwr;
2497 sub rewrite_uuid {
2498         my ($self) = @_;
2499         return $self->{-rewrite_uuid} if exists $self->{-rewrite_uuid};
2500         my $k = "svn-remote.$self->{repo_id}.rewriteUUID";
2501         my $rwid = eval { command_oneline(qw/config --get/, $k) };
2502         if ($rwid) {
2503                 $rwid =~ s#/+$##;
2504                 if ($rwid !~ m#^[a-f0-9]{8}-(?:[a-f0-9]{4}-){3}[a-f0-9]{12}$#) {
2505                         die "$rwid is not a valid UUID (key: $k)\n";
2506                 }
2507         }
2508         $self->{-rewrite_uuid} = $rwid;
2511 sub metadata_url {
2512         my ($self) = @_;
2513         ($self->rewrite_root || $self->{url}) .
2514            (length $self->{path} ? '/' . $self->{path} : '');
2517 sub full_url {
2518         my ($self) = @_;
2519         $self->{url} . (length $self->{path} ? '/' . $self->{path} : '');
2523 sub set_commit_header_env {
2524         my ($log_entry) = @_;
2525         my %env;
2526         foreach my $ned (qw/NAME EMAIL DATE/) {
2527                 foreach my $ac (qw/AUTHOR COMMITTER/) {
2528                         $env{"GIT_${ac}_${ned}"} = $ENV{"GIT_${ac}_${ned}"};
2529                 }
2530         }
2532         $ENV{GIT_AUTHOR_NAME} = $log_entry->{name};
2533         $ENV{GIT_AUTHOR_EMAIL} = $log_entry->{email};
2534         $ENV{GIT_AUTHOR_DATE} = $ENV{GIT_COMMITTER_DATE} = $log_entry->{date};
2536         $ENV{GIT_COMMITTER_NAME} = (defined $log_entry->{commit_name})
2537                                                 ? $log_entry->{commit_name}
2538                                                 : $log_entry->{name};
2539         $ENV{GIT_COMMITTER_EMAIL} = (defined $log_entry->{commit_email})
2540                                                 ? $log_entry->{commit_email}
2541                                                 : $log_entry->{email};
2542         \%env;
2545 sub restore_commit_header_env {
2546         my ($env) = @_;
2547         foreach my $ned (qw/NAME EMAIL DATE/) {
2548                 foreach my $ac (qw/AUTHOR COMMITTER/) {
2549                         my $k = "GIT_${ac}_${ned}";
2550                         if (defined $env->{$k}) {
2551                                 $ENV{$k} = $env->{$k};
2552                         } else {
2553                                 delete $ENV{$k};
2554                         }
2555                 }
2556         }
2559 sub gc {
2560         command_noisy('gc', '--auto');
2561 };
2563 sub do_git_commit {
2564         my ($self, $log_entry) = @_;
2565         my $lr = $self->last_rev;
2566         if (defined $lr && $lr >= $log_entry->{revision}) {
2567                 die "Last fetched revision of ", $self->refname,
2568                     " was r$lr, but we are about to fetch: ",
2569                     "r$log_entry->{revision}!\n";
2570         }
2571         if (my $c = $self->rev_map_get($log_entry->{revision})) {
2572                 croak "$log_entry->{revision} = $c already exists! ",
2573                       "Why are we refetching it?\n";
2574         }
2575         my $old_env = set_commit_header_env($log_entry);
2576         my $tree = $log_entry->{tree};
2577         if (!defined $tree) {
2578                 $tree = $self->tmp_index_do(sub {
2579                                             command_oneline('write-tree') });
2580         }
2581         die "Tree is not a valid sha1: $tree\n" if $tree !~ /^$::sha1$/o;
2583         my @exec = ('git', 'commit-tree', $tree);
2584         foreach ($self->get_commit_parents($log_entry)) {
2585                 push @exec, '-p', $_;
2586         }
2587         defined(my $pid = open3(my $msg_fh, my $out_fh, '>&STDERR', @exec))
2588                                                                    or croak $!;
2589         binmode $msg_fh;
2591         # we always get UTF-8 from SVN, but we may want our commits in
2592         # a different encoding.
2593         if (my $enc = Git::config('i18n.commitencoding')) {
2594                 require Encode;
2595                 Encode::from_to($log_entry->{log}, 'UTF-8', $enc);
2596         }
2597         print $msg_fh $log_entry->{log} or croak $!;
2598         restore_commit_header_env($old_env);
2599         unless ($self->no_metadata) {
2600                 print $msg_fh "\ngit-svn-id: $log_entry->{metadata}\n"
2601                               or croak $!;
2602         }
2603         $msg_fh->flush == 0 or croak $!;
2604         close $msg_fh or croak $!;
2605         chomp(my $commit = do { local $/; <$out_fh> });
2606         close $out_fh or croak $!;
2607         waitpid $pid, 0;
2608         croak $? if $?;
2609         if ($commit !~ /^$::sha1$/o) {
2610                 die "Failed to commit, invalid sha1: $commit\n";
2611         }
2613         $self->rev_map_set($log_entry->{revision}, $commit, 1);
2615         $self->{last_rev} = $log_entry->{revision};
2616         $self->{last_commit} = $commit;
2617         print "r$log_entry->{revision}" unless $::_q > 1;
2618         if (defined $log_entry->{svm_revision}) {
2619                  print " (\@$log_entry->{svm_revision})" unless $::_q > 1;
2620                  $self->rev_map_set($log_entry->{svm_revision}, $commit,
2621                                    0, $self->svm_uuid);
2622         }
2623         print " = $commit ($self->{ref_id})\n" unless $::_q > 1;
2624         if (--$_gc_nr == 0) {
2625                 $_gc_nr = $_gc_period;
2626                 gc();
2627         }
2628         return $commit;
2631 sub match_paths {
2632         my ($self, $paths, $r) = @_;
2633         return 1 if $self->{path} eq '';
2634         if (my $path = $paths->{"/$self->{path}"}) {
2635                 return ($path->{action} eq 'D') ? 0 : 1;
2636         }
2637         $self->{path_regex} ||= qr/^\/\Q$self->{path}\E\//;
2638         if (grep /$self->{path_regex}/, keys %$paths) {
2639                 return 1;
2640         }
2641         my $c = '';
2642         foreach (split m#/#, $self->{path}) {
2643                 $c .= "/$_";
2644                 next unless ($paths->{$c} &&
2645                              ($paths->{$c}->{action} =~ /^[AR]$/));
2646                 if ($self->ra->check_path($self->{path}, $r) ==
2647                     $SVN::Node::dir) {
2648                         return 1;
2649                 }
2650         }
2651         return 0;
2654 sub find_parent_branch {
2655         my ($self, $paths, $rev) = @_;
2656         return undef unless $self->follow_parent;
2657         unless (defined $paths) {
2658                 my $err_handler = $SVN::Error::handler;
2659                 $SVN::Error::handler = \&Git::SVN::Ra::skip_unknown_revs;
2660                 $self->ra->get_log([$self->{path}], $rev, $rev, 0, 1, 1,
2661                                    sub { $paths = $_[0] });
2662                 $SVN::Error::handler = $err_handler;
2663         }
2664         return undef unless defined $paths;
2666         # look for a parent from another branch:
2667         my @b_path_components = split m#/#, $self->{path};
2668         my @a_path_components;
2669         my $i;
2670         while (@b_path_components) {
2671                 $i = $paths->{'/'.join('/', @b_path_components)};
2672                 last if $i && defined $i->{copyfrom_path};
2673                 unshift(@a_path_components, pop(@b_path_components));
2674         }
2675         return undef unless defined $i && defined $i->{copyfrom_path};
2676         my $branch_from = $i->{copyfrom_path};
2677         if (@a_path_components) {
2678                 print STDERR "branch_from: $branch_from => ";
2679                 $branch_from .= '/'.join('/', @a_path_components);
2680                 print STDERR $branch_from, "\n";
2681         }
2682         my $r = $i->{copyfrom_rev};
2683         my $repos_root = $self->ra->{repos_root};
2684         my $url = $self->ra->{url};
2685         my $new_url = $url . $branch_from;
2686         print STDERR  "Found possible branch point: ",
2687                       "$new_url => ", $self->full_url, ", $r\n"
2688                       unless $::_q > 1;
2689         $branch_from =~ s#^/##;
2690         my $gs = $self->other_gs($new_url, $url,
2691                                  $branch_from, $r, $self->{ref_id});
2692         my ($r0, $parent) = $gs->find_rev_before($r, 1);
2693         {
2694                 my ($base, $head);
2695                 if (!defined $r0 || !defined $parent) {
2696                         ($base, $head) = parse_revision_argument(0, $r);
2697                 } else {
2698                         if ($r0 < $r) {
2699                                 $gs->ra->get_log([$gs->{path}], $r0 + 1, $r, 1,
2700                                         0, 1, sub { $base = $_[1] - 1 });
2701                         }
2702                 }
2703                 if (defined $base && $base <= $r) {
2704                         $gs->fetch($base, $r);
2705                 }
2706                 ($r0, $parent) = $gs->find_rev_before($r, 1);
2707         }
2708         if (defined $r0 && defined $parent) {
2709                 print STDERR "Found branch parent: ($self->{ref_id}) $parent\n"
2710                              unless $::_q > 1;
2711                 my $ed;
2712                 if ($self->ra->can_do_switch) {
2713                         $self->assert_index_clean($parent);
2714                         print STDERR "Following parent with do_switch\n"
2715                                      unless $::_q > 1;
2716                         # do_switch works with svn/trunk >= r22312, but that
2717                         # is not included with SVN 1.4.3 (the latest version
2718                         # at the moment), so we can't rely on it
2719                         $self->{last_rev} = $r0;
2720                         $self->{last_commit} = $parent;
2721                         $ed = SVN::Git::Fetcher->new($self, $gs->{path});
2722                         $gs->ra->gs_do_switch($r0, $rev, $gs,
2723                                               $self->full_url, $ed)
2724                           or die "SVN connection failed somewhere...\n";
2725                 } elsif ($self->ra->trees_match($new_url, $r0,
2726                                                 $self->full_url, $rev)) {
2727                         print STDERR "Trees match:\n",
2728                                      "  $new_url\@$r0\n",
2729                                      "  ${\$self->full_url}\@$rev\n",
2730                                      "Following parent with no changes\n"
2731                                      unless $::_q > 1;
2732                         $self->tmp_index_do(sub {
2733                             command_noisy('read-tree', $parent);
2734                         });
2735                         $self->{last_commit} = $parent;
2736                 } else {
2737                         print STDERR "Following parent with do_update\n"
2738                                      unless $::_q > 1;
2739                         $ed = SVN::Git::Fetcher->new($self);
2740                         $self->ra->gs_do_update($rev, $rev, $self, $ed)
2741                           or die "SVN connection failed somewhere...\n";
2742                 }
2743                 print STDERR "Successfully followed parent\n" unless $::_q > 1;
2744                 return $self->make_log_entry($rev, [$parent], $ed);
2745         }
2746         return undef;
2749 sub do_fetch {
2750         my ($self, $paths, $rev) = @_;
2751         my $ed;
2752         my ($last_rev, @parents);
2753         if (my $lc = $self->last_commit) {
2754                 # we can have a branch that was deleted, then re-added
2755                 # under the same name but copied from another path, in
2756                 # which case we'll have multiple parents (we don't
2757                 # want to break the original ref, nor lose copypath info):
2758                 if (my $log_entry = $self->find_parent_branch($paths, $rev)) {
2759                         push @{$log_entry->{parents}}, $lc;
2760                         return $log_entry;
2761                 }
2762                 $ed = SVN::Git::Fetcher->new($self);
2763                 $last_rev = $self->{last_rev};
2764                 $ed->{c} = $lc;
2765                 @parents = ($lc);
2766         } else {
2767                 $last_rev = $rev;
2768                 if (my $log_entry = $self->find_parent_branch($paths, $rev)) {
2769                         return $log_entry;
2770                 }
2771                 $ed = SVN::Git::Fetcher->new($self);
2772         }
2773         unless ($self->ra->gs_do_update($last_rev, $rev, $self, $ed)) {
2774                 die "SVN connection failed somewhere...\n";
2775         }
2776         $self->make_log_entry($rev, \@parents, $ed);
2779 sub mkemptydirs {
2780         my ($self, $r) = @_;
2782         sub scan {
2783                 my ($r, $empty_dirs, $line) = @_;
2784                 if (defined $r && $line =~ /^r(\d+)$/) {
2785                         return 0 if $1 > $r;
2786                 } elsif ($line =~ /^  \+empty_dir: (.+)$/) {
2787                         $empty_dirs->{$1} = 1;
2788                 } elsif ($line =~ /^  \-empty_dir: (.+)$/) {
2789                         my @d = grep {m[^\Q$1\E(/|$)]} (keys %$empty_dirs);
2790                         delete @$empty_dirs{@d};
2791                 }
2792                 1; # continue
2793         };
2795         my %empty_dirs = ();
2796         my $gz_file = "$self->{dir}/unhandled.log.gz";
2797         if (-f $gz_file) {
2798                 if (!$can_compress) {
2799                         warn "Compress::Zlib could not be found; ",
2800                              "empty directories in $gz_file will not be read\n";
2801                 } else {
2802                         my $gz = Compress::Zlib::gzopen($gz_file, "rb") or
2803                                 die "Unable to open $gz_file: $!\n";
2804                         my $line;
2805                         while ($gz->gzreadline($line) > 0) {
2806                                 scan($r, \%empty_dirs, $line) or last;
2807                         }
2808                         $gz->gzclose;
2809                 }
2810         }
2812         if (open my $fh, '<', "$self->{dir}/unhandled.log") {
2813                 binmode $fh or croak "binmode: $!";
2814                 while (<$fh>) {
2815                         scan($r, \%empty_dirs, $_) or last;
2816                 }
2817                 close $fh;
2818         }
2820         my $strip = qr/\A\Q$self->{path}\E(?:\/|$)/;
2821         foreach my $d (sort keys %empty_dirs) {
2822                 $d = uri_decode($d);
2823                 $d =~ s/$strip//;
2824                 next if -d $d;
2825                 if (-e _) {
2826                         warn "$d exists but is not a directory\n";
2827                 } else {
2828                         print "creating empty directory: $d\n";
2829                         mkpath([$d]);
2830                 }
2831         }
2834 sub get_untracked {
2835         my ($self, $ed) = @_;
2836         my @out;
2837         my $h = $ed->{empty};
2838         foreach (sort keys %$h) {
2839                 my $act = $h->{$_} ? '+empty_dir' : '-empty_dir';
2840                 push @out, "  $act: " . uri_encode($_);
2841                 warn "W: $act: $_\n";
2842         }
2843         foreach my $t (qw/dir_prop file_prop/) {
2844                 $h = $ed->{$t} or next;
2845                 foreach my $path (sort keys %$h) {
2846                         my $ppath = $path eq '' ? '.' : $path;
2847                         foreach my $prop (sort keys %{$h->{$path}}) {
2848                                 next if $SKIP_PROP{$prop};
2849                                 my $v = $h->{$path}->{$prop};
2850                                 my $t_ppath_prop = "$t: " .
2851                                                     uri_encode($ppath) . ' ' .
2852                                                     uri_encode($prop);
2853                                 if (defined $v) {
2854                                         push @out, "  +$t_ppath_prop " .
2855                                                    uri_encode($v);
2856                                 } else {
2857                                         push @out, "  -$t_ppath_prop";
2858                                 }
2859                         }
2860                 }
2861         }
2862         foreach my $t (qw/absent_file absent_directory/) {
2863                 $h = $ed->{$t} or next;
2864                 foreach my $parent (sort keys %$h) {
2865                         foreach my $path (sort @{$h->{$parent}}) {
2866                                 push @out, "  $t: " .
2867                                            uri_encode("$parent/$path");
2868                                 warn "W: $t: $parent/$path ",
2869                                      "Insufficient permissions?\n";
2870                         }
2871                 }
2872         }
2873         \@out;
2876 # parse_svn_date(DATE)
2877 # --------------------
2878 # Given a date (in UTC) from Subversion, return a string in the format
2879 # "<TZ Offset> <local date/time>" that Git will use.
2881 # By default the parsed date will be in UTC; if $Git::SVN::_localtime
2882 # is true we'll convert it to the local timezone instead.
2883 sub parse_svn_date {
2884         my $date = shift || return '+0000 1970-01-01 00:00:00';
2885         my ($Y,$m,$d,$H,$M,$S) = ($date =~ /^(\d{4})\-(\d\d)\-(\d\d)T
2886                                             (\d\d)\:(\d\d)\:(\d\d)\.\d*Z$/x) or
2887                                          croak "Unable to parse date: $date\n";
2888         my $parsed_date;    # Set next.
2890         if ($Git::SVN::_localtime) {
2891                 # Translate the Subversion datetime to an epoch time.
2892                 # Begin by switching ourselves to $date's timezone, UTC.
2893                 my $old_env_TZ = $ENV{TZ};
2894                 $ENV{TZ} = 'UTC';
2896                 my $epoch_in_UTC =
2897                     POSIX::strftime('%s', $S, $M, $H, $d, $m - 1, $Y - 1900);
2899                 # Determine our local timezone (including DST) at the
2900                 # time of $epoch_in_UTC.  $Git::SVN::Log::TZ stored the
2901                 # value of TZ, if any, at the time we were run.
2902                 if (defined $Git::SVN::Log::TZ) {
2903                         $ENV{TZ} = $Git::SVN::Log::TZ;
2904                 } else {
2905                         delete $ENV{TZ};
2906                 }
2908                 my $our_TZ =
2909                     POSIX::strftime('%Z', $S, $M, $H, $d, $m - 1, $Y - 1900);
2911                 # This converts $epoch_in_UTC into our local timezone.
2912                 my ($sec, $min, $hour, $mday, $mon, $year,
2913                     $wday, $yday, $isdst) = localtime($epoch_in_UTC);
2915                 $parsed_date = sprintf('%s %04d-%02d-%02d %02d:%02d:%02d',
2916                                        $our_TZ, $year + 1900, $mon + 1,
2917                                        $mday, $hour, $min, $sec);
2919                 # Reset us to the timezone in effect when we entered
2920                 # this routine.
2921                 if (defined $old_env_TZ) {
2922                         $ENV{TZ} = $old_env_TZ;
2923                 } else {
2924                         delete $ENV{TZ};
2925                 }
2926         } else {
2927                 $parsed_date = "+0000 $Y-$m-$d $H:$M:$S";
2928         }
2930         return $parsed_date;
2933 sub other_gs {
2934         my ($self, $new_url, $url,
2935             $branch_from, $r, $old_ref_id) = @_;
2936         my $gs = Git::SVN->find_by_url($new_url, $url, $branch_from);
2937         unless ($gs) {
2938                 my $ref_id = $old_ref_id;
2939                 $ref_id =~ s/\@\d+$//;
2940                 $ref_id .= "\@$r";
2941                 # just grow a tail if we're not unique enough :x
2942                 $ref_id .= '-' while find_ref($ref_id);
2943                 print STDERR "Initializing parent: $ref_id\n" unless $::_q > 1;
2944                 my ($u, $p, $repo_id) = ($new_url, '', $ref_id);
2945                 if ($u =~ s#^\Q$url\E(/|$)##) {
2946                         $p = $u;
2947                         $u = $url;
2948                         $repo_id = $self->{repo_id};
2949                 }
2950                 $gs = Git::SVN->init($u, $p, $repo_id, $ref_id, 1);
2951         }
2952         $gs
2955 sub call_authors_prog {
2956         my ($orig_author) = @_;
2957         $orig_author = command_oneline('rev-parse', '--sq-quote', $orig_author);
2958         my $author = `$::_authors_prog $orig_author`;
2959         if ($? != 0) {
2960                 die "$::_authors_prog failed with exit code $?\n"
2961         }
2962         if ($author =~ /^\s*(.+?)\s*<(.*)>\s*$/) {
2963                 my ($name, $email) = ($1, $2);
2964                 $email = undef if length $2 == 0;
2965                 return [$name, $email];
2966         } else {
2967                 die "Author: $orig_author: $::_authors_prog returned "
2968                         . "invalid author format: $author\n";
2969         }
2972 sub check_author {
2973         my ($author) = @_;
2974         if (!defined $author || length $author == 0) {
2975                 $author = '(no author)';
2976         }
2977         if (!defined $::users{$author}) {
2978                 if (defined $::_authors_prog) {
2979                         $::users{$author} = call_authors_prog($author);
2980                 } elsif (defined $::_authors) {
2981                         die "Author: $author not defined in $::_authors file\n";
2982                 }
2983         }
2984         $author;
2987 sub find_extra_svk_parents {
2988         my ($self, $ed, $tickets, $parents) = @_;
2989         # aha!  svk:merge property changed...
2990         my @tickets = split "\n", $tickets;
2991         my @known_parents;
2992         for my $ticket ( @tickets ) {
2993                 my ($uuid, $path, $rev) = split /:/, $ticket;
2994                 if ( $uuid eq $self->ra_uuid ) {
2995                         my $url = $self->rewrite_root || $self->{url};
2996                         my $repos_root = $url;
2997                         my $branch_from = $path;
2998                         $branch_from =~ s{^/}{};
2999                         my $gs = $self->other_gs($repos_root."/".$branch_from,
3000                                                  $url,
3001                                                  $branch_from,
3002                                                  $rev,
3003                                                  $self->{ref_id});
3004                         if ( my $commit = $gs->rev_map_get($rev, $uuid) ) {
3005                                 # wahey!  we found it, but it might be
3006                                 # an old one (!)
3007                                 push @known_parents, [ $rev, $commit ];
3008                         }
3009                 }
3010         }
3011         # Ordering matters; highest-numbered commit merge tickets
3012         # first, as they may account for later merge ticket additions
3013         # or changes.
3014         @known_parents = map {$_->[1]} sort {$b->[0] <=> $a->[0]} @known_parents;
3015         for my $parent ( @known_parents ) {
3016                 my @cmd = ('rev-list', $parent, map { "^$_" } @$parents );
3017                 my ($msg_fh, $ctx) = command_output_pipe(@cmd);
3018                 my $new;
3019                 while ( <$msg_fh> ) {
3020                         $new=1;last;
3021                 }
3022                 command_close_pipe($msg_fh, $ctx);
3023                 if ( $new ) {
3024                         print STDERR
3025                             "Found merge parent (svk:merge ticket): $parent\n";
3026                         push @$parents, $parent;
3027                 }
3028         }
3031 sub lookup_svn_merge {
3032         my $uuid = shift;
3033         my $url = shift;
3034         my $merge = shift;
3036         my ($source, $revs) = split ":", $merge;
3037         my $path = $source;
3038         $path =~ s{^/}{};
3039         my $gs = Git::SVN->find_by_url($url.$source, $url, $path);
3040         if ( !$gs ) {
3041                 warn "Couldn't find revmap for $url$source\n";
3042                 return;
3043         }
3044         my @ranges = split ",", $revs;
3045         my ($tip, $tip_commit);
3046         my @merged_commit_ranges;
3047         # find the tip
3048         for my $range ( @ranges ) {
3049                 my ($bottom, $top) = split "-", $range;
3050                 $top ||= $bottom;
3051                 my $bottom_commit = $gs->find_rev_after( $bottom, 1, $top );
3052                 my $top_commit = $gs->find_rev_before( $top, 1, $bottom );
3054                 unless ($top_commit and $bottom_commit) {
3055                         warn "W:unknown path/rev in svn:mergeinfo "
3056                                 ."dirprop: $source:$range\n";
3057                         next;
3058                 }
3060                 push @merged_commit_ranges,
3061                         "$bottom_commit^..$top_commit";
3063                 if ( !defined $tip or $top > $tip ) {
3064                         $tip = $top;
3065                         $tip_commit = $top_commit;
3066                 }
3067         }
3068         return ($tip_commit, @merged_commit_ranges);
3071 sub _rev_list {
3072         my ($msg_fh, $ctx) = command_output_pipe(
3073                 "rev-list", @_,
3074                );
3075         my @rv;
3076         while ( <$msg_fh> ) {
3077                 chomp;
3078                 push @rv, $_;
3079         }
3080         command_close_pipe($msg_fh, $ctx);
3081         @rv;
3084 sub check_cherry_pick {
3085         my $base = shift;
3086         my $tip = shift;
3087         my @ranges = @_;
3088         my %commits = map { $_ => 1 }
3089                 _rev_list("--no-merges", $tip, "--not", $base);
3090         for my $range ( @ranges ) {
3091                 delete @commits{_rev_list($range)};
3092         }
3093         for my $commit (keys %commits) {
3094                 if (has_no_changes($commit)) {
3095                         delete $commits{$commit};
3096                 }
3097         }
3098         return (keys %commits);
3101 sub has_no_changes {
3102         my $commit = shift;
3104         my @revs = split / /, command_oneline(
3105                 qw(rev-list --parents -1 -m), $commit);
3107         # Commits with no parents, e.g. the start of a partial branch,
3108         # have changes by definition.
3109         return 1 if (@revs < 2);
3111         # Commits with multiple parents, e.g a merge, have no changes
3112         # by definition.
3113         return 0 if (@revs > 2);
3115         return (command_oneline("rev-parse", "$commit^{tree}") eq
3116                 command_oneline("rev-parse", "$commit~1^{tree}"));
3119 BEGIN {
3120         memoize 'lookup_svn_merge';
3121         memoize 'check_cherry_pick';
3122         memoize 'has_no_changes';
3125 sub parents_exclude {
3126         my $parents = shift;
3127         my @commits = @_;
3128         return unless @commits;
3130         my @excluded;
3131         my $excluded;
3132         do {
3133                 my @cmd = ('rev-list', "-1", @commits, "--not", @$parents );
3134                 $excluded = command_oneline(@cmd);
3135                 if ( $excluded ) {
3136                         my @new;
3137                         my $found;
3138                         for my $commit ( @commits ) {
3139                                 if ( $commit eq $excluded ) {
3140                                         push @excluded, $commit;
3141                                         $found++;
3142                                         last;
3143                                 }
3144                                 else {
3145                                         push @new, $commit;
3146                                 }
3147                         }
3148                         die "saw commit '$excluded' in rev-list output, "
3149                                 ."but we didn't ask for that commit (wanted: @commits --not @$parents)"
3150                                         unless $found;
3151                         @commits = @new;
3152                 }
3153         }
3154                 while ($excluded and @commits);
3156         return @excluded;
3160 # note: this function should only be called if the various dirprops
3161 # have actually changed
3162 sub find_extra_svn_parents {
3163         my ($self, $ed, $mergeinfo, $parents) = @_;
3164         # aha!  svk:merge property changed...
3166         # We first search for merged tips which are not in our
3167         # history.  Then, we figure out which git revisions are in
3168         # that tip, but not this revision.  If all of those revisions
3169         # are now marked as merge, we can add the tip as a parent.
3170         my @merges = split "\n", $mergeinfo;
3171         my @merge_tips;
3172         my $url = $self->rewrite_root || $self->{url};
3173         my $uuid = $self->ra_uuid;
3174         my %ranges;
3175         for my $merge ( @merges ) {
3176                 my ($tip_commit, @ranges) =
3177                         lookup_svn_merge( $uuid, $url, $merge );
3178                 unless (!$tip_commit or
3179                                 grep { $_ eq $tip_commit } @$parents ) {
3180                         push @merge_tips, $tip_commit;
3181                         $ranges{$tip_commit} = \@ranges;
3182                 } else {
3183                         push @merge_tips, undef;
3184                 }
3185         }
3187         my %excluded = map { $_ => 1 }
3188                 parents_exclude($parents, grep { defined } @merge_tips);
3190         # check merge tips for new parents
3191         my @new_parents;
3192         for my $merge_tip ( @merge_tips ) {
3193                 my $spec = shift @merges;
3194                 next unless $merge_tip and $excluded{$merge_tip};
3196                 my $ranges = $ranges{$merge_tip};
3198                 # check out 'new' tips
3199                 my $merge_base;
3200                 eval {
3201                         $merge_base = command_oneline(
3202                                 "merge-base",
3203                                 @$parents, $merge_tip,
3204                         );
3205                 };
3206                 if ($@) {
3207                         die "An error occurred during merge-base"
3208                                 unless $@->isa("Git::Error::Command");
3210                         warn "W: Cannot find common ancestor between ".
3211                              "@$parents and $merge_tip. Ignoring merge info.\n";
3212                         next;
3213                 }
3215                 # double check that there are no missing non-merge commits
3216                 my (@incomplete) = check_cherry_pick(
3217                         $merge_base, $merge_tip,
3218                         @$ranges,
3219                        );
3221                 if ( @incomplete ) {
3222                         warn "W:svn cherry-pick ignored ($spec) - missing "
3223                                 .@incomplete." commit(s) (eg $incomplete[0])\n";
3224                 } else {
3225                         warn
3226                                 "Found merge parent (svn:mergeinfo prop): ",
3227                                         $merge_tip, "\n";
3228                         push @new_parents, $merge_tip;
3229                 }
3230         }
3232         # cater for merges which merge commits from multiple branches
3233         if ( @new_parents > 1 ) {
3234                 for ( my $i = 0; $i <= $#new_parents; $i++ ) {
3235                         for ( my $j = 0; $j <= $#new_parents; $j++ ) {
3236                                 next if $i == $j;
3237                                 next unless $new_parents[$i];
3238                                 next unless $new_parents[$j];
3239                                 my $revs = command_oneline(
3240                                         "rev-list", "-1",
3241                                         "$new_parents[$i]..$new_parents[$j]",
3242                                        );
3243                                 if ( !$revs ) {
3244                                         undef($new_parents[$i]);
3245                                 }
3246                         }
3247                 }
3248         }
3249         push @$parents, grep { defined } @new_parents;
3252 sub make_log_entry {
3253         my ($self, $rev, $parents, $ed) = @_;
3254         my $untracked = $self->get_untracked($ed);
3256         my @parents = @$parents;
3257         my $ps = $ed->{path_strip} || "";
3258         for my $path ( grep { m/$ps/ } %{$ed->{dir_prop}} ) {
3259                 my $props = $ed->{dir_prop}{$path};
3260                 if ( $props->{"svk:merge"} ) {
3261                         $self->find_extra_svk_parents
3262                                 ($ed, $props->{"svk:merge"}, \@parents);
3263                 }
3264                 if ( $props->{"svn:mergeinfo"} ) {
3265                         $self->find_extra_svn_parents
3266                                 ($ed,
3267                                  $props->{"svn:mergeinfo"},
3268                                  \@parents);
3269                 }
3270         }
3272         open my $un, '>>', "$self->{dir}/unhandled.log" or croak $!;
3273         print $un "r$rev\n" or croak $!;
3274         print $un $_, "\n" foreach @$untracked;
3275         my %log_entry = ( parents => \@parents, revision => $rev,
3276                           log => '');
3278         my $headrev;
3279         my $logged = delete $self->{logged_rev_props};
3280         if (!$logged || $self->{-want_revprops}) {
3281                 my $rp = $self->ra->rev_proplist($rev);
3282                 foreach (sort keys %$rp) {
3283                         my $v = $rp->{$_};
3284                         if (/^svn:(author|date|log)$/) {
3285                                 $log_entry{$1} = $v;
3286                         } elsif ($_ eq 'svm:headrev') {
3287                                 $headrev = $v;
3288                         } else {
3289                                 print $un "  rev_prop: ", uri_encode($_), ' ',
3290                                           uri_encode($v), "\n";
3291                         }
3292                 }
3293         } else {
3294                 map { $log_entry{$_} = $logged->{$_} } keys %$logged;
3295         }
3296         close $un or croak $!;
3298         $log_entry{date} = parse_svn_date($log_entry{date});
3299         $log_entry{log} .= "\n";
3300         my $author = $log_entry{author} = check_author($log_entry{author});
3301         my ($name, $email) = defined $::users{$author} ? @{$::users{$author}}
3302                                                        : ($author, undef);
3304         my ($commit_name, $commit_email) = ($name, $email);
3305         if ($_use_log_author) {
3306                 my $name_field;
3307                 if ($log_entry{log} =~ /From:\s+(.*\S)\s*\n/i) {
3308                         $name_field = $1;
3309                 } elsif ($log_entry{log} =~ /Signed-off-by:\s+(.*\S)\s*\n/i) {
3310                         $name_field = $1;
3311                 }
3312                 if (!defined $name_field) {
3313                         if (!defined $email) {
3314                                 $email = $name;
3315                         }
3316                 } elsif ($name_field =~ /(.*?)\s+<(.*)>/) {
3317                         ($name, $email) = ($1, $2);
3318                 } elsif ($name_field =~ /(.*)@/) {
3319                         ($name, $email) = ($1, $name_field);
3320                 } else {
3321                         ($name, $email) = ($name_field, $name_field);
3322                 }
3323         }
3324         if (defined $headrev && $self->use_svm_props) {
3325                 if ($self->rewrite_root) {
3326                         die "Can't have both 'useSvmProps' and 'rewriteRoot' ",
3327                             "options set!\n";
3328                 }
3329                 if ($self->rewrite_uuid) {
3330                         die "Can't have both 'useSvmProps' and 'rewriteUUID' ",
3331                             "options set!\n";
3332                 }
3333                 my ($uuid, $r) = $headrev =~ m{^([a-f\d\-]{30,}):(\d+)$}i;
3334                 # we don't want "SVM: initializing mirror for junk" ...
3335                 return undef if $r == 0;
3336                 my $svm = $self->svm;
3337                 if ($uuid ne $svm->{uuid}) {
3338                         die "UUID mismatch on SVM path:\n",
3339                             "expected: $svm->{uuid}\n",
3340                             "     got: $uuid\n";
3341                 }
3342                 my $full_url = $self->full_url;
3343                 $full_url =~ s#^\Q$svm->{replace}\E(/|$)#$svm->{source}$1# or
3344                              die "Failed to replace '$svm->{replace}' with ",
3345                                  "'$svm->{source}' in $full_url\n";
3346                 # throw away username for storing in records
3347                 remove_username($full_url);
3348                 $log_entry{metadata} = "$full_url\@$r $uuid";
3349                 $log_entry{svm_revision} = $r;
3350                 $email ||= "$author\@$uuid";
3351                 $commit_email ||= "$author\@$uuid";
3352         } elsif ($self->use_svnsync_props) {
3353                 my $full_url = $self->svnsync->{url};
3354                 $full_url .= "/$self->{path}" if length $self->{path};
3355                 remove_username($full_url);
3356                 my $uuid = $self->svnsync->{uuid};
3357                 $log_entry{metadata} = "$full_url\@$rev $uuid";
3358                 $email ||= "$author\@$uuid";
3359                 $commit_email ||= "$author\@$uuid";
3360         } else {
3361                 my $url = $self->metadata_url;
3362                 remove_username($url);
3363                 my $uuid = $self->rewrite_uuid || $self->ra->get_uuid;
3364                 $log_entry{metadata} = "$url\@$rev " . $uuid;
3365                 $email ||= "$author\@" . $uuid;
3366                 $commit_email ||= "$author\@" . $uuid;
3367         }
3368         $log_entry{name} = $name;
3369         $log_entry{email} = $email;
3370         $log_entry{commit_name} = $commit_name;
3371         $log_entry{commit_email} = $commit_email;
3372         \%log_entry;
3375 sub fetch {
3376         my ($self, $min_rev, $max_rev, @parents) = @_;
3377         my ($last_rev, $last_commit) = $self->last_rev_commit;
3378         my ($base, $head) = $self->get_fetch_range($min_rev, $max_rev);
3379         $self->ra->gs_fetch_loop_common($base, $head, [$self]);
3382 sub set_tree_cb {
3383         my ($self, $log_entry, $tree, $rev, $date, $author) = @_;
3384         $self->{inject_parents} = { $rev => $tree };
3385         $self->fetch(undef, undef);
3388 sub set_tree {
3389         my ($self, $tree) = (shift, shift);
3390         my $log_entry = ::get_commit_entry($tree);
3391         unless ($self->{last_rev}) {
3392                 ::fatal("Must have an existing revision to commit");
3393         }
3394         my %ed_opts = ( r => $self->{last_rev},
3395                         log => $log_entry->{log},
3396                         ra => $self->ra,
3397                         tree_a => $self->{last_commit},
3398                         tree_b => $tree,
3399                         editor_cb => sub {
3400                                $self->set_tree_cb($log_entry, $tree, @_) },
3401                         svn_path => $self->{path} );
3402         if (!SVN::Git::Editor->new(\%ed_opts)->apply_diff) {
3403                 print "No changes\nr$self->{last_rev} = $tree\n";
3404         }
3407 sub rebuild_from_rev_db {
3408         my ($self, $path) = @_;
3409         my $r = -1;
3410         open my $fh, '<', $path or croak "open: $!";
3411         binmode $fh or croak "binmode: $!";
3412         while (<$fh>) {
3413                 length($_) == 41 or croak "inconsistent size in ($_) != 41";
3414                 chomp($_);
3415                 ++$r;
3416                 next if $_ eq ('0' x 40);
3417                 $self->rev_map_set($r, $_);
3418                 print "r$r = $_\n";
3419         }
3420         close $fh or croak "close: $!";
3421         unlink $path or croak "unlink: $!";
3424 sub rebuild {
3425         my ($self) = @_;
3426         my $map_path = $self->map_path;
3427         my $partial = (-e $map_path && ! -z $map_path);
3428         return unless ::verify_ref($self->refname.'^0');
3429         if (!$partial && ($self->use_svm_props || $self->no_metadata)) {
3430                 my $rev_db = $self->rev_db_path;
3431                 $self->rebuild_from_rev_db($rev_db);
3432                 if ($self->use_svm_props) {
3433                         my $svm_rev_db = $self->rev_db_path($self->svm_uuid);
3434                         $self->rebuild_from_rev_db($svm_rev_db);
3435                 }
3436                 $self->unlink_rev_db_symlink;
3437                 return;
3438         }
3439         print "Rebuilding $map_path ...\n" if (!$partial);
3440         my ($base_rev, $head) = ($partial ? $self->rev_map_max_norebuild(1) :
3441                 (undef, undef));
3442         my ($log, $ctx) =
3443             command_output_pipe(qw/rev-list --pretty=raw --no-color --reverse/,
3444                                 ($head ? "$head.." : "") . $self->refname,
3445                                 '--');
3446         my $metadata_url = $self->metadata_url;
3447         remove_username($metadata_url);
3448         my $svn_uuid = $self->rewrite_uuid || $self->ra_uuid;
3449         my $c;
3450         while (<$log>) {
3451                 if ( m{^commit ($::sha1)$} ) {
3452                         $c = $1;
3453                         next;
3454                 }
3455                 next unless s{^\s*(git-svn-id:)}{$1};
3456                 my ($url, $rev, $uuid) = ::extract_metadata($_);
3457                 remove_username($url);
3459                 # ignore merges (from set-tree)
3460                 next if (!defined $rev || !$uuid);
3462                 # if we merged or otherwise started elsewhere, this is
3463                 # how we break out of it
3464                 if (($uuid ne $svn_uuid) ||
3465                     ($metadata_url && $url && ($url ne $metadata_url))) {
3466                         next;
3467                 }
3468                 if ($partial && $head) {
3469                         print "Partial-rebuilding $map_path ...\n";
3470                         print "Currently at $base_rev = $head\n";
3471                         $head = undef;
3472                 }
3474                 $self->rev_map_set($rev, $c);
3475                 print "r$rev = $c\n";
3476         }
3477         command_close_pipe($log, $ctx);
3478         print "Done rebuilding $map_path\n" if (!$partial || !$head);
3479         my $rev_db_path = $self->rev_db_path;
3480         if (-f $self->rev_db_path) {
3481                 unlink $self->rev_db_path or croak "unlink: $!";
3482         }
3483         $self->unlink_rev_db_symlink;
3486 # rev_map:
3487 # Tie::File seems to be prone to offset errors if revisions get sparse,
3488 # it's not that fast, either.  Tie::File is also not in Perl 5.6.  So
3489 # one of my favorite modules is out :<  Next up would be one of the DBM
3490 # modules, but I'm not sure which is most portable...
3492 # This is the replacement for the rev_db format, which was too big
3493 # and inefficient for large repositories with a lot of sparse history
3494 # (mainly tags)
3496 # The format is this:
3497 #   - 24 bytes for every record,
3498 #     * 4 bytes for the integer representing an SVN revision number
3499 #     * 20 bytes representing the sha1 of a git commit
3500 #   - No empty padding records like the old format
3501 #     (except the last record, which can be overwritten)
3502 #   - new records are written append-only since SVN revision numbers
3503 #     increase monotonically
3504 #   - lookups on SVN revision number are done via a binary search
3505 #   - Piping the file to xxd -c24 is a good way of dumping it for
3506 #     viewing or editing (piped back through xxd -r), should the need
3507 #     ever arise.
3508 #   - The last record can be padding revision with an all-zero sha1
3509 #     This is used to optimize fetch performance when using multiple
3510 #     "fetch" directives in .git/config
3512 # These files are disposable unless noMetadata or useSvmProps is set
3514 sub _rev_map_set {
3515         my ($fh, $rev, $commit) = @_;
3517         binmode $fh or croak "binmode: $!";
3518         my $size = (stat($fh))[7];
3519         ($size % 24) == 0 or croak "inconsistent size: $size";
3521         my $wr_offset = 0;
3522         if ($size > 0) {
3523                 sysseek($fh, -24, SEEK_END) or croak "seek: $!";
3524                 my $read = sysread($fh, my $buf, 24) or croak "read: $!";
3525                 $read == 24 or croak "read only $read bytes (!= 24)";
3526                 my ($last_rev, $last_commit) = unpack(rev_map_fmt, $buf);
3527                 if ($last_commit eq ('0' x40)) {
3528                         if ($size >= 48) {
3529                                 sysseek($fh, -48, SEEK_END) or croak "seek: $!";
3530                                 $read = sysread($fh, $buf, 24) or
3531                                     croak "read: $!";
3532                                 $read == 24 or
3533                                     croak "read only $read bytes (!= 24)";
3534                                 ($last_rev, $last_commit) =
3535                                     unpack(rev_map_fmt, $buf);
3536                                 if ($last_commit eq ('0' x40)) {
3537                                         croak "inconsistent .rev_map\n";
3538                                 }
3539                         }
3540                         if ($last_rev >= $rev) {
3541                                 croak "last_rev is higher!: $last_rev >= $rev";
3542                         }
3543                         $wr_offset = -24;
3544                 }
3545         }
3546         sysseek($fh, $wr_offset, SEEK_END) or croak "seek: $!";
3547         syswrite($fh, pack(rev_map_fmt, $rev, $commit), 24) == 24 or
3548           croak "write: $!";
3551 sub _rev_map_reset {
3552         my ($fh, $rev, $commit) = @_;
3553         my $c = _rev_map_get($fh, $rev);
3554         $c eq $commit or die "_rev_map_reset(@_) commit $c does not match!\n";
3555         my $offset = sysseek($fh, 0, SEEK_CUR) or croak "seek: $!";
3556         truncate $fh, $offset or croak "truncate: $!";
3559 sub mkfile {
3560         my ($path) = @_;
3561         unless (-e $path) {
3562                 my ($dir, $base) = ($path =~ m#^(.*?)/?([^/]+)$#);
3563                 mkpath([$dir]) unless -d $dir;
3564                 open my $fh, '>>', $path or die "Couldn't create $path: $!\n";
3565                 close $fh or die "Couldn't close (create) $path: $!\n";
3566         }
3569 sub rev_map_set {
3570         my ($self, $rev, $commit, $update_ref, $uuid) = @_;
3571         length $commit == 40 or die "arg3 must be a full SHA1 hexsum\n";
3572         my $db = $self->map_path($uuid);
3573         my $db_lock = "$db.lock";
3574         my $sig;
3575         $update_ref ||= 0;
3576         if ($update_ref) {
3577                 $SIG{INT} = $SIG{HUP} = $SIG{TERM} = $SIG{ALRM} = $SIG{PIPE} =
3578                             $SIG{USR1} = $SIG{USR2} = sub { $sig = $_[0] };
3579         }
3580         mkfile($db);
3582         $LOCKFILES{$db_lock} = 1;
3583         my $sync;
3584         # both of these options make our .rev_db file very, very important
3585         # and we can't afford to lose it because rebuild() won't work
3586         if ($self->use_svm_props || $self->no_metadata) {
3587                 $sync = 1;
3588                 copy($db, $db_lock) or die "rev_map_set(@_): ",
3589                                            "Failed to copy: ",
3590                                            "$db => $db_lock ($!)\n";
3591         } else {
3592                 rename $db, $db_lock or die "rev_map_set(@_): ",
3593                                             "Failed to rename: ",
3594                                             "$db => $db_lock ($!)\n";
3595         }
3597         sysopen(my $fh, $db_lock, O_RDWR | O_CREAT)
3598              or croak "Couldn't open $db_lock: $!\n";
3599         $update_ref eq 'reset' ? _rev_map_reset($fh, $rev, $commit) :
3600                                  _rev_map_set($fh, $rev, $commit);
3601         if ($sync) {
3602                 $fh->flush or die "Couldn't flush $db_lock: $!\n";
3603                 $fh->sync or die "Couldn't sync $db_lock: $!\n";
3604         }
3605         close $fh or croak $!;
3606         if ($update_ref) {
3607                 $_head = $self;
3608                 my $note = "";
3609                 $note = " ($update_ref)" if ($update_ref !~ /^\d*$/);
3610                 command_noisy('update-ref', '-m', "r$rev$note",
3611                               $self->refname, $commit);
3612         }
3613         rename $db_lock, $db or die "rev_map_set(@_): ", "Failed to rename: ",
3614                                     "$db_lock => $db ($!)\n";
3615         delete $LOCKFILES{$db_lock};
3616         if ($update_ref) {
3617                 $SIG{INT} = $SIG{HUP} = $SIG{TERM} = $SIG{ALRM} = $SIG{PIPE} =
3618                             $SIG{USR1} = $SIG{USR2} = 'DEFAULT';
3619                 kill $sig, $$ if defined $sig;
3620         }
3623 # If want_commit, this will return an array of (rev, commit) where
3624 # commit _must_ be a valid commit in the archive.
3625 # Otherwise, it'll return the max revision (whether or not the
3626 # commit is valid or just a 0x40 placeholder).
3627 sub rev_map_max {
3628         my ($self, $want_commit) = @_;
3629         $self->rebuild;
3630         my ($r, $c) = $self->rev_map_max_norebuild($want_commit);
3631         $want_commit ? ($r, $c) : $r;
3634 sub rev_map_max_norebuild {
3635         my ($self, $want_commit) = @_;
3636         my $map_path = $self->map_path;
3637         stat $map_path or return $want_commit ? (0, undef) : 0;
3638         sysopen(my $fh, $map_path, O_RDONLY) or croak "open: $!";
3639         binmode $fh or croak "binmode: $!";
3640         my $size = (stat($fh))[7];
3641         ($size % 24) == 0 or croak "inconsistent size: $size";
3643         if ($size == 0) {
3644                 close $fh or croak "close: $!";
3645                 return $want_commit ? (0, undef) : 0;
3646         }
3648         sysseek($fh, -24, SEEK_END) or croak "seek: $!";
3649         sysread($fh, my $buf, 24) == 24 or croak "read: $!";
3650         my ($r, $c) = unpack(rev_map_fmt, $buf);
3651         if ($want_commit && $c eq ('0' x40)) {
3652                 if ($size < 48) {
3653                         return $want_commit ? (0, undef) : 0;
3654                 }
3655                 sysseek($fh, -48, SEEK_END) or croak "seek: $!";
3656                 sysread($fh, $buf, 24) == 24 or croak "read: $!";
3657                 ($r, $c) = unpack(rev_map_fmt, $buf);
3658                 if ($c eq ('0'x40)) {
3659                         croak "Penultimate record is all-zeroes in $map_path";
3660                 }
3661         }
3662         close $fh or croak "close: $!";
3663         $want_commit ? ($r, $c) : $r;
3666 sub rev_map_get {
3667         my ($self, $rev, $uuid) = @_;
3668         my $map_path = $self->map_path($uuid);
3669         return undef unless -e $map_path;
3671         sysopen(my $fh, $map_path, O_RDONLY) or croak "open: $!";
3672         my $c = _rev_map_get($fh, $rev);
3673         close($fh) or croak "close: $!";
3674         $c
3677 sub _rev_map_get {
3678         my ($fh, $rev) = @_;
3680         binmode $fh or croak "binmode: $!";
3681         my $size = (stat($fh))[7];
3682         ($size % 24) == 0 or croak "inconsistent size: $size";
3684         if ($size == 0) {
3685                 return undef;
3686         }
3688         my ($l, $u) = (0, $size - 24);
3689         my ($r, $c, $buf);
3691         while ($l <= $u) {
3692                 my $i = int(($l/24 + $u/24) / 2) * 24;
3693                 sysseek($fh, $i, SEEK_SET) or croak "seek: $!";
3694                 sysread($fh, my $buf, 24) == 24 or croak "read: $!";
3695                 my ($r, $c) = unpack(rev_map_fmt, $buf);
3697                 if ($r < $rev) {
3698                         $l = $i + 24;
3699                 } elsif ($r > $rev) {
3700                         $u = $i - 24;
3701                 } else { # $r == $rev
3702                         return $c eq ('0' x 40) ? undef : $c;
3703                 }
3704         }
3705         undef;
3708 # Finds the first svn revision that exists on (if $eq_ok is true) or
3709 # before $rev for the current branch.  It will not search any lower
3710 # than $min_rev.  Returns the git commit hash and svn revision number
3711 # if found, else (undef, undef).
3712 sub find_rev_before {
3713         my ($self, $rev, $eq_ok, $min_rev) = @_;
3714         --$rev unless $eq_ok;
3715         $min_rev ||= 1;
3716         my $max_rev = $self->rev_map_max;
3717         $rev = $max_rev if ($rev > $max_rev);
3718         while ($rev >= $min_rev) {
3719                 if (my $c = $self->rev_map_get($rev)) {
3720                         return ($rev, $c);
3721                 }
3722                 --$rev;
3723         }
3724         return (undef, undef);
3727 # Finds the first svn revision that exists on (if $eq_ok is true) or
3728 # after $rev for the current branch.  It will not search any higher
3729 # than $max_rev.  Returns the git commit hash and svn revision number
3730 # if found, else (undef, undef).
3731 sub find_rev_after {
3732         my ($self, $rev, $eq_ok, $max_rev) = @_;
3733         ++$rev unless $eq_ok;
3734         $max_rev ||= $self->rev_map_max;
3735         while ($rev <= $max_rev) {
3736                 if (my $c = $self->rev_map_get($rev)) {
3737                         return ($rev, $c);
3738                 }
3739                 ++$rev;
3740         }
3741         return (undef, undef);
3744 sub _new {
3745         my ($class, $repo_id, $ref_id, $path) = @_;
3746         unless (defined $repo_id && length $repo_id) {
3747                 $repo_id = $Git::SVN::default_repo_id;
3748         }
3749         unless (defined $ref_id && length $ref_id) {
3750                 $_prefix = '' unless defined($_prefix);
3751                 $_[2] = $ref_id =
3752                              "refs/remotes/$_prefix$Git::SVN::default_ref_id";
3753         }
3754         $_[1] = $repo_id;
3755         my $dir = "$ENV{GIT_DIR}/svn/$ref_id";
3757         # Older repos imported by us used $GIT_DIR/svn/foo instead of
3758         # $GIT_DIR/svn/refs/remotes/foo when tracking refs/remotes/foo
3759         if ($ref_id =~ m{^refs/remotes/(.*)}) {
3760                 my $old_dir = "$ENV{GIT_DIR}/svn/$1";
3761                 if (-d $old_dir && ! -d $dir) {
3762                         $dir = $old_dir;
3763                 }
3764         }
3766         $_[3] = $path = '' unless (defined $path);
3767         mkpath([$dir]);
3768         bless {
3769                 ref_id => $ref_id, dir => $dir, index => "$dir/index",
3770                 path => $path, config => "$ENV{GIT_DIR}/svn/config",
3771                 map_root => "$dir/.rev_map", repo_id => $repo_id }, $class;
3774 # for read-only access of old .rev_db formats
3775 sub unlink_rev_db_symlink {
3776         my ($self) = @_;
3777         my $link = $self->rev_db_path;
3778         $link =~ s/\.[\w-]+$// or croak "missing UUID at the end of $link";
3779         if (-l $link) {
3780                 unlink $link or croak "unlink: $link failed!";
3781         }
3784 sub rev_db_path {
3785         my ($self, $uuid) = @_;
3786         my $db_path = $self->map_path($uuid);
3787         $db_path =~ s{/\.rev_map\.}{/\.rev_db\.}
3788             or croak "map_path: $db_path does not contain '/.rev_map.' !";
3789         $db_path;
3792 # the new replacement for .rev_db
3793 sub map_path {
3794         my ($self, $uuid) = @_;
3795         $uuid ||= $self->ra_uuid;
3796         "$self->{map_root}.$uuid";
3799 sub uri_encode {
3800         my ($f) = @_;
3801         $f =~ s#([^a-zA-Z0-9\*!\:_\./\-])#uc sprintf("%%%02x",ord($1))#eg;
3802         $f
3805 sub uri_decode {
3806         my ($f) = @_;
3807         $f =~ s#%([0-9a-fA-F]{2})#chr(hex($1))#eg;
3808         $f
3811 sub remove_username {
3812         $_[0] =~ s{^([^:]*://)[^@]+@}{$1};
3815 package Git::SVN::Prompt;
3816 use strict;
3817 use warnings;
3818 require SVN::Core;
3819 use vars qw/$_no_auth_cache $_username/;
3821 sub simple {
3822         my ($cred, $realm, $default_username, $may_save, $pool) = @_;
3823         $may_save = undef if $_no_auth_cache;
3824         $default_username = $_username if defined $_username;
3825         if (defined $default_username && length $default_username) {
3826                 if (defined $realm && length $realm) {
3827                         print STDERR "Authentication realm: $realm\n";
3828                         STDERR->flush;
3829                 }
3830                 $cred->username($default_username);
3831         } else {
3832                 username($cred, $realm, $may_save, $pool);
3833         }
3834         $cred->password(_read_password("Password for '" .
3835                                        $cred->username . "': ", $realm));
3836         $cred->may_save($may_save);
3837         $SVN::_Core::SVN_NO_ERROR;
3840 sub ssl_server_trust {
3841         my ($cred, $realm, $failures, $cert_info, $may_save, $pool) = @_;
3842         $may_save = undef if $_no_auth_cache;
3843         print STDERR "Error validating server certificate for '$realm':\n";
3844         {
3845                 no warnings 'once';
3846                 # All variables SVN::Auth::SSL::* are used only once,
3847                 # so we're shutting up Perl warnings about this.
3848                 if ($failures & $SVN::Auth::SSL::UNKNOWNCA) {
3849                         print STDERR " - The certificate is not issued ",
3850                             "by a trusted authority. Use the\n",
3851                             "   fingerprint to validate ",
3852                             "the certificate manually!\n";
3853                 }
3854                 if ($failures & $SVN::Auth::SSL::CNMISMATCH) {
3855                         print STDERR " - The certificate hostname ",
3856                             "does not match.\n";
3857                 }
3858                 if ($failures & $SVN::Auth::SSL::NOTYETVALID) {
3859                         print STDERR " - The certificate is not yet valid.\n";
3860                 }
3861                 if ($failures & $SVN::Auth::SSL::EXPIRED) {
3862                         print STDERR " - The certificate has expired.\n";
3863                 }
3864                 if ($failures & $SVN::Auth::SSL::OTHER) {
3865                         print STDERR " - The certificate has ",
3866                             "an unknown error.\n";
3867                 }
3868         } # no warnings 'once'
3869         printf STDERR
3870                 "Certificate information:\n".
3871                 " - Hostname: %s\n".
3872                 " - Valid: from %s until %s\n".
3873                 " - Issuer: %s\n".
3874                 " - Fingerprint: %s\n",
3875                 map $cert_info->$_, qw(hostname valid_from valid_until
3876                                        issuer_dname fingerprint);
3877         my $choice;
3878 prompt:
3879         print STDERR $may_save ?
3880               "(R)eject, accept (t)emporarily or accept (p)ermanently? " :
3881               "(R)eject or accept (t)emporarily? ";
3882         STDERR->flush;
3883         $choice = lc(substr(<STDIN> || 'R', 0, 1));
3884         if ($choice =~ /^t$/i) {
3885                 $cred->may_save(undef);
3886         } elsif ($choice =~ /^r$/i) {
3887                 return -1;
3888         } elsif ($may_save && $choice =~ /^p$/i) {
3889                 $cred->may_save($may_save);
3890         } else {
3891                 goto prompt;
3892         }
3893         $cred->accepted_failures($failures);
3894         $SVN::_Core::SVN_NO_ERROR;
3897 sub ssl_client_cert {
3898         my ($cred, $realm, $may_save, $pool) = @_;
3899         $may_save = undef if $_no_auth_cache;
3900         print STDERR "Client certificate filename: ";
3901         STDERR->flush;
3902         chomp(my $filename = <STDIN>);
3903         $cred->cert_file($filename);
3904         $cred->may_save($may_save);
3905         $SVN::_Core::SVN_NO_ERROR;
3908 sub ssl_client_cert_pw {
3909         my ($cred, $realm, $may_save, $pool) = @_;
3910         $may_save = undef if $_no_auth_cache;
3911         $cred->password(_read_password("Password: ", $realm));
3912         $cred->may_save($may_save);
3913         $SVN::_Core::SVN_NO_ERROR;
3916 sub username {
3917         my ($cred, $realm, $may_save, $pool) = @_;
3918         $may_save = undef if $_no_auth_cache;
3919         if (defined $realm && length $realm) {
3920                 print STDERR "Authentication realm: $realm\n";
3921         }
3922         my $username;
3923         if (defined $_username) {
3924                 $username = $_username;
3925         } else {
3926                 print STDERR "Username: ";
3927                 STDERR->flush;
3928                 chomp($username = <STDIN>);
3929         }
3930         $cred->username($username);
3931         $cred->may_save($may_save);
3932         $SVN::_Core::SVN_NO_ERROR;
3935 sub _read_password {
3936         my ($prompt, $realm) = @_;
3937         print STDERR $prompt;
3938         STDERR->flush;
3939         require Term::ReadKey;
3940         Term::ReadKey::ReadMode('noecho');
3941         my $password = '';
3942         while (defined(my $key = Term::ReadKey::ReadKey(0))) {
3943                 last if $key =~ /[\012\015]/; # \n\r
3944                 $password .= $key;
3945         }
3946         Term::ReadKey::ReadMode('restore');
3947         print STDERR "\n";
3948         STDERR->flush;
3949         $password;
3952 package SVN::Git::Fetcher;
3953 use vars qw/@ISA/;
3954 use strict;
3955 use warnings;
3956 use Carp qw/croak/;
3957 use File::Temp qw/tempfile/;
3958 use IO::File qw//;
3959 use vars qw/$_ignore_regex/;
3961 # file baton members: path, mode_a, mode_b, pool, fh, blob, base
3962 sub new {
3963         my ($class, $git_svn, $switch_path) = @_;
3964         my $self = SVN::Delta::Editor->new;
3965         bless $self, $class;
3966         if (exists $git_svn->{last_commit}) {
3967                 $self->{c} = $git_svn->{last_commit};
3968                 $self->{empty_symlinks} =
3969                                   _mark_empty_symlinks($git_svn, $switch_path);
3970         }
3971         $self->{ignore_regex} = eval { command_oneline('config', '--get',
3972                              "svn-remote.$git_svn->{repo_id}.ignore-paths") };
3973         $self->{empty} = {};
3974         $self->{dir_prop} = {};
3975         $self->{file_prop} = {};
3976         $self->{absent_dir} = {};
3977         $self->{absent_file} = {};
3978         $self->{gii} = $git_svn->tmp_index_do(sub { Git::IndexInfo->new });
3979         $self;
3982 # this uses the Ra object, so it must be called before do_{switch,update},
3983 # not inside them (when the Git::SVN::Fetcher object is passed) to
3984 # do_{switch,update}
3985 sub _mark_empty_symlinks {
3986         my ($git_svn, $switch_path) = @_;
3987         my $bool = Git::config_bool('svn.brokenSymlinkWorkaround');
3988         return {} if (!defined($bool)) || (defined($bool) && ! $bool);
3990         my %ret;
3991         my ($rev, $cmt) = $git_svn->last_rev_commit;
3992         return {} unless ($rev && $cmt);
3994         # allow the warning to be printed for each revision we fetch to
3995         # ensure the user sees it.  The user can also disable the workaround
3996         # on the repository even while git svn is running and the next
3997         # revision fetched will skip this expensive function.
3998         my $printed_warning;
3999         chomp(my $empty_blob = `git hash-object -t blob --stdin < /dev/null`);
4000         my ($ls, $ctx) = command_output_pipe(qw/ls-tree -r -z/, $cmt);
4001         local $/ = "\0";
4002         my $pfx = defined($switch_path) ? $switch_path : $git_svn->{path};
4003         $pfx .= '/' if length($pfx);
4004         while (<$ls>) {
4005                 chomp;
4006                 s/\A100644 blob $empty_blob\t//o or next;
4007                 unless ($printed_warning) {
4008                         print STDERR "Scanning for empty symlinks, ",
4009                                      "this may take a while if you have ",
4010                                      "many empty files\n",
4011                                      "You may disable this with `",
4012                                      "git config svn.brokenSymlinkWorkaround ",
4013                                      "false'.\n",
4014                                      "This may be done in a different ",
4015                                      "terminal without restarting ",
4016                                      "git svn\n";
4017                         $printed_warning = 1;
4018                 }
4019                 my $path = $_;
4020                 my (undef, $props) =
4021                                $git_svn->ra->get_file($pfx.$path, $rev, undef);
4022                 if ($props->{'svn:special'}) {
4023                         $ret{$path} = 1;
4024                 }
4025         }
4026         command_close_pipe($ls, $ctx);
4027         \%ret;
4030 # returns true if a given path is inside a ".git" directory
4031 sub in_dot_git {
4032         $_[0] =~ m{(?:^|/)\.git(?:/|$)};
4035 # return value: 0 -- don't ignore, 1 -- ignore
4036 sub is_path_ignored {
4037         my ($self, $path) = @_;
4038         return 1 if in_dot_git($path);
4039         return 1 if defined($self->{ignore_regex}) &&
4040                     $path =~ m!$self->{ignore_regex}!;
4041         return 0 unless defined($_ignore_regex);
4042         return 1 if $path =~ m!$_ignore_regex!o;
4043         return 0;
4046 sub set_path_strip {
4047         my ($self, $path) = @_;
4048         $self->{path_strip} = qr/^\Q$path\E(\/|$)/ if length $path;
4051 sub open_root {
4052         { path => '' };
4055 sub open_directory {
4056         my ($self, $path, $pb, $rev) = @_;
4057         { path => $path };
4060 sub git_path {
4061         my ($self, $path) = @_;
4062         if ($self->{path_strip}) {
4063                 $path =~ s!$self->{path_strip}!! or
4064                   die "Failed to strip path '$path' ($self->{path_strip})\n";
4065         }
4066         $path;
4069 sub delete_entry {
4070         my ($self, $path, $rev, $pb) = @_;
4071         return undef if $self->is_path_ignored($path);
4073         my $gpath = $self->git_path($path);
4074         return undef if ($gpath eq '');
4076         # remove entire directories.
4077         my ($tree) = (command('ls-tree', '-z', $self->{c}, "./$gpath")
4078                          =~ /\A040000 tree ([a-f\d]{40})\t\Q$gpath\E\0/);
4079         if ($tree) {
4080                 my ($ls, $ctx) = command_output_pipe(qw/ls-tree
4081                                                      -r --name-only -z/,
4082                                                      $tree);
4083                 local $/ = "\0";
4084                 while (<$ls>) {
4085                         chomp;
4086                         my $rmpath = "$gpath/$_";
4087                         $self->{gii}->remove($rmpath);
4088                         print "\tD\t$rmpath\n" unless $::_q;
4089                 }
4090                 print "\tD\t$gpath/\n" unless $::_q;
4091                 command_close_pipe($ls, $ctx);
4092         } else {
4093                 $self->{gii}->remove($gpath);
4094                 print "\tD\t$gpath\n" unless $::_q;
4095         }
4096         $self->{empty}->{$path} = 0;
4097         undef;
4100 sub open_file {
4101         my ($self, $path, $pb, $rev) = @_;
4102         my ($mode, $blob);
4104         goto out if $self->is_path_ignored($path);
4106         my $gpath = $self->git_path($path);
4107         ($mode, $blob) = (command('ls-tree', '-z', $self->{c}, "./$gpath")
4108                              =~ /\A(\d{6}) blob ([a-f\d]{40})\t\Q$gpath\E\0/);
4109         unless (defined $mode && defined $blob) {
4110                 die "$path was not found in commit $self->{c} (r$rev)\n";
4111         }
4112         if ($mode eq '100644' && $self->{empty_symlinks}->{$path}) {
4113                 $mode = '120000';
4114         }
4115 out:
4116         { path => $path, mode_a => $mode, mode_b => $mode, blob => $blob,
4117           pool => SVN::Pool->new, action => 'M' };
4120 sub add_file {
4121         my ($self, $path, $pb, $cp_path, $cp_rev) = @_;
4122         my $mode;
4124         if (!$self->is_path_ignored($path)) {
4125                 my ($dir, $file) = ($path =~ m#^(.*?)/?([^/]+)$#);
4126                 delete $self->{empty}->{$dir};
4127                 $mode = '100644';
4128         }
4129         { path => $path, mode_a => $mode, mode_b => $mode,
4130           pool => SVN::Pool->new, action => 'A' };
4133 sub add_directory {
4134         my ($self, $path, $cp_path, $cp_rev) = @_;
4135         goto out if $self->is_path_ignored($path);
4136         my $gpath = $self->git_path($path);
4137         if ($gpath eq '') {
4138                 my ($ls, $ctx) = command_output_pipe(qw/ls-tree
4139                                                      -r --name-only -z/,
4140                                                      $self->{c});
4141                 local $/ = "\0";
4142                 while (<$ls>) {
4143                         chomp;
4144                         $self->{gii}->remove($_);
4145                         print "\tD\t$_\n" unless $::_q;
4146                 }
4147                 command_close_pipe($ls, $ctx);
4148                 $self->{empty}->{$path} = 0;
4149         }
4150         my ($dir, $file) = ($path =~ m#^(.*?)/?([^/]+)$#);
4151         delete $self->{empty}->{$dir};
4152         $self->{empty}->{$path} = 1;
4153 out:
4154         { path => $path };
4157 sub change_dir_prop {
4158         my ($self, $db, $prop, $value) = @_;
4159         return undef if $self->is_path_ignored($db->{path});
4160         $self->{dir_prop}->{$db->{path}} ||= {};
4161         $self->{dir_prop}->{$db->{path}}->{$prop} = $value;
4162         undef;
4165 sub absent_directory {
4166         my ($self, $path, $pb) = @_;
4167         return undef if $self->is_path_ignored($path);
4168         $self->{absent_dir}->{$pb->{path}} ||= [];
4169         push @{$self->{absent_dir}->{$pb->{path}}}, $path;
4170         undef;
4173 sub absent_file {
4174         my ($self, $path, $pb) = @_;
4175         return undef if $self->is_path_ignored($path);
4176         $self->{absent_file}->{$pb->{path}} ||= [];
4177         push @{$self->{absent_file}->{$pb->{path}}}, $path;
4178         undef;
4181 sub change_file_prop {
4182         my ($self, $fb, $prop, $value) = @_;
4183         return undef if $self->is_path_ignored($fb->{path});
4184         if ($prop eq 'svn:executable') {
4185                 if ($fb->{mode_b} != 120000) {
4186                         $fb->{mode_b} = defined $value ? 100755 : 100644;
4187                 }
4188         } elsif ($prop eq 'svn:special') {
4189                 $fb->{mode_b} = defined $value ? 120000 : 100644;
4190         } else {
4191                 $self->{file_prop}->{$fb->{path}} ||= {};
4192                 $self->{file_prop}->{$fb->{path}}->{$prop} = $value;
4193         }
4194         undef;
4197 sub apply_textdelta {
4198         my ($self, $fb, $exp) = @_;
4199         return undef if $self->is_path_ignored($fb->{path});
4200         my $fh = $::_repository->temp_acquire('svn_delta');
4201         # $fh gets auto-closed() by SVN::TxDelta::apply(),
4202         # (but $base does not,) so dup() it for reading in close_file
4203         open my $dup, '<&', $fh or croak $!;
4204         my $base = $::_repository->temp_acquire('git_blob');
4206         if ($fb->{blob}) {
4207                 my ($base_is_link, $size);
4209                 if ($fb->{mode_a} eq '120000' &&
4210                     ! $self->{empty_symlinks}->{$fb->{path}}) {
4211                         print $base 'link ' or die "print $!\n";
4212                         $base_is_link = 1;
4213                 }
4214         retry:
4215                 $size = $::_repository->cat_blob($fb->{blob}, $base);
4216                 die "Failed to read object $fb->{blob}" if ($size < 0);
4218                 if (defined $exp) {
4219                         seek $base, 0, 0 or croak $!;
4220                         my $got = ::md5sum($base);
4221                         if ($got ne $exp) {
4222                                 my $err = "Checksum mismatch: ".
4223                                        "$fb->{path} $fb->{blob}\n" .
4224                                        "expected: $exp\n" .
4225                                        "     got: $got\n";
4226                                 if ($base_is_link) {
4227                                         warn $err,
4228                                              "Retrying... (possibly ",
4229                                              "a bad symlink from SVN)\n";
4230                                         $::_repository->temp_reset($base);
4231                                         $base_is_link = 0;
4232                                         goto retry;
4233                                 }
4234                                 die $err;
4235                         }
4236                 }
4237         }
4238         seek $base, 0, 0 or croak $!;
4239         $fb->{fh} = $fh;
4240         $fb->{base} = $base;
4241         [ SVN::TxDelta::apply($base, $dup, undef, $fb->{path}, $fb->{pool}) ];
4244 sub close_file {
4245         my ($self, $fb, $exp) = @_;
4246         return undef if $self->is_path_ignored($fb->{path});
4248         my $hash;
4249         my $path = $self->git_path($fb->{path});
4250         if (my $fh = $fb->{fh}) {
4251                 if (defined $exp) {
4252                         seek($fh, 0, 0) or croak $!;
4253                         my $got = ::md5sum($fh);
4254                         if ($got ne $exp) {
4255                                 die "Checksum mismatch: $path\n",
4256                                     "expected: $exp\n    got: $got\n";
4257                         }
4258                 }
4259                 if ($fb->{mode_b} == 120000) {
4260                         sysseek($fh, 0, 0) or croak $!;
4261                         my $rd = sysread($fh, my $buf, 5);
4263                         if (!defined $rd) {
4264                                 croak "sysread: $!\n";
4265                         } elsif ($rd == 0) {
4266                                 warn "$path has mode 120000",
4267                                      " but it points to nothing\n",
4268                                      "converting to an empty file with mode",
4269                                      " 100644\n";
4270                                 $fb->{mode_b} = '100644';
4271                         } elsif ($buf ne 'link ') {
4272                                 warn "$path has mode 120000",
4273                                      " but is not a link\n";
4274                         } else {
4275                                 my $tmp_fh = $::_repository->temp_acquire(
4276                                         'svn_hash');
4277                                 my $res;
4278                                 while ($res = sysread($fh, my $str, 1024)) {
4279                                         my $out = syswrite($tmp_fh, $str, $res);
4280                                         defined($out) && $out == $res
4281                                                 or croak("write ",
4282                                                         Git::temp_path($tmp_fh),
4283                                                         ": $!\n");
4284                                 }
4285                                 defined $res or croak $!;
4287                                 ($fh, $tmp_fh) = ($tmp_fh, $fh);
4288                                 Git::temp_release($tmp_fh, 1);
4289                         }
4290                 }
4292                 $hash = $::_repository->hash_and_insert_object(
4293                                 Git::temp_path($fh));
4294                 $hash =~ /^[a-f\d]{40}$/ or die "not a sha1: $hash\n";
4296                 Git::temp_release($fb->{base}, 1);
4297                 Git::temp_release($fh, 1);
4298         } else {
4299                 $hash = $fb->{blob} or die "no blob information\n";
4300         }
4301         $fb->{pool}->clear;
4302         $self->{gii}->update($fb->{mode_b}, $hash, $path) or croak $!;
4303         print "\t$fb->{action}\t$path\n" if $fb->{action} && ! $::_q;
4304         undef;
4307 sub abort_edit {
4308         my $self = shift;
4309         $self->{nr} = $self->{gii}->{nr};
4310         delete $self->{gii};
4311         $self->SUPER::abort_edit(@_);
4314 sub close_edit {
4315         my $self = shift;
4316         $self->{git_commit_ok} = 1;
4317         $self->{nr} = $self->{gii}->{nr};
4318         delete $self->{gii};
4319         $self->SUPER::close_edit(@_);
4322 package SVN::Git::Editor;
4323 use vars qw/@ISA $_rmdir $_cp_similarity $_find_copies_harder $_rename_limit/;
4324 use strict;
4325 use warnings;
4326 use Carp qw/croak/;
4327 use IO::File;
4329 sub new {
4330         my ($class, $opts) = @_;
4331         foreach (qw/svn_path r ra tree_a tree_b log editor_cb/) {
4332                 die "$_ required!\n" unless (defined $opts->{$_});
4333         }
4335         my $pool = SVN::Pool->new;
4336         my $mods = generate_diff($opts->{tree_a}, $opts->{tree_b});
4337         my $types = check_diff_paths($opts->{ra}, $opts->{svn_path},
4338                                      $opts->{r}, $mods);
4340         # $opts->{ra} functions should not be used after this:
4341         my @ce  = $opts->{ra}->get_commit_editor($opts->{log},
4342                                                 $opts->{editor_cb}, $pool);
4343         my $self = SVN::Delta::Editor->new(@ce, $pool);
4344         bless $self, $class;
4345         foreach (qw/svn_path r tree_a tree_b/) {
4346                 $self->{$_} = $opts->{$_};
4347         }
4348         $self->{url} = $opts->{ra}->{url};
4349         $self->{mods} = $mods;
4350         $self->{types} = $types;
4351         $self->{pool} = $pool;
4352         $self->{bat} = { '' => $self->open_root($self->{r}, $self->{pool}) };
4353         $self->{rm} = { };
4354         $self->{path_prefix} = length $self->{svn_path} ?
4355                                "$self->{svn_path}/" : '';
4356         $self->{config} = $opts->{config};
4357         return $self;
4360 sub generate_diff {
4361         my ($tree_a, $tree_b) = @_;
4362         my @diff_tree = qw(diff-tree -z -r);
4363         if ($_cp_similarity) {
4364                 push @diff_tree, "-C$_cp_similarity";
4365         } else {
4366                 push @diff_tree, '-C';
4367         }
4368         push @diff_tree, '--find-copies-harder' if $_find_copies_harder;
4369         push @diff_tree, "-l$_rename_limit" if defined $_rename_limit;
4370         push @diff_tree, $tree_a, $tree_b;
4371         my ($diff_fh, $ctx) = command_output_pipe(@diff_tree);
4372         local $/ = "\0";
4373         my $state = 'meta';
4374         my @mods;
4375         while (<$diff_fh>) {
4376                 chomp $_; # this gets rid of the trailing "\0"
4377                 if ($state eq 'meta' && /^:(\d{6})\s(\d{6})\s
4378                                         ($::sha1)\s($::sha1)\s
4379                                         ([MTCRAD])\d*$/xo) {
4380                         push @mods, {   mode_a => $1, mode_b => $2,
4381                                         sha1_a => $3, sha1_b => $4,
4382                                         chg => $5 };
4383                         if ($5 =~ /^(?:C|R)$/) {
4384                                 $state = 'file_a';
4385                         } else {
4386                                 $state = 'file_b';
4387                         }
4388                 } elsif ($state eq 'file_a') {
4389                         my $x = $mods[$#mods] or croak "Empty array\n";
4390                         if ($x->{chg} !~ /^(?:C|R)$/) {
4391                                 croak "Error parsing $_, $x->{chg}\n";
4392                         }
4393                         $x->{file_a} = $_;
4394                         $state = 'file_b';
4395                 } elsif ($state eq 'file_b') {
4396                         my $x = $mods[$#mods] or croak "Empty array\n";
4397                         if (exists $x->{file_a} && $x->{chg} !~ /^(?:C|R)$/) {
4398                                 croak "Error parsing $_, $x->{chg}\n";
4399                         }
4400                         if (!exists $x->{file_a} && $x->{chg} =~ /^(?:C|R)$/) {
4401                                 croak "Error parsing $_, $x->{chg}\n";
4402                         }
4403                         $x->{file_b} = $_;
4404                         $state = 'meta';
4405                 } else {
4406                         croak "Error parsing $_\n";
4407                 }
4408         }
4409         command_close_pipe($diff_fh, $ctx);
4410         \@mods;
4413 sub check_diff_paths {
4414         my ($ra, $pfx, $rev, $mods) = @_;
4415         my %types;
4416         $pfx .= '/' if length $pfx;
4418         sub type_diff_paths {
4419                 my ($ra, $types, $path, $rev) = @_;
4420                 my @p = split m#/+#, $path;
4421                 my $c = shift @p;
4422                 unless (defined $types->{$c}) {
4423                         $types->{$c} = $ra->check_path($c, $rev);
4424                 }
4425                 while (@p) {
4426                         $c .= '/' . shift @p;
4427                         next if defined $types->{$c};
4428                         $types->{$c} = $ra->check_path($c, $rev);
4429                 }
4430         }
4432         foreach my $m (@$mods) {
4433                 foreach my $f (qw/file_a file_b/) {
4434                         next unless defined $m->{$f};
4435                         my ($dir) = ($m->{$f} =~ m#^(.*?)/?(?:[^/]+)$#);
4436                         if (length $pfx.$dir && ! defined $types{$dir}) {
4437                                 type_diff_paths($ra, \%types, $pfx.$dir, $rev);
4438                         }
4439                 }
4440         }
4441         \%types;
4444 sub split_path {
4445         return ($_[0] =~ m#^(.*?)/?([^/]+)$#);
4448 sub repo_path {
4449         my ($self, $path) = @_;
4450         $self->{path_prefix}.(defined $path ? $path : '');
4453 sub url_path {
4454         my ($self, $path) = @_;
4455         if ($self->{url} =~ m#^https?://#) {
4456                 $path =~ s!([^~a-zA-Z0-9_./-])!uc sprintf("%%%02x",ord($1))!eg;
4457         }
4458         $self->{url} . '/' . $self->repo_path($path);
4461 sub rmdirs {
4462         my ($self) = @_;
4463         my $rm = $self->{rm};
4464         delete $rm->{''}; # we never delete the url we're tracking
4465         return unless %$rm;
4467         foreach (keys %$rm) {
4468                 my @d = split m#/#, $_;
4469                 my $c = shift @d;
4470                 $rm->{$c} = 1;
4471                 while (@d) {
4472                         $c .= '/' . shift @d;
4473                         $rm->{$c} = 1;
4474                 }
4475         }
4476         delete $rm->{$self->{svn_path}};
4477         delete $rm->{''}; # we never delete the url we're tracking
4478         return unless %$rm;
4480         my ($fh, $ctx) = command_output_pipe(qw/ls-tree --name-only -r -z/,
4481                                              $self->{tree_b});
4482         local $/ = "\0";
4483         while (<$fh>) {
4484                 chomp;
4485                 my @dn = split m#/#, $_;
4486                 while (pop @dn) {
4487                         delete $rm->{join '/', @dn};
4488                 }
4489                 unless (%$rm) {
4490                         close $fh;
4491                         return;
4492                 }
4493         }
4494         command_close_pipe($fh, $ctx);
4496         my ($r, $p, $bat) = ($self->{r}, $self->{pool}, $self->{bat});
4497         foreach my $d (sort { $b =~ tr#/#/# <=> $a =~ tr#/#/# } keys %$rm) {
4498                 $self->close_directory($bat->{$d}, $p);
4499                 my ($dn) = ($d =~ m#^(.*?)/?(?:[^/]+)$#);
4500                 print "\tD+\t$d/\n" unless $::_q;
4501                 $self->SUPER::delete_entry($d, $r, $bat->{$dn}, $p);
4502                 delete $bat->{$d};
4503         }
4506 sub open_or_add_dir {
4507         my ($self, $full_path, $baton) = @_;
4508         my $t = $self->{types}->{$full_path};
4509         if (!defined $t) {
4510                 die "$full_path not known in r$self->{r} or we have a bug!\n";
4511         }
4512         {
4513                 no warnings 'once';
4514                 # SVN::Node::none and SVN::Node::file are used only once,
4515                 # so we're shutting up Perl's warnings about them.
4516                 if ($t == $SVN::Node::none) {
4517                         return $self->add_directory($full_path, $baton,
4518                             undef, -1, $self->{pool});
4519                 } elsif ($t == $SVN::Node::dir) {
4520                         return $self->open_directory($full_path, $baton,
4521                             $self->{r}, $self->{pool});
4522                 } # no warnings 'once'
4523                 print STDERR "$full_path already exists in repository at ",
4524                     "r$self->{r} and it is not a directory (",
4525                     ($t == $SVN::Node::file ? 'file' : 'unknown'),"/$t)\n";
4526         } # no warnings 'once'
4527         exit 1;
4530 sub ensure_path {
4531         my ($self, $path) = @_;
4532         my $bat = $self->{bat};
4533         my $repo_path = $self->repo_path($path);
4534         return $bat->{''} unless (length $repo_path);
4535         my @p = split m#/+#, $repo_path;
4536         my $c = shift @p;
4537         $bat->{$c} ||= $self->open_or_add_dir($c, $bat->{''});
4538         while (@p) {
4539                 my $c0 = $c;
4540                 $c .= '/' . shift @p;
4541                 $bat->{$c} ||= $self->open_or_add_dir($c, $bat->{$c0});
4542         }
4543         return $bat->{$c};
4546 # Subroutine to convert a globbing pattern to a regular expression.
4547 # From perl cookbook.
4548 sub glob2pat {
4549         my $globstr = shift;
4550         my %patmap = ('*' => '.*', '?' => '.', '[' => '[', ']' => ']');
4551         $globstr =~ s{(.)} { $patmap{$1} || "\Q$1" }ge;
4552         return '^' . $globstr . '$';
4555 sub check_autoprop {
4556         my ($self, $pattern, $properties, $file, $fbat) = @_;
4557         # Convert the globbing pattern to a regular expression.
4558         my $regex = glob2pat($pattern);
4559         # Check if the pattern matches the file name.
4560         if($file =~ m/($regex)/) {
4561                 # Parse the list of properties to set.
4562                 my @props = split(/;/, $properties);
4563                 foreach my $prop (@props) {
4564                         # Parse 'name=value' syntax and set the property.
4565                         if ($prop =~ /([^=]+)=(.*)/) {
4566                                 my ($n,$v) = ($1,$2);
4567                                 for ($n, $v) {
4568                                         s/^\s+//; s/\s+$//;
4569                                 }
4570                                 $self->change_file_prop($fbat, $n, $v);
4571                         }
4572                 }
4573         }
4576 sub apply_autoprops {
4577         my ($self, $file, $fbat) = @_;
4578         my $conf_t = ${$self->{config}}{'config'};
4579         no warnings 'once';
4580         # Check [miscellany]/enable-auto-props in svn configuration.
4581         if (SVN::_Core::svn_config_get_bool(
4582                 $conf_t,
4583                 $SVN::_Core::SVN_CONFIG_SECTION_MISCELLANY,
4584                 $SVN::_Core::SVN_CONFIG_OPTION_ENABLE_AUTO_PROPS,
4585                 0)) {
4586                 # Auto-props are enabled.  Enumerate them to look for matches.
4587                 my $callback = sub {
4588                         $self->check_autoprop($_[0], $_[1], $file, $fbat);
4589                 };
4590                 SVN::_Core::svn_config_enumerate(
4591                         $conf_t,
4592                         $SVN::_Core::SVN_CONFIG_SECTION_AUTO_PROPS,
4593                         $callback);
4594         }
4597 sub A {
4598         my ($self, $m) = @_;
4599         my ($dir, $file) = split_path($m->{file_b});
4600         my $pbat = $self->ensure_path($dir);
4601         my $fbat = $self->add_file($self->repo_path($m->{file_b}), $pbat,
4602                                         undef, -1);
4603         print "\tA\t$m->{file_b}\n" unless $::_q;
4604         $self->apply_autoprops($file, $fbat);
4605         $self->chg_file($fbat, $m);
4606         $self->close_file($fbat,undef,$self->{pool});
4609 sub C {
4610         my ($self, $m) = @_;
4611         my ($dir, $file) = split_path($m->{file_b});
4612         my $pbat = $self->ensure_path($dir);
4613         my $fbat = $self->add_file($self->repo_path($m->{file_b}), $pbat,
4614                                 $self->url_path($m->{file_a}), $self->{r});
4615         print "\tC\t$m->{file_a} => $m->{file_b}\n" unless $::_q;
4616         $self->chg_file($fbat, $m);
4617         $self->close_file($fbat,undef,$self->{pool});
4620 sub delete_entry {
4621         my ($self, $path, $pbat) = @_;
4622         my $rpath = $self->repo_path($path);
4623         my ($dir, $file) = split_path($rpath);
4624         $self->{rm}->{$dir} = 1;
4625         $self->SUPER::delete_entry($rpath, $self->{r}, $pbat, $self->{pool});
4628 sub R {
4629         my ($self, $m) = @_;
4630         my ($dir, $file) = split_path($m->{file_b});
4631         my $pbat = $self->ensure_path($dir);
4632         my $fbat = $self->add_file($self->repo_path($m->{file_b}), $pbat,
4633                                 $self->url_path($m->{file_a}), $self->{r});
4634         print "\tR\t$m->{file_a} => $m->{file_b}\n" unless $::_q;
4635         $self->apply_autoprops($file, $fbat);
4636         $self->chg_file($fbat, $m);
4637         $self->close_file($fbat,undef,$self->{pool});
4639         ($dir, $file) = split_path($m->{file_a});
4640         $pbat = $self->ensure_path($dir);
4641         $self->delete_entry($m->{file_a}, $pbat);
4644 sub M {
4645         my ($self, $m) = @_;
4646         my ($dir, $file) = split_path($m->{file_b});
4647         my $pbat = $self->ensure_path($dir);
4648         my $fbat = $self->open_file($self->repo_path($m->{file_b}),
4649                                 $pbat,$self->{r},$self->{pool});
4650         print "\t$m->{chg}\t$m->{file_b}\n" unless $::_q;
4651         $self->chg_file($fbat, $m);
4652         $self->close_file($fbat,undef,$self->{pool});
4655 sub T { shift->M(@_) }
4657 sub change_file_prop {
4658         my ($self, $fbat, $pname, $pval) = @_;
4659         $self->SUPER::change_file_prop($fbat, $pname, $pval, $self->{pool});
4662 sub _chg_file_get_blob ($$$$) {
4663         my ($self, $fbat, $m, $which) = @_;
4664         my $fh = $::_repository->temp_acquire("git_blob_$which");
4665         if ($m->{"mode_$which"} =~ /^120/) {
4666                 print $fh 'link ' or croak $!;
4667                 $self->change_file_prop($fbat,'svn:special','*');
4668         } elsif ($m->{mode_a} =~ /^120/ && $m->{"mode_$which"} !~ /^120/) {
4669                 $self->change_file_prop($fbat,'svn:special',undef);
4670         }
4671         my $blob = $m->{"sha1_$which"};
4672         return ($fh,) if ($blob =~ /^0{40}$/);
4673         my $size = $::_repository->cat_blob($blob, $fh);
4674         croak "Failed to read object $blob" if ($size < 0);
4675         $fh->flush == 0 or croak $!;
4676         seek $fh, 0, 0 or croak $!;
4678         my $exp = ::md5sum($fh);
4679         seek $fh, 0, 0 or croak $!;
4680         return ($fh, $exp);
4683 sub chg_file {
4684         my ($self, $fbat, $m) = @_;
4685         if ($m->{mode_b} =~ /755$/ && $m->{mode_a} !~ /755$/) {
4686                 $self->change_file_prop($fbat,'svn:executable','*');
4687         } elsif ($m->{mode_b} !~ /755$/ && $m->{mode_a} =~ /755$/) {
4688                 $self->change_file_prop($fbat,'svn:executable',undef);
4689         }
4690         my ($fh_a, $exp_a) = _chg_file_get_blob $self, $fbat, $m, 'a';
4691         my ($fh_b, $exp_b) = _chg_file_get_blob $self, $fbat, $m, 'b';
4692         my $pool = SVN::Pool->new;
4693         my $atd = $self->apply_textdelta($fbat, $exp_a, $pool);
4694         if (-s $fh_a) {
4695                 my $txstream = SVN::TxDelta::new ($fh_a, $fh_b, $pool);
4696                 my $res = SVN::TxDelta::send_txstream($txstream, @$atd, $pool);
4697                 if (defined $res) {
4698                         die "Unexpected result from send_txstream: $res\n",
4699                             "(SVN::Core::VERSION: $SVN::Core::VERSION)\n";
4700                 }
4701         } else {
4702                 my $got = SVN::TxDelta::send_stream($fh_b, @$atd, $pool);
4703                 die "Checksum mismatch\nexpected: $exp_b\ngot: $got\n"
4704                     if ($got ne $exp_b);
4705         }
4706         Git::temp_release($fh_b, 1);
4707         Git::temp_release($fh_a, 1);
4708         $pool->clear;
4711 sub D {
4712         my ($self, $m) = @_;
4713         my ($dir, $file) = split_path($m->{file_b});
4714         my $pbat = $self->ensure_path($dir);
4715         print "\tD\t$m->{file_b}\n" unless $::_q;
4716         $self->delete_entry($m->{file_b}, $pbat);
4719 sub close_edit {
4720         my ($self) = @_;
4721         my ($p,$bat) = ($self->{pool}, $self->{bat});
4722         foreach (sort { $b =~ tr#/#/# <=> $a =~ tr#/#/# } keys %$bat) {
4723                 next if $_ eq '';
4724                 $self->close_directory($bat->{$_}, $p);
4725         }
4726         $self->close_directory($bat->{''}, $p);
4727         $self->SUPER::close_edit($p);
4728         $p->clear;
4731 sub abort_edit {
4732         my ($self) = @_;
4733         $self->SUPER::abort_edit($self->{pool});
4736 sub DESTROY {
4737         my $self = shift;
4738         $self->SUPER::DESTROY(@_);
4739         $self->{pool}->clear;
4742 # this drives the editor
4743 sub apply_diff {
4744         my ($self) = @_;
4745         my $mods = $self->{mods};
4746         my %o = ( D => 1, R => 0, C => -1, A => 3, M => 3, T => 3 );
4747         foreach my $m (sort { $o{$a->{chg}} <=> $o{$b->{chg}} } @$mods) {
4748                 my $f = $m->{chg};
4749                 if (defined $o{$f}) {
4750                         $self->$f($m);
4751                 } else {
4752                         fatal("Invalid change type: $f");
4753                 }
4754         }
4755         $self->rmdirs if $_rmdir;
4756         if (@$mods == 0) {
4757                 $self->abort_edit;
4758         } else {
4759                 $self->close_edit;
4760         }
4761         return scalar @$mods;
4764 package Git::SVN::Ra;
4765 use vars qw/@ISA $config_dir $_log_window_size/;
4766 use strict;
4767 use warnings;
4768 my ($ra_invalid, $can_do_switch, %ignored_err, $RA);
4770 BEGIN {
4771         # enforce temporary pool usage for some simple functions
4772         no strict 'refs';
4773         for my $f (qw/rev_proplist get_latest_revnum get_uuid get_repos_root
4774                       get_file/) {
4775                 my $SUPER = "SUPER::$f";
4776                 *$f = sub {
4777                         my $self = shift;
4778                         my $pool = SVN::Pool->new;
4779                         my @ret = $self->$SUPER(@_,$pool);
4780                         $pool->clear;
4781                         wantarray ? @ret : $ret[0];
4782                 };
4783         }
4786 sub _auth_providers () {
4787         [
4788           SVN::Client::get_simple_provider(),
4789           SVN::Client::get_ssl_server_trust_file_provider(),
4790           SVN::Client::get_simple_prompt_provider(
4791             \&Git::SVN::Prompt::simple, 2),
4792           SVN::Client::get_ssl_client_cert_file_provider(),
4793           SVN::Client::get_ssl_client_cert_prompt_provider(
4794             \&Git::SVN::Prompt::ssl_client_cert, 2),
4795           SVN::Client::get_ssl_client_cert_pw_file_provider(),
4796           SVN::Client::get_ssl_client_cert_pw_prompt_provider(
4797             \&Git::SVN::Prompt::ssl_client_cert_pw, 2),
4798           SVN::Client::get_username_provider(),
4799           SVN::Client::get_ssl_server_trust_prompt_provider(
4800             \&Git::SVN::Prompt::ssl_server_trust),
4801           SVN::Client::get_username_prompt_provider(
4802             \&Git::SVN::Prompt::username, 2)
4803         ]
4806 sub escape_uri_only {
4807         my ($uri) = @_;
4808         my @tmp;
4809         foreach (split m{/}, $uri) {
4810                 s/([^~\w.%+-]|%(?![a-fA-F0-9]{2}))/sprintf("%%%02X",ord($1))/eg;
4811                 push @tmp, $_;
4812         }
4813         join('/', @tmp);
4816 sub escape_url {
4817         my ($url) = @_;
4818         if ($url =~ m#^(https?)://([^/]+)(.*)$#) {
4819                 my ($scheme, $domain, $uri) = ($1, $2, escape_uri_only($3));
4820                 $url = "$scheme://$domain$uri";
4821         }
4822         $url;
4825 sub new {
4826         my ($class, $url) = @_;
4827         $url =~ s!/+$!!;
4828         return $RA if ($RA && $RA->{url} eq $url);
4830         SVN::_Core::svn_config_ensure($config_dir, undef);
4831         my ($baton, $callbacks) = SVN::Core::auth_open_helper(_auth_providers);
4832         my $config = SVN::Core::config_get_config($config_dir);
4833         $RA = undef;
4834         my $dont_store_passwords = 1;
4835         my $conf_t = ${$config}{'config'};
4836         {
4837                 no warnings 'once';
4838                 # The usage of $SVN::_Core::SVN_CONFIG_* variables
4839                 # produces warnings that variables are used only once.
4840                 # I had not found the better way to shut them up, so
4841                 # the warnings of type 'once' are disabled in this block.
4842                 if (SVN::_Core::svn_config_get_bool($conf_t,
4843                     $SVN::_Core::SVN_CONFIG_SECTION_AUTH,
4844                     $SVN::_Core::SVN_CONFIG_OPTION_STORE_PASSWORDS,
4845                     1) == 0) {
4846                         SVN::_Core::svn_auth_set_parameter($baton,
4847                             $SVN::_Core::SVN_AUTH_PARAM_DONT_STORE_PASSWORDS,
4848                             bless (\$dont_store_passwords, "_p_void"));
4849                 }
4850                 if (SVN::_Core::svn_config_get_bool($conf_t,
4851                     $SVN::_Core::SVN_CONFIG_SECTION_AUTH,
4852                     $SVN::_Core::SVN_CONFIG_OPTION_STORE_AUTH_CREDS,
4853                     1) == 0) {
4854                         $Git::SVN::Prompt::_no_auth_cache = 1;
4855                 }
4856         } # no warnings 'once'
4857         my $self = SVN::Ra->new(url => escape_url($url), auth => $baton,
4858                               config => $config,
4859                               pool => SVN::Pool->new,
4860                               auth_provider_callbacks => $callbacks);
4861         $self->{url} = $url;
4862         $self->{svn_path} = $url;
4863         $self->{repos_root} = $self->get_repos_root;
4864         $self->{svn_path} =~ s#^\Q$self->{repos_root}\E(/|$)##;
4865         $self->{cache} = { check_path => { r => 0, data => {} },
4866                            get_dir => { r => 0, data => {} } };
4867         $RA = bless $self, $class;
4870 sub check_path {
4871         my ($self, $path, $r) = @_;
4872         my $cache = $self->{cache}->{check_path};
4873         if ($r == $cache->{r} && exists $cache->{data}->{$path}) {
4874                 return $cache->{data}->{$path};
4875         }
4876         my $pool = SVN::Pool->new;
4877         my $t = $self->SUPER::check_path($path, $r, $pool);
4878         $pool->clear;
4879         if ($r != $cache->{r}) {
4880                 %{$cache->{data}} = ();
4881                 $cache->{r} = $r;
4882         }
4883         $cache->{data}->{$path} = $t;
4886 sub get_dir {
4887         my ($self, $dir, $r) = @_;
4888         my $cache = $self->{cache}->{get_dir};
4889         if ($r == $cache->{r}) {
4890                 if (my $x = $cache->{data}->{$dir}) {
4891                         return wantarray ? @$x : $x->[0];
4892                 }
4893         }
4894         my $pool = SVN::Pool->new;
4895         my ($d, undef, $props) = $self->SUPER::get_dir($dir, $r, $pool);
4896         my %dirents = map { $_ => { kind => $d->{$_}->kind } } keys %$d;
4897         $pool->clear;
4898         if ($r != $cache->{r}) {
4899                 %{$cache->{data}} = ();
4900                 $cache->{r} = $r;
4901         }
4902         $cache->{data}->{$dir} = [ \%dirents, $r, $props ];
4903         wantarray ? (\%dirents, $r, $props) : \%dirents;
4906 sub DESTROY {
4907         # do not call the real DESTROY since we store ourselves in $RA
4910 # get_log(paths, start, end, limit,
4911 #         discover_changed_paths, strict_node_history, receiver)
4912 sub get_log {
4913         my ($self, @args) = @_;
4914         my $pool = SVN::Pool->new;
4916         # svn_log_changed_path_t objects passed to get_log are likely to be
4917         # overwritten even if only the refs are copied to an external variable,
4918         # so we should dup the structures in their entirety.  Using an
4919         # externally passed pool (instead of our temporary and quickly cleared
4920         # pool in Git::SVN::Ra) does not help matters at all...
4921         my $receiver = pop @args;
4922         my $prefix = "/".$self->{svn_path};
4923         $prefix =~ s#/+($)##;
4924         my $prefix_regex = qr#^\Q$prefix\E#;
4925         push(@args, sub {
4926                 my ($paths) = $_[0];
4927                 return &$receiver(@_) unless $paths;
4928                 $_[0] = ();
4929                 foreach my $p (keys %$paths) {
4930                         my $i = $paths->{$p};
4931                         # Make path relative to our url, not repos_root
4932                         $p =~ s/$prefix_regex//;
4933                         my %s = map { $_ => $i->$_; }
4934                                 qw/copyfrom_path copyfrom_rev action/;
4935                         if ($s{'copyfrom_path'}) {
4936                                 $s{'copyfrom_path'} =~ s/$prefix_regex//;
4937                         }
4938                         $_[0]{$p} = \%s;
4939                 }
4940                 &$receiver(@_);
4941         });
4944         # the limit parameter was not supported in SVN 1.1.x, so we
4945         # drop it.  Therefore, the receiver callback passed to it
4946         # is made aware of this limitation by being wrapped if
4947         # the limit passed to is being wrapped.
4948         if ($SVN::Core::VERSION le '1.2.0') {
4949                 my $limit = splice(@args, 3, 1);
4950                 if ($limit > 0) {
4951                         my $receiver = pop @args;
4952                         push(@args, sub { &$receiver(@_) if (--$limit >= 0) });
4953                 }
4954         }
4955         my $ret = $self->SUPER::get_log(@args, $pool);
4956         $pool->clear;
4957         $ret;
4960 sub trees_match {
4961         my ($self, $url1, $rev1, $url2, $rev2) = @_;
4962         my $ctx = SVN::Client->new(auth => _auth_providers);
4963         my $out = IO::File->new_tmpfile;
4965         # older SVN (1.1.x) doesn't take $pool as the last parameter for
4966         # $ctx->diff(), so we'll create a default one
4967         my $pool = SVN::Pool->new_default_sub;
4969         $ra_invalid = 1; # this will open a new SVN::Ra connection to $url1
4970         $ctx->diff([], $url1, $rev1, $url2, $rev2, 1, 1, 0, $out, $out);
4971         $out->flush;
4972         my $ret = (($out->stat)[7] == 0);
4973         close $out or croak $!;
4975         $ret;
4978 sub get_commit_editor {
4979         my ($self, $log, $cb, $pool) = @_;
4980         my @lock = $SVN::Core::VERSION ge '1.2.0' ? (undef, 0) : ();
4981         $self->SUPER::get_commit_editor($log, $cb, @lock, $pool);
4984 sub gs_do_update {
4985         my ($self, $rev_a, $rev_b, $gs, $editor) = @_;
4986         my $new = ($rev_a == $rev_b);
4987         my $path = $gs->{path};
4989         if ($new && -e $gs->{index}) {
4990                 unlink $gs->{index} or die
4991                   "Couldn't unlink index: $gs->{index}: $!\n";
4992         }
4993         my $pool = SVN::Pool->new;
4994         $editor->set_path_strip($path);
4995         my (@pc) = split m#/#, $path;
4996         my $reporter = $self->do_update($rev_b, (@pc ? shift @pc : ''),
4997                                         1, $editor, $pool);
4998         my @lock = $SVN::Core::VERSION ge '1.2.0' ? (undef) : ();
5000         # Since we can't rely on svn_ra_reparent being available, we'll
5001         # just have to do some magic with set_path to make it so
5002         # we only want a partial path.
5003         my $sp = '';
5004         my $final = join('/', @pc);
5005         while (@pc) {
5006                 $reporter->set_path($sp, $rev_b, 0, @lock, $pool);
5007                 $sp .= '/' if length $sp;
5008                 $sp .= shift @pc;
5009         }
5010         die "BUG: '$sp' != '$final'\n" if ($sp ne $final);
5012         $reporter->set_path($sp, $rev_a, $new, @lock, $pool);
5014         $reporter->finish_report($pool);
5015         $pool->clear;
5016         $editor->{git_commit_ok};
5019 # this requires SVN 1.4.3 or later (do_switch didn't work before 1.4.3, and
5020 # svn_ra_reparent didn't work before 1.4)
5021 sub gs_do_switch {
5022         my ($self, $rev_a, $rev_b, $gs, $url_b, $editor) = @_;
5023         my $path = $gs->{path};
5024         my $pool = SVN::Pool->new;
5026         my $full_url = $self->{url};
5027         my $old_url = $full_url;
5028         $full_url .= '/' . $path if length $path;
5029         my ($ra, $reparented);
5031         if ($old_url =~ m#^svn(\+ssh)?://# ||
5032             ($full_url =~ m#^https?://# &&
5033              escape_url($full_url) ne $full_url)) {
5034                 $_[0] = undef;
5035                 $self = undef;
5036                 $RA = undef;
5037                 $ra = Git::SVN::Ra->new($full_url);
5038                 $ra_invalid = 1;
5039         } elsif ($old_url ne $full_url) {
5040                 SVN::_Ra::svn_ra_reparent($self->{session}, $full_url, $pool);
5041                 $self->{url} = $full_url;
5042                 $reparented = 1;
5043         }
5045         $ra ||= $self;
5046         $url_b = escape_url($url_b);
5047         my $reporter = $ra->do_switch($rev_b, '', 1, $url_b, $editor, $pool);
5048         my @lock = $SVN::Core::VERSION ge '1.2.0' ? (undef) : ();
5049         $reporter->set_path('', $rev_a, 0, @lock, $pool);
5050         $reporter->finish_report($pool);
5052         if ($reparented) {
5053                 SVN::_Ra::svn_ra_reparent($self->{session}, $old_url, $pool);
5054                 $self->{url} = $old_url;
5055         }
5057         $pool->clear;
5058         $editor->{git_commit_ok};
5061 sub longest_common_path {
5062         my ($gsv, $globs) = @_;
5063         my %common;
5064         my $common_max = scalar @$gsv;
5066         foreach my $gs (@$gsv) {
5067                 my @tmp = split m#/#, $gs->{path};
5068                 my $p = '';
5069                 foreach (@tmp) {
5070                         $p .= length($p) ? "/$_" : $_;
5071                         $common{$p} ||= 0;
5072                         $common{$p}++;
5073                 }
5074         }
5075         $globs ||= [];
5076         $common_max += scalar @$globs;
5077         foreach my $glob (@$globs) {
5078                 my @tmp = split m#/#, $glob->{path}->{left};
5079                 my $p = '';
5080                 foreach (@tmp) {
5081                         $p .= length($p) ? "/$_" : $_;
5082                         $common{$p} ||= 0;
5083                         $common{$p}++;
5084                 }
5085         }
5087         my $longest_path = '';
5088         foreach (sort {length $b <=> length $a} keys %common) {
5089                 if ($common{$_} == $common_max) {
5090                         $longest_path = $_;
5091                         last;
5092                 }
5093         }
5094         $longest_path;
5097 sub gs_fetch_loop_common {
5098         my ($self, $base, $head, $gsv, $globs) = @_;
5099         return if ($base > $head);
5100         my $inc = $_log_window_size;
5101         my ($min, $max) = ($base, $head < $base + $inc ? $head : $base + $inc);
5102         my $longest_path = longest_common_path($gsv, $globs);
5103         my $ra_url = $self->{url};
5104         my $find_trailing_edge;
5105         while (1) {
5106                 my %revs;
5107                 my $err;
5108                 my $err_handler = $SVN::Error::handler;
5109                 $SVN::Error::handler = sub {
5110                         ($err) = @_;
5111                         skip_unknown_revs($err);
5112                 };
5113                 sub _cb {
5114                         my ($paths, $r, $author, $date, $log) = @_;
5115                         [ $paths,
5116                           { author => $author, date => $date, log => $log } ];
5117                 }
5118                 $self->get_log([$longest_path], $min, $max, 0, 1, 1,
5119                                sub { $revs{$_[1]} = _cb(@_) });
5120                 if ($err) {
5121                         print "Checked through r$max\r";
5122                 } else {
5123                         $find_trailing_edge = 1;
5124                 }
5125                 if ($err and $find_trailing_edge) {
5126                         print STDERR "Path '$longest_path' ",
5127                                      "was probably deleted:\n",
5128                                      $err->expanded_message,
5129                                      "\nWill attempt to follow ",
5130                                      "revisions r$min .. r$max ",
5131                                      "committed before the deletion\n";
5132                         my $hi = $max;
5133                         while (--$hi >= $min) {
5134                                 my $ok;
5135                                 $self->get_log([$longest_path], $min, $hi,
5136                                                0, 1, 1, sub {
5137                                                $ok = $_[1];
5138                                                $revs{$_[1]} = _cb(@_) });
5139                                 if ($ok) {
5140                                         print STDERR "r$min .. r$ok OK\n";
5141                                         last;
5142                                 }
5143                         }
5144                         $find_trailing_edge = 0;
5145                 }
5146                 $SVN::Error::handler = $err_handler;
5148                 my %exists = map { $_->{path} => $_ } @$gsv;
5149                 foreach my $r (sort {$a <=> $b} keys %revs) {
5150                         my ($paths, $logged) = @{$revs{$r}};
5152                         foreach my $gs ($self->match_globs(\%exists, $paths,
5153                                                            $globs, $r)) {
5154                                 if ($gs->rev_map_max >= $r) {
5155                                         next;
5156                                 }
5157                                 next unless $gs->match_paths($paths, $r);
5158                                 $gs->{logged_rev_props} = $logged;
5159                                 if (my $last_commit = $gs->last_commit) {
5160                                         $gs->assert_index_clean($last_commit);
5161                                 }
5162                                 my $log_entry = $gs->do_fetch($paths, $r);
5163                                 if ($log_entry) {
5164                                         $gs->do_git_commit($log_entry);
5165                                 }
5166                                 $INDEX_FILES{$gs->{index}} = 1;
5167                         }
5168                         foreach my $g (@$globs) {
5169                                 my $k = "svn-remote.$g->{remote}." .
5170                                         "$g->{t}-maxRev";
5171                                 Git::SVN::tmp_config($k, $r);
5172                         }
5173                         if ($ra_invalid) {
5174                                 $_[0] = undef;
5175                                 $self = undef;
5176                                 $RA = undef;
5177                                 $self = Git::SVN::Ra->new($ra_url);
5178                                 $ra_invalid = undef;
5179                         }
5180                 }
5181                 # pre-fill the .rev_db since it'll eventually get filled in
5182                 # with '0' x40 if something new gets committed
5183                 foreach my $gs (@$gsv) {
5184                         next if $gs->rev_map_max >= $max;
5185                         next if defined $gs->rev_map_get($max);
5186                         $gs->rev_map_set($max, 0 x40);
5187                 }
5188                 foreach my $g (@$globs) {
5189                         my $k = "svn-remote.$g->{remote}.$g->{t}-maxRev";
5190                         Git::SVN::tmp_config($k, $max);
5191                 }
5192                 last if $max >= $head;
5193                 $min = $max + 1;
5194                 $max += $inc;
5195                 $max = $head if ($max > $head);
5196         }
5197         Git::SVN::gc();
5200 sub get_dir_globbed {
5201         my ($self, $left, $depth, $r) = @_;
5203         my @x = eval { $self->get_dir($left, $r) };
5204         return unless scalar @x == 3;
5205         my $dirents = $x[0];
5206         my @finalents;
5207         foreach my $de (keys %$dirents) {
5208                 next if $dirents->{$de}->{kind} != $SVN::Node::dir;
5209                 if ($depth > 1) {
5210                         my @args = ("$left/$de", $depth - 1, $r);
5211                         foreach my $dir ($self->get_dir_globbed(@args)) {
5212                                 push @finalents, "$de/$dir";
5213                         }
5214                 } else {
5215                         push @finalents, $de;
5216                 }
5217         }
5218         @finalents;
5221 sub match_globs {
5222         my ($self, $exists, $paths, $globs, $r) = @_;
5224         sub get_dir_check {
5225                 my ($self, $exists, $g, $r) = @_;
5227                 my @dirs = $self->get_dir_globbed($g->{path}->{left},
5228                                                   $g->{path}->{depth},
5229                                                   $r);
5231                 foreach my $de (@dirs) {
5232                         my $p = $g->{path}->full_path($de);
5233                         next if $exists->{$p};
5234                         next if (length $g->{path}->{right} &&
5235                                  ($self->check_path($p, $r) !=
5236                                   $SVN::Node::dir));
5237                         next unless $p =~ /$g->{path}->{regex}/;
5238                         $exists->{$p} = Git::SVN->init($self->{url}, $p, undef,
5239                                          $g->{ref}->full_path($de), 1);
5240                 }
5241         }
5242         foreach my $g (@$globs) {
5243                 if (my $path = $paths->{"/$g->{path}->{left}"}) {
5244                         if ($path->{action} =~ /^[AR]$/) {
5245                                 get_dir_check($self, $exists, $g, $r);
5246                         }
5247                 }
5248                 foreach (keys %$paths) {
5249                         if (/$g->{path}->{left_regex}/ &&
5250                             !/$g->{path}->{regex}/) {
5251                                 next if $paths->{$_}->{action} !~ /^[AR]$/;
5252                                 get_dir_check($self, $exists, $g, $r);
5253                         }
5254                         next unless /$g->{path}->{regex}/;
5255                         my $p = $1;
5256                         my $pathname = $g->{path}->full_path($p);
5257                         next if $exists->{$pathname};
5258                         next if ($self->check_path($pathname, $r) !=
5259                                  $SVN::Node::dir);
5260                         $exists->{$pathname} = Git::SVN->init(
5261                                               $self->{url}, $pathname, undef,
5262                                               $g->{ref}->full_path($p), 1);
5263                 }
5264                 my $c = '';
5265                 foreach (split m#/#, $g->{path}->{left}) {
5266                         $c .= "/$_";
5267                         next unless ($paths->{$c} &&
5268                                      ($paths->{$c}->{action} =~ /^[AR]$/));
5269                         get_dir_check($self, $exists, $g, $r);
5270                 }
5271         }
5272         values %$exists;
5275 sub minimize_url {
5276         my ($self) = @_;
5277         return $self->{url} if ($self->{url} eq $self->{repos_root});
5278         my $url = $self->{repos_root};
5279         my @components = split(m!/!, $self->{svn_path});
5280         my $c = '';
5281         do {
5282                 $url .= "/$c" if length $c;
5283                 eval {
5284                         my $ra = (ref $self)->new($url);
5285                         my $latest = $ra->get_latest_revnum;
5286                         $ra->get_log("", $latest, 0, 1, 0, 1, sub {});
5287                 };
5288         } while ($@ && ($c = shift @components));
5289         $url;
5292 sub can_do_switch {
5293         my $self = shift;
5294         unless (defined $can_do_switch) {
5295                 my $pool = SVN::Pool->new;
5296                 my $rep = eval {
5297                         $self->do_switch(1, '', 0, $self->{url},
5298                                          SVN::Delta::Editor->new, $pool);
5299                 };
5300                 if ($@) {
5301                         $can_do_switch = 0;
5302                 } else {
5303                         $rep->abort_report($pool);
5304                         $can_do_switch = 1;
5305                 }
5306                 $pool->clear;
5307         }
5308         $can_do_switch;
5311 sub skip_unknown_revs {
5312         my ($err) = @_;
5313         my $errno = $err->apr_err();
5314         # Maybe the branch we're tracking didn't
5315         # exist when the repo started, so it's
5316         # not an error if it doesn't, just continue
5317         #
5318         # Wonderfully consistent library, eh?
5319         # 160013 - svn:// and file://
5320         # 175002 - http(s)://
5321         # 175007 - http(s):// (this repo required authorization, too...)
5322         #   More codes may be discovered later...
5323         if ($errno == 175007 || $errno == 175002 || $errno == 160013) {
5324                 my $err_key = $err->expanded_message;
5325                 # revision numbers change every time, filter them out
5326                 $err_key =~ s/\d+/\0/g;
5327                 $err_key = "$errno\0$err_key";
5328                 unless ($ignored_err{$err_key}) {
5329                         warn "W: Ignoring error from SVN, path probably ",
5330                              "does not exist: ($errno): ",
5331                              $err->expanded_message,"\n";
5332                         warn "W: Do not be alarmed at the above message ",
5333                              "git-svn is just searching aggressively for ",
5334                              "old history.\n",
5335                              "This may take a while on large repositories\n";
5336                         $ignored_err{$err_key} = 1;
5337                 }
5338                 return;
5339         }
5340         die "Error from SVN, ($errno): ", $err->expanded_message,"\n";
5343 package Git::SVN::Log;
5344 use strict;
5345 use warnings;
5346 use POSIX qw/strftime/;
5347 use Time::Local;
5348 use constant commit_log_separator => ('-' x 72) . "\n";
5349 use vars qw/$TZ $limit $color $pager $non_recursive $verbose $oneline
5350             %rusers $show_commit $incremental/;
5351 my $l_fmt;
5353 sub cmt_showable {
5354         my ($c) = @_;
5355         return 1 if defined $c->{r};
5357         # big commit message got truncated by the 16k pretty buffer in rev-list
5358         if ($c->{l} && $c->{l}->[-1] eq "...\n" &&
5359                                 $c->{a_raw} =~ /\@([a-f\d\-]+)>$/) {
5360                 @{$c->{l}} = ();
5361                 my @log = command(qw/cat-file commit/, $c->{c});
5363                 # shift off the headers
5364                 shift @log while ($log[0] ne '');
5365                 shift @log;
5367                 # TODO: make $c->{l} not have a trailing newline in the future
5368                 @{$c->{l}} = map { "$_\n" } grep !/^git-svn-id: /, @log;
5370                 (undef, $c->{r}, undef) = ::extract_metadata(
5371                                 (grep(/^git-svn-id: /, @log))[-1]);
5372         }
5373         return defined $c->{r};
5376 sub log_use_color {
5377         return $color || Git->repository->get_colorbool('color.diff');
5380 sub git_svn_log_cmd {
5381         my ($r_min, $r_max, @args) = @_;
5382         my $head = 'HEAD';
5383         my (@files, @log_opts);
5384         foreach my $x (@args) {
5385                 if ($x eq '--' || @files) {
5386                         push @files, $x;
5387                 } else {
5388                         if (::verify_ref("$x^0")) {
5389                                 $head = $x;
5390                         } else {
5391                                 push @log_opts, $x;
5392                         }
5393                 }
5394         }
5396         my ($url, $rev, $uuid, $gs) = ::working_head_info($head);
5397         $gs ||= Git::SVN->_new;
5398         my @cmd = (qw/log --abbrev-commit --pretty=raw --default/,
5399                    $gs->refname);
5400         push @cmd, '-r' unless $non_recursive;
5401         push @cmd, qw/--raw --name-status/ if $verbose;
5402         push @cmd, '--color' if log_use_color();
5403         push @cmd, @log_opts;
5404         if (defined $r_max && $r_max == $r_min) {
5405                 push @cmd, '--max-count=1';
5406                 if (my $c = $gs->rev_map_get($r_max)) {
5407                         push @cmd, $c;
5408                 }
5409         } elsif (defined $r_max) {
5410                 if ($r_max < $r_min) {
5411                         ($r_min, $r_max) = ($r_max, $r_min);
5412                 }
5413                 my (undef, $c_max) = $gs->find_rev_before($r_max, 1, $r_min);
5414                 my (undef, $c_min) = $gs->find_rev_after($r_min, 1, $r_max);
5415                 # If there are no commits in the range, both $c_max and $c_min
5416                 # will be undefined.  If there is at least 1 commit in the
5417                 # range, both will be defined.
5418                 return () if !defined $c_min || !defined $c_max;
5419                 if ($c_min eq $c_max) {
5420                         push @cmd, '--max-count=1', $c_min;
5421                 } else {
5422                         push @cmd, '--boundary', "$c_min..$c_max";
5423                 }
5424         }
5425         return (@cmd, @files);
5428 # adapted from pager.c
5429 sub config_pager {
5430         chomp(my $pager = command_oneline(qw(var GIT_PAGER)));
5431         if ($pager eq 'cat') {
5432                 $pager = undef;
5433         }
5434         $ENV{GIT_PAGER_IN_USE} = defined($pager);
5437 sub run_pager {
5438         return unless -t *STDOUT && defined $pager;
5439         pipe my ($rfd, $wfd) or return;
5440         defined(my $pid = fork) or ::fatal "Can't fork: $!";
5441         if (!$pid) {
5442                 open STDOUT, '>&', $wfd or
5443                                      ::fatal "Can't redirect to stdout: $!";
5444                 return;
5445         }
5446         open STDIN, '<&', $rfd or ::fatal "Can't redirect stdin: $!";
5447         $ENV{LESS} ||= 'FRSX';
5448         exec $pager or ::fatal "Can't run pager: $! ($pager)";
5451 sub format_svn_date {
5452         # some systmes don't handle or mishandle %z, so be creative.
5453         my $t = shift || time;
5454         my $gm = timelocal(gmtime($t));
5455         my $sign = qw( + + - )[ $t <=> $gm ];
5456         my $gmoff = sprintf("%s%02d%02d", $sign, (gmtime(abs($t - $gm)))[2,1]);
5457         return strftime("%Y-%m-%d %H:%M:%S $gmoff (%a, %d %b %Y)", localtime($t));
5460 sub parse_git_date {
5461         my ($t, $tz) = @_;
5462         # Date::Parse isn't in the standard Perl distro :(
5463         if ($tz =~ s/^\+//) {
5464                 $t += tz_to_s_offset($tz);
5465         } elsif ($tz =~ s/^\-//) {
5466                 $t -= tz_to_s_offset($tz);
5467         }
5468         return $t;
5471 sub set_local_timezone {
5472         if (defined $TZ) {
5473                 $ENV{TZ} = $TZ;
5474         } else {
5475                 delete $ENV{TZ};
5476         }
5479 sub tz_to_s_offset {
5480         my ($tz) = @_;
5481         $tz =~ s/(\d\d)$//;
5482         return ($1 * 60) + ($tz * 3600);
5485 sub get_author_info {
5486         my ($dest, $author, $t, $tz) = @_;
5487         $author =~ s/(?:^\s*|\s*$)//g;
5488         $dest->{a_raw} = $author;
5489         my $au;
5490         if ($::_authors) {
5491                 $au = $rusers{$author} || undef;
5492         }
5493         if (!$au) {
5494                 ($au) = ($author =~ /<([^>]+)\@[^>]+>$/);
5495         }
5496         $dest->{t} = $t;
5497         $dest->{tz} = $tz;
5498         $dest->{a} = $au;
5499         $dest->{t_utc} = parse_git_date($t, $tz);
5502 sub process_commit {
5503         my ($c, $r_min, $r_max, $defer) = @_;
5504         if (defined $r_min && defined $r_max) {
5505                 if ($r_min == $c->{r} && $r_min == $r_max) {
5506                         show_commit($c);
5507                         return 0;
5508                 }
5509                 return 1 if $r_min == $r_max;
5510                 if ($r_min < $r_max) {
5511                         # we need to reverse the print order
5512                         return 0 if (defined $limit && --$limit < 0);
5513                         push @$defer, $c;
5514                         return 1;
5515                 }
5516                 if ($r_min != $r_max) {
5517                         return 1 if ($r_min < $c->{r});
5518                         return 1 if ($r_max > $c->{r});
5519                 }
5520         }
5521         return 0 if (defined $limit && --$limit < 0);
5522         show_commit($c);
5523         return 1;
5526 sub show_commit {
5527         my $c = shift;
5528         if ($oneline) {
5529                 my $x = "\n";
5530                 if (my $l = $c->{l}) {
5531                         while ($l->[0] =~ /^\s*$/) { shift @$l }
5532                         $x = $l->[0];
5533                 }
5534                 $l_fmt ||= 'A' . length($c->{r});
5535                 print 'r',pack($l_fmt, $c->{r}),' | ';
5536                 print "$c->{c} | " if $show_commit;
5537                 print $x;
5538         } else {
5539                 show_commit_normal($c);
5540         }
5543 sub show_commit_changed_paths {
5544         my ($c) = @_;
5545         return unless $c->{changed};
5546         print "Changed paths:\n", @{$c->{changed}};
5549 sub show_commit_normal {
5550         my ($c) = @_;
5551         print commit_log_separator, "r$c->{r} | ";
5552         print "$c->{c} | " if $show_commit;
5553         print "$c->{a} | ", format_svn_date($c->{t_utc}), ' | ';
5554         my $nr_line = 0;
5556         if (my $l = $c->{l}) {
5557                 while ($l->[$#$l] eq "\n" && $#$l > 0
5558                                           && $l->[($#$l - 1)] eq "\n") {
5559                         pop @$l;
5560                 }
5561                 $nr_line = scalar @$l;
5562                 if (!$nr_line) {
5563                         print "1 line\n\n\n";
5564                 } else {
5565                         if ($nr_line == 1) {
5566                                 $nr_line = '1 line';
5567                         } else {
5568                                 $nr_line .= ' lines';
5569                         }
5570                         print $nr_line, "\n";
5571                         show_commit_changed_paths($c);
5572                         print "\n";
5573                         print $_ foreach @$l;
5574                 }
5575         } else {
5576                 print "1 line\n";
5577                 show_commit_changed_paths($c);
5578                 print "\n";
5580         }
5581         foreach my $x (qw/raw stat diff/) {
5582                 if ($c->{$x}) {
5583                         print "\n";
5584                         print $_ foreach @{$c->{$x}}
5585                 }
5586         }
5589 sub cmd_show_log {
5590         my (@args) = @_;
5591         my ($r_min, $r_max);
5592         my $r_last = -1; # prevent dupes
5593         set_local_timezone();
5594         if (defined $::_revision) {
5595                 if ($::_revision =~ /^(\d+):(\d+)$/) {
5596                         ($r_min, $r_max) = ($1, $2);
5597                 } elsif ($::_revision =~ /^\d+$/) {
5598                         $r_min = $r_max = $::_revision;
5599                 } else {
5600                         ::fatal "-r$::_revision is not supported, use ",
5601                                 "standard 'git log' arguments instead";
5602                 }
5603         }
5605         config_pager();
5606         @args = git_svn_log_cmd($r_min, $r_max, @args);
5607         if (!@args) {
5608                 print commit_log_separator unless $incremental || $oneline;
5609                 return;
5610         }
5611         my $log = command_output_pipe(@args);
5612         run_pager();
5613         my (@k, $c, $d, $stat);
5614         my $esc_color = qr/(?:\033\[(?:(?:\d+;)*\d*)?m)*/;
5615         while (<$log>) {
5616                 if (/^${esc_color}commit -?($::sha1_short)/o) {
5617                         my $cmt = $1;
5618                         if ($c && cmt_showable($c) && $c->{r} != $r_last) {
5619                                 $r_last = $c->{r};
5620                                 process_commit($c, $r_min, $r_max, \@k) or
5621                                                                 goto out;
5622                         }
5623                         $d = undef;
5624                         $c = { c => $cmt };
5625                 } elsif (/^${esc_color}author (.+) (\d+) ([\-\+]?\d+)$/o) {
5626                         get_author_info($c, $1, $2, $3);
5627                 } elsif (/^${esc_color}(?:tree|parent|committer) /o) {
5628                         # ignore
5629                 } elsif (/^${esc_color}:\d{6} \d{6} $::sha1_short/o) {
5630                         push @{$c->{raw}}, $_;
5631                 } elsif (/^${esc_color}[ACRMDT]\t/) {
5632                         # we could add $SVN->{svn_path} here, but that requires
5633                         # remote access at the moment (repo_path_split)...
5634                         s#^(${esc_color})([ACRMDT])\t#$1   $2 #o;
5635                         push @{$c->{changed}}, $_;
5636                 } elsif (/^${esc_color}diff /o) {
5637                         $d = 1;
5638                         push @{$c->{diff}}, $_;
5639                 } elsif ($d) {
5640                         push @{$c->{diff}}, $_;
5641                 } elsif (/^\ .+\ \|\s*\d+\ $esc_color[\+\-]*
5642                           $esc_color*[\+\-]*$esc_color$/x) {
5643                         $stat = 1;
5644                         push @{$c->{stat}}, $_;
5645                 } elsif ($stat && /^ \d+ files changed, \d+ insertions/) {
5646                         push @{$c->{stat}}, $_;
5647                         $stat = undef;
5648                 } elsif (/^${esc_color}    (git-svn-id:.+)$/o) {
5649                         ($c->{url}, $c->{r}, undef) = ::extract_metadata($1);
5650                 } elsif (s/^${esc_color}    //o) {
5651                         push @{$c->{l}}, $_;
5652                 }
5653         }
5654         if ($c && defined $c->{r} && $c->{r} != $r_last) {
5655                 $r_last = $c->{r};
5656                 process_commit($c, $r_min, $r_max, \@k);
5657         }
5658         if (@k) {
5659                 ($r_min, $r_max) = ($r_max, $r_min);
5660                 process_commit($_, $r_min, $r_max) foreach reverse @k;
5661         }
5662 out:
5663         close $log;
5664         print commit_log_separator unless $incremental || $oneline;
5667 sub cmd_blame {
5668         my $path = pop;
5670         config_pager();
5671         run_pager();
5673         my ($fh, $ctx, $rev);
5675         if ($_git_format) {
5676                 ($fh, $ctx) = command_output_pipe('blame', @_, $path);
5677                 while (my $line = <$fh>) {
5678                         if ($line =~ /^\^?([[:xdigit:]]+)\s/) {
5679                                 # Uncommitted edits show up as a rev ID of
5680                                 # all zeros, which we can't look up with
5681                                 # cmt_metadata
5682                                 if ($1 !~ /^0+$/) {
5683                                         (undef, $rev, undef) =
5684                                                 ::cmt_metadata($1);
5685                                         $rev = '0' if (!$rev);
5686                                 } else {
5687                                         $rev = '0';
5688                                 }
5689                                 $rev = sprintf('%-10s', $rev);
5690                                 $line =~ s/^\^?[[:xdigit:]]+(\s)/$rev$1/;
5691                         }
5692                         print $line;
5693                 }
5694         } else {
5695                 ($fh, $ctx) = command_output_pipe('blame', '-p', @_, 'HEAD',
5696                                                   '--', $path);
5697                 my ($sha1);
5698                 my %authors;
5699                 my @buffer;
5700                 my %dsha; #distinct sha keys
5702                 while (my $line = <$fh>) {
5703                         push @buffer, $line;
5704                         if ($line =~ /^([[:xdigit:]]{40})\s\d+\s\d+/) {
5705                                 $dsha{$1} = 1;
5706                         }
5707                 }
5709                 my $s2r = ::cmt_sha2rev_batch([keys %dsha]);
5711                 foreach my $line (@buffer) {
5712                         if ($line =~ /^([[:xdigit:]]{40})\s\d+\s\d+/) {
5713                                 $rev = $s2r->{$1};
5714                                 $rev = '0' if (!$rev)
5715                         }
5716                         elsif ($line =~ /^author (.*)/) {
5717                                 $authors{$rev} = $1;
5718                                 $authors{$rev} =~ s/\s/_/g;
5719                         }
5720                         elsif ($line =~ /^\t(.*)$/) {
5721                                 printf("%6s %10s %s\n", $rev, $authors{$rev}, $1);
5722                         }
5723                 }
5724         }
5725         command_close_pipe($fh, $ctx);
5728 package Git::SVN::Migration;
5729 # these version numbers do NOT correspond to actual version numbers
5730 # of git nor git-svn.  They are just relative.
5732 # v0 layout: .git/$id/info/url, refs/heads/$id-HEAD
5734 # v1 layout: .git/$id/info/url, refs/remotes/$id
5736 # v2 layout: .git/svn/$id/info/url, refs/remotes/$id
5738 # v3 layout: .git/svn/$id, refs/remotes/$id
5739 #            - info/url may remain for backwards compatibility
5740 #            - this is what we migrate up to this layout automatically,
5741 #            - this will be used by git svn init on single branches
5742 # v3.1 layout (auto migrated):
5743 #            - .rev_db => .rev_db.$UUID, .rev_db will remain as a symlink
5744 #              for backwards compatibility
5746 # v4 layout: .git/svn/$repo_id/$id, refs/remotes/$repo_id/$id
5747 #            - this is only created for newly multi-init-ed
5748 #              repositories.  Similar in spirit to the
5749 #              --use-separate-remotes option in git-clone (now default)
5750 #            - we do not automatically migrate to this (following
5751 #              the example set by core git)
5753 # v5 layout: .rev_db.$UUID => .rev_map.$UUID
5754 #            - newer, more-efficient format that uses 24-bytes per record
5755 #              with no filler space.
5756 #            - use xxd -c24 < .rev_map.$UUID to view and debug
5757 #            - This is a one-way migration, repositories updated to the
5758 #              new format will not be able to use old git-svn without
5759 #              rebuilding the .rev_db.  Rebuilding the rev_db is not
5760 #              possible if noMetadata or useSvmProps are set; but should
5761 #              be no problem for users that use the (sensible) defaults.
5762 use strict;
5763 use warnings;
5764 use Carp qw/croak/;
5765 use File::Path qw/mkpath/;
5766 use File::Basename qw/dirname basename/;
5767 use vars qw/$_minimize/;
5769 sub migrate_from_v0 {
5770         my $git_dir = $ENV{GIT_DIR};
5771         return undef unless -d $git_dir;
5772         my ($fh, $ctx) = command_output_pipe(qw/rev-parse --symbolic --all/);
5773         my $migrated = 0;
5774         while (<$fh>) {
5775                 chomp;
5776                 my ($id, $orig_ref) = ($_, $_);
5777                 next unless $id =~ s#^refs/heads/(.+)-HEAD$#$1#;
5778                 next unless -f "$git_dir/$id/info/url";
5779                 my $new_ref = "refs/remotes/$id";
5780                 if (::verify_ref("$new_ref^0")) {
5781                         print STDERR "W: $orig_ref is probably an old ",
5782                                      "branch used by an ancient version of ",
5783                                      "git-svn.\n",
5784                                      "However, $new_ref also exists.\n",
5785                                      "We will not be able ",
5786                                      "to use this branch until this ",
5787                                      "ambiguity is resolved.\n";
5788                         next;
5789                 }
5790                 print STDERR "Migrating from v0 layout...\n" if !$migrated;
5791                 print STDERR "Renaming ref: $orig_ref => $new_ref\n";
5792                 command_noisy('update-ref', $new_ref, $orig_ref);
5793                 command_noisy('update-ref', '-d', $orig_ref, $orig_ref);
5794                 $migrated++;
5795         }
5796         command_close_pipe($fh, $ctx);
5797         print STDERR "Done migrating from v0 layout...\n" if $migrated;
5798         $migrated;
5801 sub migrate_from_v1 {
5802         my $git_dir = $ENV{GIT_DIR};
5803         my $migrated = 0;
5804         return $migrated unless -d $git_dir;
5805         my $svn_dir = "$git_dir/svn";
5807         # just in case somebody used 'svn' as their $id at some point...
5808         return $migrated if -d $svn_dir && ! -f "$svn_dir/info/url";
5810         print STDERR "Migrating from a git-svn v1 layout...\n";
5811         mkpath([$svn_dir]);
5812         print STDERR "Data from a previous version of git-svn exists, but\n\t",
5813                      "$svn_dir\n\t(required for this version ",
5814                      "($::VERSION) of git-svn) does not exist.\n";
5815         my ($fh, $ctx) = command_output_pipe(qw/rev-parse --symbolic --all/);
5816         while (<$fh>) {
5817                 my $x = $_;
5818                 next unless $x =~ s#^refs/remotes/##;
5819                 chomp $x;
5820                 next unless -f "$git_dir/$x/info/url";
5821                 my $u = eval { ::file_to_s("$git_dir/$x/info/url") };
5822                 next unless $u;
5823                 my $dn = dirname("$git_dir/svn/$x");
5824                 mkpath([$dn]) unless -d $dn;
5825                 if ($x eq 'svn') { # they used 'svn' as GIT_SVN_ID:
5826                         mkpath(["$git_dir/svn/svn"]);
5827                         print STDERR " - $git_dir/$x/info => ",
5828                                         "$git_dir/svn/$x/info\n";
5829                         rename "$git_dir/$x/info", "$git_dir/svn/$x/info" or
5830                                croak "$!: $x";
5831                         # don't worry too much about these, they probably
5832                         # don't exist with repos this old (save for index,
5833                         # and we can easily regenerate that)
5834                         foreach my $f (qw/unhandled.log index .rev_db/) {
5835                                 rename "$git_dir/$x/$f", "$git_dir/svn/$x/$f";
5836                         }
5837                 } else {
5838                         print STDERR " - $git_dir/$x => $git_dir/svn/$x\n";
5839                         rename "$git_dir/$x", "$git_dir/svn/$x" or
5840                                croak "$!: $x";
5841                 }
5842                 $migrated++;
5843         }
5844         command_close_pipe($fh, $ctx);
5845         print STDERR "Done migrating from a git-svn v1 layout\n";
5846         $migrated;
5849 sub read_old_urls {
5850         my ($l_map, $pfx, $path) = @_;
5851         my @dir;
5852         foreach (<$path/*>) {
5853                 if (-r "$_/info/url") {
5854                         $pfx .= '/' if $pfx && $pfx !~ m!/$!;
5855                         my $ref_id = $pfx . basename $_;
5856                         my $url = ::file_to_s("$_/info/url");
5857                         $l_map->{$ref_id} = $url;
5858                 } elsif (-d $_) {
5859                         push @dir, $_;
5860                 }
5861         }
5862         foreach (@dir) {
5863                 my $x = $_;
5864                 $x =~ s!^\Q$ENV{GIT_DIR}\E/svn/!!o;
5865                 read_old_urls($l_map, $x, $_);
5866         }
5869 sub migrate_from_v2 {
5870         my @cfg = command(qw/config -l/);
5871         return if grep /^svn-remote\..+\.url=/, @cfg;
5872         my %l_map;
5873         read_old_urls(\%l_map, '', "$ENV{GIT_DIR}/svn");
5874         my $migrated = 0;
5876         foreach my $ref_id (sort keys %l_map) {
5877                 eval { Git::SVN->init($l_map{$ref_id}, '', undef, $ref_id) };
5878                 if ($@) {
5879                         Git::SVN->init($l_map{$ref_id}, '', $ref_id, $ref_id);
5880                 }
5881                 $migrated++;
5882         }
5883         $migrated;
5886 sub minimize_connections {
5887         my $r = Git::SVN::read_all_remotes();
5888         my $new_urls = {};
5889         my $root_repos = {};
5890         foreach my $repo_id (keys %$r) {
5891                 my $url = $r->{$repo_id}->{url} or next;
5892                 my $fetch = $r->{$repo_id}->{fetch} or next;
5893                 my $ra = Git::SVN::Ra->new($url);
5895                 # skip existing cases where we already connect to the root
5896                 if (($ra->{url} eq $ra->{repos_root}) ||
5897                     ($ra->{repos_root} eq $repo_id)) {
5898                         $root_repos->{$ra->{url}} = $repo_id;
5899                         next;
5900                 }
5902                 my $root_ra = Git::SVN::Ra->new($ra->{repos_root});
5903                 my $root_path = $ra->{url};
5904                 $root_path =~ s#^\Q$ra->{repos_root}\E(/|$)##;
5905                 foreach my $path (keys %$fetch) {
5906                         my $ref_id = $fetch->{$path};
5907                         my $gs = Git::SVN->new($ref_id, $repo_id, $path);
5909                         # make sure we can read when connecting to
5910                         # a higher level of a repository
5911                         my ($last_rev, undef) = $gs->last_rev_commit;
5912                         if (!defined $last_rev) {
5913                                 $last_rev = eval {
5914                                         $root_ra->get_latest_revnum;
5915                                 };
5916                                 next if $@;
5917                         }
5918                         my $new = $root_path;
5919                         $new .= length $path ? "/$path" : '';
5920                         eval {
5921                                 $root_ra->get_log([$new], $last_rev, $last_rev,
5922                                                   0, 0, 1, sub { });
5923                         };
5924                         next if $@;
5925                         $new_urls->{$ra->{repos_root}}->{$new} =
5926                                 { ref_id => $ref_id,
5927                                   old_repo_id => $repo_id,
5928                                   old_path => $path };
5929                 }
5930         }
5932         my @emptied;
5933         foreach my $url (keys %$new_urls) {
5934                 # see if we can re-use an existing [svn-remote "repo_id"]
5935                 # instead of creating a(n ugly) new section:
5936                 my $repo_id = $root_repos->{$url} || $url;
5938                 my $fetch = $new_urls->{$url};
5939                 foreach my $path (keys %$fetch) {
5940                         my $x = $fetch->{$path};
5941                         Git::SVN->init($url, $path, $repo_id, $x->{ref_id});
5942                         my $pfx = "svn-remote.$x->{old_repo_id}";
5944                         my $old_fetch = quotemeta("$x->{old_path}:".
5945                                                   "$x->{ref_id}");
5946                         command_noisy(qw/config --unset/,
5947                                       "$pfx.fetch", '^'. $old_fetch . '$');
5948                         delete $r->{$x->{old_repo_id}}->
5949                                {fetch}->{$x->{old_path}};
5950                         if (!keys %{$r->{$x->{old_repo_id}}->{fetch}}) {
5951                                 command_noisy(qw/config --unset/,
5952                                               "$pfx.url");
5953                                 push @emptied, $x->{old_repo_id}
5954                         }
5955                 }
5956         }
5957         if (@emptied) {
5958                 my $file = $ENV{GIT_CONFIG} || "$ENV{GIT_DIR}/config";
5959                 print STDERR <<EOF;
5960 The following [svn-remote] sections in your config file ($file) are empty
5961 and can be safely removed:
5962 EOF
5963                 print STDERR "[svn-remote \"$_\"]\n" foreach @emptied;
5964         }
5967 sub migration_check {
5968         migrate_from_v0();
5969         migrate_from_v1();
5970         migrate_from_v2();
5971         minimize_connections() if $_minimize;
5974 package Git::IndexInfo;
5975 use strict;
5976 use warnings;
5977 use Git qw/command_input_pipe command_close_pipe/;
5979 sub new {
5980         my ($class) = @_;
5981         my ($gui, $ctx) = command_input_pipe(qw/update-index -z --index-info/);
5982         bless { gui => $gui, ctx => $ctx, nr => 0}, $class;
5985 sub remove {
5986         my ($self, $path) = @_;
5987         if (print { $self->{gui} } '0 ', 0 x 40, "\t", $path, "\0") {
5988                 return ++$self->{nr};
5989         }
5990         undef;
5993 sub update {
5994         my ($self, $mode, $hash, $path) = @_;
5995         if (print { $self->{gui} } $mode, ' ', $hash, "\t", $path, "\0") {
5996                 return ++$self->{nr};
5997         }
5998         undef;
6001 sub DESTROY {
6002         my ($self) = @_;
6003         command_close_pipe($self->{gui}, $self->{ctx});
6006 package Git::SVN::GlobSpec;
6007 use strict;
6008 use warnings;
6010 sub new {
6011         my ($class, $glob, $pattern_ok) = @_;
6012         my $re = $glob;
6013         $re =~ s!/+$!!g; # no need for trailing slashes
6014         my (@left, @right, @patterns);
6015         my $state = "left";
6016         my $die_msg = "Only one set of wildcard directories " .
6017                                 "(e.g. '*' or '*/*/*') is supported: '$glob'\n";
6018         for my $part (split(m|/|, $glob)) {
6019                 if ($part =~ /\*/ && $part ne "*") {
6020                         die "Invalid pattern in '$glob': $part\n";
6021                 } elsif ($pattern_ok && $part =~ /[{}]/ &&
6022                          $part !~ /^\{[^{}]+\}/) {
6023                         die "Invalid pattern in '$glob': $part\n";
6024                 }
6025                 if ($part eq "*") {
6026                         die $die_msg if $state eq "right";
6027                         $state = "pattern";
6028                         push(@patterns, "[^/]*");
6029                 } elsif ($pattern_ok && $part =~ /^\{(.*)\}$/) {
6030                         die $die_msg if $state eq "right";
6031                         $state = "pattern";
6032                         my $p = quotemeta($1);
6033                         $p =~ s/\\,/|/g;
6034                         push(@patterns, "(?:$p)");
6035                 } else {
6036                         if ($state eq "left") {
6037                                 push(@left, $part);
6038                         } else {
6039                                 push(@right, $part);
6040                                 $state = "right";
6041                         }
6042                 }
6043         }
6044         my $depth = @patterns;
6045         if ($depth == 0) {
6046                 die "One '*' is needed in glob: '$glob'\n";
6047         }
6048         my $left = join('/', @left);
6049         my $right = join('/', @right);
6050         $re = join('/', @patterns);
6051         $re = join('\/',
6052                    grep(length, quotemeta($left), "($re)", quotemeta($right)));
6053         my $left_re = qr/^\/\Q$left\E(\/|$)/;
6054         bless { left => $left, right => $right, left_regex => $left_re,
6055                 regex => qr/$re/, glob => $glob, depth => $depth }, $class;
6058 sub full_path {
6059         my ($self, $path) = @_;
6060         return (length $self->{left} ? "$self->{left}/" : '') .
6061                $path . (length $self->{right} ? "/$self->{right}" : '');
6064 __END__
6066 Data structures:
6069 $remotes = { # returned by read_all_remotes()
6070         'svn' => {
6071                 # svn-remote.svn.url=https://svn.musicpd.org
6072                 url => 'https://svn.musicpd.org',
6073                 # svn-remote.svn.fetch=mpd/trunk:trunk
6074                 fetch => {
6075                         'mpd/trunk' => 'trunk',
6076                 },
6077                 # svn-remote.svn.tags=mpd/tags/*:tags/*
6078                 tags => {
6079                         path => {
6080                                 left => 'mpd/tags',
6081                                 right => '',
6082                                 regex => qr!mpd/tags/([^/]+)$!,
6083                                 glob => 'tags/*',
6084                         },
6085                         ref => {
6086                                 left => 'tags',
6087                                 right => '',
6088                                 regex => qr!tags/([^/]+)$!,
6089                                 glob => 'tags/*',
6090                         },
6091                 }
6092         }
6093 };
6095 $log_entry hashref as returned by libsvn_log_entry()
6097         log => 'whitespace-formatted log entry
6098 ',                                              # trailing newline is preserved
6099         revision => '8',                        # integer
6100         date => '2004-02-24T17:01:44.108345Z',  # commit date
6101         author => 'committer name'
6102 };
6105 # this is generated by generate_diff();
6106 @mods = array of diff-index line hashes, each element represents one line
6107         of diff-index output
6109 diff-index line ($m hash)
6111         mode_a => first column of diff-index output, no leading ':',
6112         mode_b => second column of diff-index output,
6113         sha1_b => sha1sum of the final blob,
6114         chg => change type [MCRADT],
6115         file_a => original file name of a file (iff chg is 'C' or 'R')
6116         file_b => new/current file name of a file (any chg)
6120 # retval of read_url_paths{,_all}();
6121 $l_map = {
6122         # repository root url
6123         'https://svn.musicpd.org' => {
6124                 # repository path               # GIT_SVN_ID
6125                 'mpd/trunk'             =>      'trunk',
6126                 'mpd/tags/0.11.5'       =>      'tags/0.11.5',
6127         },
6130 Notes:
6131         I don't trust the each() function on unless I created %hash myself
6132         because the internal iterator may not have started at base.