Code

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